repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
} } public static void removeLocation(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(LONGITUDE_PARAM).apply(); getSharedPreferences(context).edit().remove(LATITUDE_PARAM).apply(); } } public static boolean isTrainingFragmentShown() { //TODO: change to return real value when Training will be Implemented. return true; //return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0); } public static void setTrainingFragmentShown(Context context, int i) { synchronized (monitor) { getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply(); } } public static void removeTrainingFragmentShown(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply(); } } public static void setBanResetAt(Context context, long resetAt) { synchronized (monitor) {
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; } } public static void removeLocation(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(LONGITUDE_PARAM).apply(); getSharedPreferences(context).edit().remove(LATITUDE_PARAM).apply(); } } public static boolean isTrainingFragmentShown() { //TODO: change to return real value when Training will be Implemented. return true; //return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0); } public static void setTrainingFragmentShown(Context context, int i) { synchronized (monitor) { getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply(); } } public static void removeTrainingFragmentShown(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply(); } } public static void setBanResetAt(Context context, long resetAt) { synchronized (monitor) {
getSharedPreferences(context).edit().putLong(BAN_RESET_AT, resetAt).apply();
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
return true; //return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0); } public static void setTrainingFragmentShown(Context context, int i) { synchronized (monitor) { getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply(); } } public static void removeTrainingFragmentShown(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply(); } } public static void setBanResetAt(Context context, long resetAt) { synchronized (monitor) { getSharedPreferences(context).edit().putLong(BAN_RESET_AT, resetAt).apply(); } } public static long getBanResetAt(Context context) { synchronized (monitor) { return getSharedPreferences(context).getLong(BAN_RESET_AT, 0L); } } private static SharedPreferences getSharedPreferences(Context context) { synchronized (monitor) {
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; return true; //return 1 == getSharedPreferences().getInt(Constants.TRAINING_FRAGMENT_SHOWN, 0); } public static void setTrainingFragmentShown(Context context, int i) { synchronized (monitor) { getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply(); } } public static void removeTrainingFragmentShown(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply(); } } public static void setBanResetAt(Context context, long resetAt) { synchronized (monitor) { getSharedPreferences(context).edit().putLong(BAN_RESET_AT, resetAt).apply(); } } public static long getBanResetAt(Context context) { synchronized (monitor) { return getSharedPreferences(context).getLong(BAN_RESET_AT, 0L); } } private static SharedPreferences getSharedPreferences(Context context) { synchronized (monitor) {
return context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply(); } } public static void removeTrainingFragmentShown(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply(); } } public static void setBanResetAt(Context context, long resetAt) { synchronized (monitor) { getSharedPreferences(context).edit().putLong(BAN_RESET_AT, resetAt).apply(); } } public static long getBanResetAt(Context context) { synchronized (monitor) { return getSharedPreferences(context).getLong(BAN_RESET_AT, 0L); } } private static SharedPreferences getSharedPreferences(Context context) { synchronized (monitor) { return context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); } } public static String getFirebaseInstanceId(Context context) { synchronized (monitor) {
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; getSharedPreferences(context).edit().putInt(TRAINING_FRAGMENT_SHOWN, i).apply(); } } public static void removeTrainingFragmentShown(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(TRAINING_FRAGMENT_SHOWN).apply(); } } public static void setBanResetAt(Context context, long resetAt) { synchronized (monitor) { getSharedPreferences(context).edit().putLong(BAN_RESET_AT, resetAt).apply(); } } public static long getBanResetAt(Context context) { synchronized (monitor) { return getSharedPreferences(context).getLong(BAN_RESET_AT, 0L); } } private static SharedPreferences getSharedPreferences(Context context) { synchronized (monitor) { return context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); } } public static String getFirebaseInstanceId(Context context) { synchronized (monitor) {
return getSharedPreferences(context).getString(FIREBASE_INSTANCE_ID, FIREBASE_INSTANCE_ID_DEFAULT_VALUE);
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
} private static SharedPreferences getSharedPreferences(Context context) { synchronized (monitor) { return context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); } } public static String getFirebaseInstanceId(Context context) { synchronized (monitor) { return getSharedPreferences(context).getString(FIREBASE_INSTANCE_ID, FIREBASE_INSTANCE_ID_DEFAULT_VALUE); } } public static void setFirebaseInstanceId(Context context, String token) { if (token != null) { synchronized (monitor) { getSharedPreferences(context).edit().putString(FIREBASE_INSTANCE_ID, token).apply(); } } } public static void removeFirebaseInstanceId(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(FIREBASE_INSTANCE_ID).apply(); } } public static Facing getCameraFacing(Context context) { synchronized (monitor) {
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; } private static SharedPreferences getSharedPreferences(Context context) { synchronized (monitor) { return context.getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); } } public static String getFirebaseInstanceId(Context context) { synchronized (monitor) { return getSharedPreferences(context).getString(FIREBASE_INSTANCE_ID, FIREBASE_INSTANCE_ID_DEFAULT_VALUE); } } public static void setFirebaseInstanceId(Context context, String token) { if (token != null) { synchronized (monitor) { getSharedPreferences(context).edit().putString(FIREBASE_INSTANCE_ID, token).apply(); } } } public static void removeFirebaseInstanceId(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(FIREBASE_INSTANCE_ID).apply(); } } public static Facing getCameraFacing(Context context) { synchronized (monitor) {
Facing facing = Facing.valueOf(getSharedPreferences(context).getString(CAMERA_FACING_STRING, Facing.BACK.name()));
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
if (token != null) { synchronized (monitor) { getSharedPreferences(context).edit().putString(FIREBASE_INSTANCE_ID, token).apply(); } } } public static void removeFirebaseInstanceId(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(FIREBASE_INSTANCE_ID).apply(); } } public static Facing getCameraFacing(Context context) { synchronized (monitor) { Facing facing = Facing.valueOf(getSharedPreferences(context).getString(CAMERA_FACING_STRING, Facing.BACK.name())); return facing; } } public static void setCameraFacing(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FACING_STRING, facing.name()).apply(); } } } public static Grid getCameraGrid(Context context) { synchronized (monitor) {
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; if (token != null) { synchronized (monitor) { getSharedPreferences(context).edit().putString(FIREBASE_INSTANCE_ID, token).apply(); } } } public static void removeFirebaseInstanceId(Context context) { synchronized (monitor) { getSharedPreferences(context).edit().remove(FIREBASE_INSTANCE_ID).apply(); } } public static Facing getCameraFacing(Context context) { synchronized (monitor) { Facing facing = Facing.valueOf(getSharedPreferences(context).getString(CAMERA_FACING_STRING, Facing.BACK.name())); return facing; } } public static void setCameraFacing(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FACING_STRING, facing.name()).apply(); } } } public static Grid getCameraGrid(Context context) { synchronized (monitor) {
return Grid.valueOf(getSharedPreferences(context).getString(CAMERA_GRID_STRING, Grid.OFF.name()));
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
public static Facing getCameraFacing(Context context) { synchronized (monitor) { Facing facing = Facing.valueOf(getSharedPreferences(context).getString(CAMERA_FACING_STRING, Facing.BACK.name())); return facing; } } public static void setCameraFacing(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FACING_STRING, facing.name()).apply(); } } } public static Grid getCameraGrid(Context context) { synchronized (monitor) { return Grid.valueOf(getSharedPreferences(context).getString(CAMERA_GRID_STRING, Grid.OFF.name())); } } public static void setCameraGrid(Context context, Grid cameraGrid) { synchronized (monitor) { getSharedPreferences(context).edit().putString(CAMERA_GRID_STRING, cameraGrid.name()).apply(); } } public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) {
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; public static Facing getCameraFacing(Context context) { synchronized (monitor) { Facing facing = Facing.valueOf(getSharedPreferences(context).getString(CAMERA_FACING_STRING, Facing.BACK.name())); return facing; } } public static void setCameraFacing(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FACING_STRING, facing.name()).apply(); } } } public static Grid getCameraGrid(Context context) { synchronized (monitor) { return Grid.valueOf(getSharedPreferences(context).getString(CAMERA_GRID_STRING, Grid.OFF.name())); } } public static void setCameraGrid(Context context, Grid cameraGrid) { synchronized (monitor) { getSharedPreferences(context).edit().putString(CAMERA_GRID_STRING, cameraGrid.name()).apply(); } } public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) {
return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name()));
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
public static void setCameraGrid(Context context, Grid cameraGrid) { synchronized (monitor) { getSharedPreferences(context).edit().putString(CAMERA_GRID_STRING, cameraGrid.name()).apply(); } } public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name())); } else { return Flash.OFF; } } } public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) { synchronized (monitor) { if (flashMode != null && facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply(); } } } public static void removeCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply(); } }
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; public static void setCameraGrid(Context context, Grid cameraGrid) { synchronized (monitor) { getSharedPreferences(context).edit().putString(CAMERA_GRID_STRING, cameraGrid.name()).apply(); } } public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name())); } else { return Flash.OFF; } } } public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) { synchronized (monitor) { if (flashMode != null && facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply(); } } } public static void removeCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply(); } }
public static void setUserStatistics(Context context, Statistics statistics) {
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
} } public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name())); } else { return Flash.OFF; } } } public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) { synchronized (monitor) { if (flashMode != null && facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply(); } } } public static void removeCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply(); } } public static void setUserStatistics(Context context, Statistics statistics) { synchronized (monitor) { if (statistics != null) {
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; } } public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name())); } else { return Flash.OFF; } } } public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) { synchronized (monitor) { if (flashMode != null && facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply(); } } } public static void removeCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply(); } } public static void setUserStatistics(Context context, Statistics statistics) { synchronized (monitor) { if (statistics != null) {
getSharedPreferences(context).edit().putInt(USER_STATISTICS_LIKES, statistics.getLikes()).apply();
RandoApp/Rando-android
src/main/java/com/github/randoapp/preferences/Preferences.java
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes";
import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES;
} public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name())); } else { return Flash.OFF; } } } public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) { synchronized (monitor) { if (flashMode != null && facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply(); } } } public static void removeCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply(); } } public static void setUserStatistics(Context context, Statistics statistics) { synchronized (monitor) { if (statistics != null) { getSharedPreferences(context).edit().putInt(USER_STATISTICS_LIKES, statistics.getLikes()).apply();
// Path: src/main/java/com/github/randoapp/db/model/Statistics.java // public class Statistics implements Serializable { // private int likes; // private int dislikes; // // public static Statistics of(int likes, int dislikes) { // Statistics statistics = new Statistics(); // statistics.likes = likes; // statistics.dislikes = dislikes; // return statistics; // } // // public static Statistics from(JSONObject obj) { // Statistics statistics = new Statistics(); // try { // statistics.likes = obj.has(Constants.USER_STATISTICS_LIKES) ? obj.getInt(Constants.USER_STATISTICS_LIKES) : 0; // statistics.dislikes = obj.has(Constants.USER_STATISTICS_DISLIKES) ? obj.getInt(Constants.USER_STATISTICS_DISLIKES) : 0; // } catch (JSONException e) { // e.printStackTrace(); // } // return statistics; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getDislikes() { // return dislikes; // } // // public void setDislikes(int dislikes) { // this.dislikes = dislikes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String ACCOUNT = "account"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String AUTH_TOKEN = "auth.token"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String BAN_RESET_AT = "main.ban.reset.at"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FACING_STRING = "camera.facing.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_FLASH_MODE = "camera.flash.mode"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_GRID_STRING = "camera.grid.string"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String FIREBASE_INSTANCE_ID = "firebase.instance.id"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LATITUDE_PARAM = "latitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LOCATION = "location"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String LONGITUDE_PARAM = "longitude"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String PREFERENCES_FILE_NAME = "rando.prefs"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String TRAINING_FRAGMENT_SHOWN = "training.fragment.shown"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_DISLIKES = "dislikes"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String USER_STATISTICS_LIKES = "likes"; // Path: src/main/java/com/github/randoapp/preferences/Preferences.java import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import com.github.randoapp.db.model.Statistics; import com.otaliastudios.cameraview.Facing; import com.otaliastudios.cameraview.Flash; import com.otaliastudios.cameraview.Grid; import static com.github.randoapp.Constants.ACCOUNT; import static com.github.randoapp.Constants.AUTH_TOKEN; import static com.github.randoapp.Constants.BAN_RESET_AT; import static com.github.randoapp.Constants.CAMERA_FACING_STRING; import static com.github.randoapp.Constants.CAMERA_FLASH_MODE; import static com.github.randoapp.Constants.CAMERA_GRID_STRING; import static com.github.randoapp.Constants.FIREBASE_INSTANCE_ID; import static com.github.randoapp.Constants.LATITUDE_PARAM; import static com.github.randoapp.Constants.LOCATION; import static com.github.randoapp.Constants.LONGITUDE_PARAM; import static com.github.randoapp.Constants.PREFERENCES_FILE_NAME; import static com.github.randoapp.Constants.TRAINING_FRAGMENT_SHOWN; import static com.github.randoapp.Constants.USER_STATISTICS_DISLIKES; import static com.github.randoapp.Constants.USER_STATISTICS_LIKES; } public static Flash getCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { if (facing != null) { return Flash.valueOf(getSharedPreferences(context).getString(CAMERA_FLASH_MODE + facing.name(), Flash.OFF.name())); } else { return Flash.OFF; } } } public static void setCameraFlashMode(Context context, Facing facing, Flash flashMode) { synchronized (monitor) { if (flashMode != null && facing != null) { getSharedPreferences(context).edit().putString(CAMERA_FLASH_MODE + facing.name(), flashMode.name()).apply(); } } } public static void removeCameraFlashMode(Context context, Facing facing) { synchronized (monitor) { getSharedPreferences(context).edit().remove(CAMERA_FLASH_MODE + facing.name()).apply(); } } public static void setUserStatistics(Context context, Statistics statistics) { synchronized (monitor) { if (statistics != null) { getSharedPreferences(context).edit().putInt(USER_STATISTICS_LIKES, statistics.getLikes()).apply();
getSharedPreferences(context).edit().putInt(USER_STATISTICS_DISLIKES, statistics.getDislikes()).apply();
RandoApp/Rando-android
src/main/java/com/github/randoapp/task/CropToSquareImageTask.java
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH";
import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH;
File file = saveBitmap(resultedBitmap); if (bitmap.get()!= null) { bitmap.get().recycle(); } bitmap.clear(); resultedBitmap.recycle(); return file; } private WeakReference<Bitmap> decodeSquare(WeakReference<byte[]> data, BitmapFactory.Options options) { int size = Math.min(options.outWidth, options.outHeight); //We need to crop square image from the center of the image int indent = (Math.max(options.outWidth, options.outHeight) - size) / 2; Rect rect; if (options.outHeight >= options.outWidth) { rect = new Rect(0, indent, size, size + indent); } else { rect = new Rect(indent, 0, size + indent, size); } options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; WeakReference<Bitmap> result; try { BitmapRegionDecoder regionDecoder = BitmapRegionDecoder.newInstance(data.get(), 0, data.get().length, true); result = new WeakReference<>(regionDecoder.decodeRegion(rect, options)); regionDecoder.recycle(); } catch (IOException ex) {
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH"; // Path: src/main/java/com/github/randoapp/task/CropToSquareImageTask.java import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH; File file = saveBitmap(resultedBitmap); if (bitmap.get()!= null) { bitmap.get().recycle(); } bitmap.clear(); resultedBitmap.recycle(); return file; } private WeakReference<Bitmap> decodeSquare(WeakReference<byte[]> data, BitmapFactory.Options options) { int size = Math.min(options.outWidth, options.outHeight); //We need to crop square image from the center of the image int indent = (Math.max(options.outWidth, options.outHeight) - size) / 2; Rect rect; if (options.outHeight >= options.outWidth) { rect = new Rect(0, indent, size, size + indent); } else { rect = new Rect(indent, 0, size + indent, size); } options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; WeakReference<Bitmap> result; try { BitmapRegionDecoder regionDecoder = BitmapRegionDecoder.newInstance(data.get(), 0, data.get().length, true); result = new WeakReference<>(regionDecoder.decodeRegion(rect, options)); regionDecoder.recycle(); } catch (IOException ex) {
Log.e(CropToSquareImageTask.class, "exception creating BitmapRegionDecoder", ex);
RandoApp/Rando-android
src/main/java/com/github/randoapp/task/CropToSquareImageTask.java
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH";
import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH;
Log.e(CropToSquareImageTask.class, "Exception parsing JPEG Exif", e); // TODO: ripple to client } if (exifInterface != null) { int orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); Log.d(CropToSquareImageTask.class, "Orientation: " + orientation); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_UNDEFINED: rotation = 0; break; default: break; } } return rotation; } private File saveBitmap(Bitmap bitmap) { try {
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH"; // Path: src/main/java/com/github/randoapp/task/CropToSquareImageTask.java import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH; Log.e(CropToSquareImageTask.class, "Exception parsing JPEG Exif", e); // TODO: ripple to client } if (exifInterface != null) { int orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); Log.d(CropToSquareImageTask.class, "Orientation: " + orientation); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: rotation = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: rotation = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: rotation = 270; break; case ExifInterface.ORIENTATION_NORMAL: case ExifInterface.ORIENTATION_UNDEFINED: rotation = 0; break; default: break; } } return rotation; } private File saveBitmap(Bitmap bitmap) { try {
File file = FileUtil.getOutputMediaFile();
RandoApp/Rando-android
src/main/java/com/github/randoapp/task/CropToSquareImageTask.java
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH";
import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH;
case ExifInterface.ORIENTATION_UNDEFINED: rotation = 0; break; default: break; } } return rotation; } private File saveBitmap(Bitmap bitmap) { try { File file = FileUtil.getOutputMediaFile(); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos); fos.close(); Log.d(CropToSquareImageTask.class, "Camera Pic Processed."); return file; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override public void run() { File image = saveSquareImage();
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH"; // Path: src/main/java/com/github/randoapp/task/CropToSquareImageTask.java import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH; case ExifInterface.ORIENTATION_UNDEFINED: rotation = 0; break; default: break; } } return rotation; } private File saveBitmap(Bitmap bitmap) { try { File file = FileUtil.getOutputMediaFile(); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos); fos.close(); Log.d(CropToSquareImageTask.class, "Camera Pic Processed."); return file; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override public void run() { File image = saveSquareImage();
Intent intent = new Intent(CAMERA_BROADCAST_EVENT);
RandoApp/Rando-android
src/main/java/com/github/randoapp/task/CropToSquareImageTask.java
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH";
import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH;
break; default: break; } } return rotation; } private File saveBitmap(Bitmap bitmap) { try { File file = FileUtil.getOutputMediaFile(); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos); fos.close(); Log.d(CropToSquareImageTask.class, "Camera Pic Processed."); return file; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override public void run() { File image = saveSquareImage(); Intent intent = new Intent(CAMERA_BROADCAST_EVENT); if (image != null && !isCanceled.get()) {
// Path: src/main/java/com/github/randoapp/log/Log.java // public class Log { // // public static void i(Class clazz, String... msgs) { // android.util.Log.i(clazz.getName(), concatenate(msgs)); // } // // public static void d(Class clazz, String... msgs) { // android.util.Log.d(clazz.getName(), concatenate(msgs)); // } // // public static void w(Class clazz, String... msgs) { // android.util.Log.w(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String... msgs) { // android.util.Log.e(clazz.getName(), concatenate(msgs)); // } // // public static void e(Class clazz, String comment, Throwable throwable) { // android.util.Log.e(clazz.getName(), comment + " error:", throwable); // } // // public static void v(Class clazz, String... msgs) { // android.util.Log.v(clazz.getName(), concatenate(msgs)); // } // // private static String concatenate(String[] msgs) { // if (msgs == null) { // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (String msg : msgs) { // sb.append(msg).append(" "); // } // return sb.toString(); // } // // } // // Path: src/main/java/com/github/randoapp/util/FileUtil.java // public class FileUtil { // // public static File getOutputMediaDir() { // File mediaStorageDir = new File( // Environment // .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), // Constants.ALBUM_NAME); // if (!mediaStorageDir.exists()) { // if (!mediaStorageDir.mkdirs()) { // return null; // } // } // return mediaStorageDir; // } // // public static File getOutputMediaFile() { // Log.d(FileUtil.class, "getOutputMediaFile"); // // File mediaStorageDir = getOutputMediaDir(); // if (mediaStorageDir == null) { // return null; // } // // Create a media file name // String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") // .format(new Date()); // File mediaFile; // mediaFile = new File(mediaStorageDir.getPath() + File.separator // + Constants.IMAGE_PREFIX + timeStamp + Constants.IMAGE_POSTFIX); // return mediaFile; // } // // public static void removeFileIfExist(String filename) { // File file = new File(filename); // if (file.isFile()) { // file.delete(); // } // } // // public static byte[] readFile(File file) { // int size = (int) file.length(); // byte[] bytes = new byte[size]; // BufferedInputStream buf = null; // try { // buf = new BufferedInputStream(new FileInputStream(file)); // buf.read(bytes, 0, bytes.length); // } catch (FileNotFoundException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } catch (IOException e) { // Log.e(FileUtil.class, "Error Reading File", e); // } finally { // if (buf != null) { // try { // buf.close(); // } catch (IOException e) { // } // } // } // return bytes; // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String CAMERA_BROADCAST_EVENT = "RANDO_CAMERA_EVENT"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String RANDO_PHOTO_PATH = "RANDO_PHOTO_PATH"; // Path: src/main/java/com/github/randoapp/task/CropToSquareImageTask.java import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Matrix; import android.graphics.Rect; import android.support.media.ExifInterface; import android.support.v4.content.LocalBroadcastManager; import com.github.randoapp.log.Log; import com.github.randoapp.util.FileUtil; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.randoapp.Constants.CAMERA_BROADCAST_EVENT; import static com.github.randoapp.Constants.RANDO_PHOTO_PATH; break; default: break; } } return rotation; } private File saveBitmap(Bitmap bitmap) { try { File file = FileUtil.getOutputMediaFile(); FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos); fos.close(); Log.d(CropToSquareImageTask.class, "Camera Pic Processed."); return file; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override public void run() { File image = saveSquareImage(); Intent intent = new Intent(CAMERA_BROADCAST_EVENT); if (image != null && !isCanceled.get()) {
intent.putExtra(RANDO_PHOTO_PATH, image.getAbsolutePath());
RandoApp/Rando-android
src/main/java/com/github/randoapp/network/VolleySingleton.java
// Path: src/main/java/com/github/randoapp/cache/LruMemCache.java // public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / NUMBER_OF_IMAGES_FOR_CACHING; // // return cacheSize; // } // // public LruMemCache() { // this(getDefaultLruCacheSize()); // } // // public LruMemCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String DEFAULT_CACHE_DIR = "volley"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final int DEFAULT_CACHE_SIZE = 20 * 1024 * 1024;
import android.content.Context; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.github.randoapp.cache.LruMemCache; import java.io.File; import static com.github.randoapp.Constants.DEFAULT_CACHE_DIR; import static com.github.randoapp.Constants.DEFAULT_CACHE_SIZE;
package com.github.randoapp.network; public class VolleySingleton { private static VolleySingleton instance = null; private RequestQueue requestQueue; private ImageLoader imageLoader; private VolleySingleton(Context context) { requestQueue = createRequestQueue(context);
// Path: src/main/java/com/github/randoapp/cache/LruMemCache.java // public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / NUMBER_OF_IMAGES_FOR_CACHING; // // return cacheSize; // } // // public LruMemCache() { // this(getDefaultLruCacheSize()); // } // // public LruMemCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String DEFAULT_CACHE_DIR = "volley"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final int DEFAULT_CACHE_SIZE = 20 * 1024 * 1024; // Path: src/main/java/com/github/randoapp/network/VolleySingleton.java import android.content.Context; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.github.randoapp.cache.LruMemCache; import java.io.File; import static com.github.randoapp.Constants.DEFAULT_CACHE_DIR; import static com.github.randoapp.Constants.DEFAULT_CACHE_SIZE; package com.github.randoapp.network; public class VolleySingleton { private static VolleySingleton instance = null; private RequestQueue requestQueue; private ImageLoader imageLoader; private VolleySingleton(Context context) { requestQueue = createRequestQueue(context);
imageLoader = new ImageLoader(this.requestQueue, new LruMemCache());
RandoApp/Rando-android
src/main/java/com/github/randoapp/network/VolleySingleton.java
// Path: src/main/java/com/github/randoapp/cache/LruMemCache.java // public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / NUMBER_OF_IMAGES_FOR_CACHING; // // return cacheSize; // } // // public LruMemCache() { // this(getDefaultLruCacheSize()); // } // // public LruMemCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String DEFAULT_CACHE_DIR = "volley"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final int DEFAULT_CACHE_SIZE = 20 * 1024 * 1024;
import android.content.Context; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.github.randoapp.cache.LruMemCache; import java.io.File; import static com.github.randoapp.Constants.DEFAULT_CACHE_DIR; import static com.github.randoapp.Constants.DEFAULT_CACHE_SIZE;
package com.github.randoapp.network; public class VolleySingleton { private static VolleySingleton instance = null; private RequestQueue requestQueue; private ImageLoader imageLoader; private VolleySingleton(Context context) { requestQueue = createRequestQueue(context); imageLoader = new ImageLoader(this.requestQueue, new LruMemCache()); } public static VolleySingleton getInstance(Context context) { if (instance == null) { instance = new VolleySingleton(context); } return instance; } public RequestQueue getRequestQueue() { return requestQueue; } public ImageLoader getImageLoader() { return imageLoader; } private RequestQueue createRequestQueue(Context context) { if (context == null) { return null; }
// Path: src/main/java/com/github/randoapp/cache/LruMemCache.java // public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / NUMBER_OF_IMAGES_FOR_CACHING; // // return cacheSize; // } // // public LruMemCache() { // this(getDefaultLruCacheSize()); // } // // public LruMemCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String DEFAULT_CACHE_DIR = "volley"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final int DEFAULT_CACHE_SIZE = 20 * 1024 * 1024; // Path: src/main/java/com/github/randoapp/network/VolleySingleton.java import android.content.Context; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.github.randoapp.cache.LruMemCache; import java.io.File; import static com.github.randoapp.Constants.DEFAULT_CACHE_DIR; import static com.github.randoapp.Constants.DEFAULT_CACHE_SIZE; package com.github.randoapp.network; public class VolleySingleton { private static VolleySingleton instance = null; private RequestQueue requestQueue; private ImageLoader imageLoader; private VolleySingleton(Context context) { requestQueue = createRequestQueue(context); imageLoader = new ImageLoader(this.requestQueue, new LruMemCache()); } public static VolleySingleton getInstance(Context context) { if (instance == null) { instance = new VolleySingleton(context); } return instance; } public RequestQueue getRequestQueue() { return requestQueue; } public ImageLoader getImageLoader() { return imageLoader; } private RequestQueue createRequestQueue(Context context) { if (context == null) { return null; }
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
RandoApp/Rando-android
src/main/java/com/github/randoapp/network/VolleySingleton.java
// Path: src/main/java/com/github/randoapp/cache/LruMemCache.java // public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / NUMBER_OF_IMAGES_FOR_CACHING; // // return cacheSize; // } // // public LruMemCache() { // this(getDefaultLruCacheSize()); // } // // public LruMemCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String DEFAULT_CACHE_DIR = "volley"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final int DEFAULT_CACHE_SIZE = 20 * 1024 * 1024;
import android.content.Context; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.github.randoapp.cache.LruMemCache; import java.io.File; import static com.github.randoapp.Constants.DEFAULT_CACHE_DIR; import static com.github.randoapp.Constants.DEFAULT_CACHE_SIZE;
package com.github.randoapp.network; public class VolleySingleton { private static VolleySingleton instance = null; private RequestQueue requestQueue; private ImageLoader imageLoader; private VolleySingleton(Context context) { requestQueue = createRequestQueue(context); imageLoader = new ImageLoader(this.requestQueue, new LruMemCache()); } public static VolleySingleton getInstance(Context context) { if (instance == null) { instance = new VolleySingleton(context); } return instance; } public RequestQueue getRequestQueue() { return requestQueue; } public ImageLoader getImageLoader() { return imageLoader; } private RequestQueue createRequestQueue(Context context) { if (context == null) { return null; } File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); Network network = new BasicNetwork(new HurlStack());
// Path: src/main/java/com/github/randoapp/cache/LruMemCache.java // public class LruMemCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { // public static int getDefaultLruCacheSize() { // final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // final int cacheSize = maxMemory / NUMBER_OF_IMAGES_FOR_CACHING; // // return cacheSize; // } // // public LruMemCache() { // this(getDefaultLruCacheSize()); // } // // public LruMemCache(int sizeInKiloBytes) { // super(sizeInKiloBytes); // } // // @Override // protected int sizeOf(String key, Bitmap value) { // return value.getRowBytes() * value.getHeight() / 1024; // } // // @Override // public Bitmap getBitmap(String url) { // return get(url); // } // // @Override // public void putBitmap(String url, Bitmap bitmap) { // put(url, bitmap); // } // } // // Path: src/main/java/com/github/randoapp/Constants.java // public static final String DEFAULT_CACHE_DIR = "volley"; // // Path: src/main/java/com/github/randoapp/Constants.java // public static final int DEFAULT_CACHE_SIZE = 20 * 1024 * 1024; // Path: src/main/java/com/github/randoapp/network/VolleySingleton.java import android.content.Context; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; import com.github.randoapp.cache.LruMemCache; import java.io.File; import static com.github.randoapp.Constants.DEFAULT_CACHE_DIR; import static com.github.randoapp.Constants.DEFAULT_CACHE_SIZE; package com.github.randoapp.network; public class VolleySingleton { private static VolleySingleton instance = null; private RequestQueue requestQueue; private ImageLoader imageLoader; private VolleySingleton(Context context) { requestQueue = createRequestQueue(context); imageLoader = new ImageLoader(this.requestQueue, new LruMemCache()); } public static VolleySingleton getInstance(Context context) { if (instance == null) { instance = new VolleySingleton(context); } return instance; } public RequestQueue getRequestQueue() { return requestQueue; } public ImageLoader getImageLoader() { return imageLoader; } private RequestQueue createRequestQueue(Context context) { if (context == null) { return null; } File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); Network network = new BasicNetwork(new HurlStack());
RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir, DEFAULT_CACHE_SIZE), network);
sytolk/TaxiAndroidOpen
src/main/java/com/opentaxi/android/NetworkStateReceiver.java
// Path: src/main/java/com/opentaxi/android/utils/MessageEvent.java // public class MessageEvent { // public final String message; // // public MessageEvent(String message) { // this.message = message; // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import com.opentaxi.android.utils.MessageEvent; import com.opentaxi.rest.RestClient; import de.greenrobot.event.EventBus;
package com.opentaxi.android; /** * Created with IntelliJ IDEA. * User: stanimir * Date: 11/8/13 * Time: 12:16 PM * developer STANIMIR MARINOV */ public class NetworkStateReceiver extends BroadcastReceiver { /** * if (bandwidth > 16) Code for large items * if (bandwidth <= 16 && bandwidth > 8) Code for medium items * else Code for small items */ public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null) { if (activeNetInfo.isConnected()) { StringBuilder network = new StringBuilder(); if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); network.append(activeNetInfo.getTypeName()).append(" ").append(wm.getConnectionInfo().getLinkSpeed()).append("Mbps"); } else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); network.append(activeNetInfo.getTypeName()).append(" ").append(getNetworkTypeName(tm.getNetworkType())); } //else RestClient.getInstance().setBandwidth(0); onConnected(network.toString()); } else onDisconnected(); } else onDisconnected(); } private void onConnected(String typeName) { RestClient.getInstance().setHaveConnection(true);
// Path: src/main/java/com/opentaxi/android/utils/MessageEvent.java // public class MessageEvent { // public final String message; // // public MessageEvent(String message) { // this.message = message; // } // } // Path: src/main/java/com/opentaxi/android/NetworkStateReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import com.opentaxi.android.utils.MessageEvent; import com.opentaxi.rest.RestClient; import de.greenrobot.event.EventBus; package com.opentaxi.android; /** * Created with IntelliJ IDEA. * User: stanimir * Date: 11/8/13 * Time: 12:16 PM * developer STANIMIR MARINOV */ public class NetworkStateReceiver extends BroadcastReceiver { /** * if (bandwidth > 16) Code for large items * if (bandwidth <= 16 && bandwidth > 8) Code for medium items * else Code for small items */ public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null) { if (activeNetInfo.isConnected()) { StringBuilder network = new StringBuilder(); if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); network.append(activeNetInfo.getTypeName()).append(" ").append(wm.getConnectionInfo().getLinkSpeed()).append("Mbps"); } else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); network.append(activeNetInfo.getTypeName()).append(" ").append(getNetworkTypeName(tm.getNetworkType())); } //else RestClient.getInstance().setBandwidth(0); onConnected(network.toString()); } else onDisconnected(); } else onDisconnected(); } private void onConnected(String typeName) { RestClient.getInstance().setHaveConnection(true);
EventBus.getDefault().postSticky(new MessageEvent(typeName));
sytolk/TaxiAndroidOpen
src/main/java/com/opentaxi/android/gcm/GCMRegisterService.java
// Path: src/main/java/com/opentaxi/android/TaxiApplication.java // @ReportsCrashes(logcatFilterByPid = true) //formKey = "", // public class TaxiApplication extends Application { //extends MultiDexApplication { // // public static String gcmId = ""; // //private static boolean havePlayService = true; // private static boolean requestsVisible = false; // //private static boolean requestsHistory = false; // //private static boolean requestsDetailsVisible = false; // private static boolean userPassVisible = false; // private static boolean mapVisible = false; // private static Integer lastRequestId; // private static boolean versionSend = false; // private static boolean serversUpdated = false; // private static boolean msgVisible = false; // private static String GCMRegistrationId; // // /*public static void setHavePlayService(boolean havePlayService) { // TaxiApplication.havePlayService = havePlayService; // } // // public static boolean isHavePlayService() { // return havePlayService; // }*/ // // public static boolean isRequestsVisible() { // return requestsVisible; // } // // public static void requestsResumed() { // requestsVisible = true; // } // // public static void requestsPaused() { // requestsVisible = false; // } // // /*public static boolean isRequestsDetailsVisible() { // return requestsDetailsVisible; // } // // public static void requestsDetailsResumed() { // requestsDetailsVisible = true; // } // // public static void requestsDetailsPaused() { // requestsDetailsVisible = false; // }*/ // // public static boolean isUserPassVisible() { // return userPassVisible; // } // // public static void userPassResumed() { // userPassVisible = true; // } // // public static void userPassPaused() { // userPassVisible = false; // } // // public static boolean isMapVisible() { // return mapVisible; // } // // public static void mapResumed() { // mapVisible = true; // } // // public static void mapPaused() { // mapVisible = false; // } // // public static Integer getLastRequestId() { // return lastRequestId; // } // // public static void setLastRequestId(Integer lastRequestId) { // TaxiApplication.lastRequestId = lastRequestId; // } // // public static boolean isVersionSend() { // return versionSend; // } // // public static void setVersionSend(boolean versionSend) { // TaxiApplication.versionSend = versionSend; // } // // public static boolean isServersUpdated() { // return serversUpdated; // } // // public static void setServersUpdated(boolean serversUpdated) { // TaxiApplication.serversUpdated = serversUpdated; // } // // public static boolean isMsgVisible() { // return msgVisible; // } // // public static void msgResumed() { // msgVisible = true; // } // // public static void msgPaused() { // msgVisible = false; // } // // public static String getGCMRegistrationId() { // return GCMRegistrationId; // } // // public static void setGCMRegistrationId(String GCMRegistrationId) { // TaxiApplication.GCMRegistrationId = GCMRegistrationId; // } // // @Override // public void onCreate() { // // /*try { // Class.forName("android.os.AsyncTask"); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // }*/ // // super.onCreate(); // //LeakCanary.install(this); // // Iconify.with(new MaterialModule()); // // FacebookSdk.sdkInitialize(getApplicationContext()); //this must be here! its have usage in MainActivity and UserPass // // //RestClient.getInstance().clearCache(); // // //AndroidGraphicFactory.createInstance(this); // // //Log.d("TaxiApplication", "onCreate()"); // // // The following line triggers the initialization of ACRA // ACRA.init(this); // CrashReportSender mySender = new CrashReportSender(); // ACRA.getErrorReporter().setReportSender(mySender); // // RestClient.getInstance().enableCache(getApplicationContext(), 1024L * 1024L * 5L); //5MB // //Iconics.registerFont(new GoogleMaterial()); // // /*// output debug to LogCat, with tag LittleFluffyLocationLibrary // //LocationLibrary.showDebugOutput(true); // // // in most cases the following initialising code using defaults is probably sufficient: // // // // LocationLibrary.initialiseLibrary(getBaseContext(), "com.opentaxi.android.service"); // // // // however for the purposes of the test app, we will request unrealistically frequent location broadcasts // // every 1 minute, and force a location update if there hasn't been one for 2 minutes. // LocationLibrary.initialiseLibrary(getBaseContext(), 30 * 1000, 60 * 1000, "com.opentaxi.android"); // LocationLibrary.useFineAccuracyForRequests(true); // LocationLibrary.showDebugOutput(true); // //LocationLibrary.forceLocationUpdate(getBaseContext()); // LocationLibrary.startAlarmAndListener(getBaseContext());*/ // } // }
import android.app.IntentService; import android.content.Intent; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import com.opentaxi.android.TaxiApplication; import com.opentaxi.rest.RestClient; import java.io.IOException;
package com.opentaxi.android.gcm; public class GCMRegisterService extends IntentService { public GCMRegisterService() { super("GCMRegisterService"); } @Override protected void onHandleIntent(Intent intent) { //Log.i("GCMRegisterService", "started"); InstanceID iid = InstanceID.getInstance(getApplicationContext()); try { String[] senderIds = RestClient.getInstance().getGCMsenderIds(); if (senderIds != null) { for (String sender : senderIds) { String token = iid.getToken(sender, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Boolean success = RestClient.getInstance().gcmRegister(token); if (success != null && !success) {
// Path: src/main/java/com/opentaxi/android/TaxiApplication.java // @ReportsCrashes(logcatFilterByPid = true) //formKey = "", // public class TaxiApplication extends Application { //extends MultiDexApplication { // // public static String gcmId = ""; // //private static boolean havePlayService = true; // private static boolean requestsVisible = false; // //private static boolean requestsHistory = false; // //private static boolean requestsDetailsVisible = false; // private static boolean userPassVisible = false; // private static boolean mapVisible = false; // private static Integer lastRequestId; // private static boolean versionSend = false; // private static boolean serversUpdated = false; // private static boolean msgVisible = false; // private static String GCMRegistrationId; // // /*public static void setHavePlayService(boolean havePlayService) { // TaxiApplication.havePlayService = havePlayService; // } // // public static boolean isHavePlayService() { // return havePlayService; // }*/ // // public static boolean isRequestsVisible() { // return requestsVisible; // } // // public static void requestsResumed() { // requestsVisible = true; // } // // public static void requestsPaused() { // requestsVisible = false; // } // // /*public static boolean isRequestsDetailsVisible() { // return requestsDetailsVisible; // } // // public static void requestsDetailsResumed() { // requestsDetailsVisible = true; // } // // public static void requestsDetailsPaused() { // requestsDetailsVisible = false; // }*/ // // public static boolean isUserPassVisible() { // return userPassVisible; // } // // public static void userPassResumed() { // userPassVisible = true; // } // // public static void userPassPaused() { // userPassVisible = false; // } // // public static boolean isMapVisible() { // return mapVisible; // } // // public static void mapResumed() { // mapVisible = true; // } // // public static void mapPaused() { // mapVisible = false; // } // // public static Integer getLastRequestId() { // return lastRequestId; // } // // public static void setLastRequestId(Integer lastRequestId) { // TaxiApplication.lastRequestId = lastRequestId; // } // // public static boolean isVersionSend() { // return versionSend; // } // // public static void setVersionSend(boolean versionSend) { // TaxiApplication.versionSend = versionSend; // } // // public static boolean isServersUpdated() { // return serversUpdated; // } // // public static void setServersUpdated(boolean serversUpdated) { // TaxiApplication.serversUpdated = serversUpdated; // } // // public static boolean isMsgVisible() { // return msgVisible; // } // // public static void msgResumed() { // msgVisible = true; // } // // public static void msgPaused() { // msgVisible = false; // } // // public static String getGCMRegistrationId() { // return GCMRegistrationId; // } // // public static void setGCMRegistrationId(String GCMRegistrationId) { // TaxiApplication.GCMRegistrationId = GCMRegistrationId; // } // // @Override // public void onCreate() { // // /*try { // Class.forName("android.os.AsyncTask"); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // }*/ // // super.onCreate(); // //LeakCanary.install(this); // // Iconify.with(new MaterialModule()); // // FacebookSdk.sdkInitialize(getApplicationContext()); //this must be here! its have usage in MainActivity and UserPass // // //RestClient.getInstance().clearCache(); // // //AndroidGraphicFactory.createInstance(this); // // //Log.d("TaxiApplication", "onCreate()"); // // // The following line triggers the initialization of ACRA // ACRA.init(this); // CrashReportSender mySender = new CrashReportSender(); // ACRA.getErrorReporter().setReportSender(mySender); // // RestClient.getInstance().enableCache(getApplicationContext(), 1024L * 1024L * 5L); //5MB // //Iconics.registerFont(new GoogleMaterial()); // // /*// output debug to LogCat, with tag LittleFluffyLocationLibrary // //LocationLibrary.showDebugOutput(true); // // // in most cases the following initialising code using defaults is probably sufficient: // // // // LocationLibrary.initialiseLibrary(getBaseContext(), "com.opentaxi.android.service"); // // // // however for the purposes of the test app, we will request unrealistically frequent location broadcasts // // every 1 minute, and force a location update if there hasn't been one for 2 minutes. // LocationLibrary.initialiseLibrary(getBaseContext(), 30 * 1000, 60 * 1000, "com.opentaxi.android"); // LocationLibrary.useFineAccuracyForRequests(true); // LocationLibrary.showDebugOutput(true); // //LocationLibrary.forceLocationUpdate(getBaseContext()); // LocationLibrary.startAlarmAndListener(getBaseContext());*/ // } // } // Path: src/main/java/com/opentaxi/android/gcm/GCMRegisterService.java import android.app.IntentService; import android.content.Intent; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import com.opentaxi.android.TaxiApplication; import com.opentaxi.rest.RestClient; import java.io.IOException; package com.opentaxi.android.gcm; public class GCMRegisterService extends IntentService { public GCMRegisterService() { super("GCMRegisterService"); } @Override protected void onHandleIntent(Intent intent) { //Log.i("GCMRegisterService", "started"); InstanceID iid = InstanceID.getInstance(getApplicationContext()); try { String[] senderIds = RestClient.getInstance().getGCMsenderIds(); if (senderIds != null) { for (String sender : senderIds) { String token = iid.getToken(sender, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Boolean success = RestClient.getInstance().gcmRegister(token); if (success != null && !success) {
TaxiApplication.setGCMRegistrationId(token);
sytolk/TaxiAndroidOpen
src/main/java/com/opentaxi/android/TaxiApplication.java
// Path: src/main/java/com/opentaxi/android/utils/CrashReportSender.java // public class CrashReportSender implements ReportSender { // // //private static final String BASE_URL = "https://rink.hockeyapp.net/api/2/apps/"; // //private static final String CRASHES_PATH = "/crashes"; // // @Override // public void send(Context context, CrashReportData report) throws ReportSenderException { // DebuggerLog log = new DebuggerLog(); // log.setAppVersionCode(Integer.parseInt(report.get(ReportField.APP_VERSION_CODE))); // log.setAppVersionName(report.get(ReportField.APP_VERSION_NAME)); // log.setPackageName(report.get(ReportField.PACKAGE_NAME)); // log.setFilePath(report.get(ReportField.FILE_PATH)); // log.setPhoneModel(report.get(ReportField.PHONE_MODEL)); // log.setBrand(report.get(ReportField.BRAND)); // log.setProduct(report.get(ReportField.PRODUCT)); // log.setAndroidVersion(report.get(ReportField.ANDROID_VERSION)); // log.setBuild(report.get(ReportField.BUILD)); // log.setTotalMemSize(report.get(ReportField.TOTAL_MEM_SIZE)); // log.setAvailableMemSize(report.get(ReportField.AVAILABLE_MEM_SIZE)); // log.setStackTrace(report.get(ReportField.STACK_TRACE)); // log.setInitialConfiguration(report.get(ReportField.INITIAL_CONFIGURATION)); // log.setCrashConfiguration(report.get(ReportField.CRASH_CONFIGURATION)); // log.setDisplay(report.get(ReportField.DISPLAY)); // DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // try { // log.setUserAppStartDate(new Timestamp(format.parse(report.get(ReportField.USER_APP_START_DATE)).getTime())); // log.setUserCrashDate(new Timestamp(format.parse(report.get(ReportField.USER_CRASH_DATE)).getTime())); // } catch (ParseException e) { // e.printStackTrace(); // } // log.setDumpsysMeminfo(report.get(ReportField.DUMPSYS_MEMINFO)); // log.setLogcat(report.get(ReportField.LOGCAT)); // log.setInstallationId(report.get(ReportField.INSTALLATION_ID)); // log.setDeviceFeatures(report.get(ReportField.DEVICE_FEATURES)); // log.setEnvironment(report.get(ReportField.ENVIRONMENT)); // log.setSharedPreferences(report.get(ReportField.SHARED_PREFERENCES)); // log.setSettingsSystem(report.get(ReportField.SETTINGS_SYSTEM)); // log.setSettingsSecure(report.get(ReportField.SETTINGS_SECURE)); // RestClient.getInstance().sendLog(log); // /*String log = createCrashLog(report); // Log.i("CrashReportSender", log); // String url = BASE_URL + ACRA.getConfig().formKey() + CRASHES_PATH; // // try { // DefaultHttpClient httpClient = new DefaultHttpClient(); // HttpPost httpPost = new HttpPost(url); // // List<NameValuePair> parameters = new ArrayList<NameValuePair>(); // parameters.add(new BasicNameValuePair("raw", log)); // parameters.add(new BasicNameValuePair("userID", report.get(ReportField.INSTALLATION_ID))); // parameters.add(new BasicNameValuePair("contact", report.get(ReportField.USER_EMAIL))); // parameters.add(new BasicNameValuePair("description", report.get(ReportField.USER_COMMENT))); // httpPost.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); // // httpClient.execute(httpPost); // } // catch (Exception e) { // e.printStackTrace(); // }*/ // } // // /*private String createCrashLog(CrashReportData report) { // Date now = new Date(); // StringBuilder log = new StringBuilder(); // log.append("Package: " + report.get(ReportField.PACKAGE_NAME) + "\n"); // log.append("Version: " + report.get(ReportField.APP_VERSION_CODE) + "\n"); // log.append("Android: " + report.get(ReportField.ANDROID_VERSION) + "\n"); // log.append("Manufacturer: " + android.os.Build.MANUFACTURER + "\n"); // log.append("Model: " + report.get(ReportField.PHONE_MODEL) + "\n"); // log.append("Date: " + now + "\n"); // log.append("\n"); // log.append(report.get(ReportField.STACK_TRACE)); // // return log.toString(); // }*/ // }
import android.app.Application; import com.facebook.FacebookSdk; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.MaterialModule; import com.opentaxi.android.utils.CrashReportSender; import com.opentaxi.rest.RestClient; import org.acra.ACRA; import org.acra.annotation.ReportsCrashes;
} public static void setGCMRegistrationId(String GCMRegistrationId) { TaxiApplication.GCMRegistrationId = GCMRegistrationId; } @Override public void onCreate() { /*try { Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { e.printStackTrace(); }*/ super.onCreate(); //LeakCanary.install(this); Iconify.with(new MaterialModule()); FacebookSdk.sdkInitialize(getApplicationContext()); //this must be here! its have usage in MainActivity and UserPass //RestClient.getInstance().clearCache(); //AndroidGraphicFactory.createInstance(this); //Log.d("TaxiApplication", "onCreate()"); // The following line triggers the initialization of ACRA ACRA.init(this);
// Path: src/main/java/com/opentaxi/android/utils/CrashReportSender.java // public class CrashReportSender implements ReportSender { // // //private static final String BASE_URL = "https://rink.hockeyapp.net/api/2/apps/"; // //private static final String CRASHES_PATH = "/crashes"; // // @Override // public void send(Context context, CrashReportData report) throws ReportSenderException { // DebuggerLog log = new DebuggerLog(); // log.setAppVersionCode(Integer.parseInt(report.get(ReportField.APP_VERSION_CODE))); // log.setAppVersionName(report.get(ReportField.APP_VERSION_NAME)); // log.setPackageName(report.get(ReportField.PACKAGE_NAME)); // log.setFilePath(report.get(ReportField.FILE_PATH)); // log.setPhoneModel(report.get(ReportField.PHONE_MODEL)); // log.setBrand(report.get(ReportField.BRAND)); // log.setProduct(report.get(ReportField.PRODUCT)); // log.setAndroidVersion(report.get(ReportField.ANDROID_VERSION)); // log.setBuild(report.get(ReportField.BUILD)); // log.setTotalMemSize(report.get(ReportField.TOTAL_MEM_SIZE)); // log.setAvailableMemSize(report.get(ReportField.AVAILABLE_MEM_SIZE)); // log.setStackTrace(report.get(ReportField.STACK_TRACE)); // log.setInitialConfiguration(report.get(ReportField.INITIAL_CONFIGURATION)); // log.setCrashConfiguration(report.get(ReportField.CRASH_CONFIGURATION)); // log.setDisplay(report.get(ReportField.DISPLAY)); // DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // try { // log.setUserAppStartDate(new Timestamp(format.parse(report.get(ReportField.USER_APP_START_DATE)).getTime())); // log.setUserCrashDate(new Timestamp(format.parse(report.get(ReportField.USER_CRASH_DATE)).getTime())); // } catch (ParseException e) { // e.printStackTrace(); // } // log.setDumpsysMeminfo(report.get(ReportField.DUMPSYS_MEMINFO)); // log.setLogcat(report.get(ReportField.LOGCAT)); // log.setInstallationId(report.get(ReportField.INSTALLATION_ID)); // log.setDeviceFeatures(report.get(ReportField.DEVICE_FEATURES)); // log.setEnvironment(report.get(ReportField.ENVIRONMENT)); // log.setSharedPreferences(report.get(ReportField.SHARED_PREFERENCES)); // log.setSettingsSystem(report.get(ReportField.SETTINGS_SYSTEM)); // log.setSettingsSecure(report.get(ReportField.SETTINGS_SECURE)); // RestClient.getInstance().sendLog(log); // /*String log = createCrashLog(report); // Log.i("CrashReportSender", log); // String url = BASE_URL + ACRA.getConfig().formKey() + CRASHES_PATH; // // try { // DefaultHttpClient httpClient = new DefaultHttpClient(); // HttpPost httpPost = new HttpPost(url); // // List<NameValuePair> parameters = new ArrayList<NameValuePair>(); // parameters.add(new BasicNameValuePair("raw", log)); // parameters.add(new BasicNameValuePair("userID", report.get(ReportField.INSTALLATION_ID))); // parameters.add(new BasicNameValuePair("contact", report.get(ReportField.USER_EMAIL))); // parameters.add(new BasicNameValuePair("description", report.get(ReportField.USER_COMMENT))); // httpPost.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8)); // // httpClient.execute(httpPost); // } // catch (Exception e) { // e.printStackTrace(); // }*/ // } // // /*private String createCrashLog(CrashReportData report) { // Date now = new Date(); // StringBuilder log = new StringBuilder(); // log.append("Package: " + report.get(ReportField.PACKAGE_NAME) + "\n"); // log.append("Version: " + report.get(ReportField.APP_VERSION_CODE) + "\n"); // log.append("Android: " + report.get(ReportField.ANDROID_VERSION) + "\n"); // log.append("Manufacturer: " + android.os.Build.MANUFACTURER + "\n"); // log.append("Model: " + report.get(ReportField.PHONE_MODEL) + "\n"); // log.append("Date: " + now + "\n"); // log.append("\n"); // log.append(report.get(ReportField.STACK_TRACE)); // // return log.toString(); // }*/ // } // Path: src/main/java/com/opentaxi/android/TaxiApplication.java import android.app.Application; import com.facebook.FacebookSdk; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.MaterialModule; import com.opentaxi.android.utils.CrashReportSender; import com.opentaxi.rest.RestClient; import org.acra.ACRA; import org.acra.annotation.ReportsCrashes; } public static void setGCMRegistrationId(String GCMRegistrationId) { TaxiApplication.GCMRegistrationId = GCMRegistrationId; } @Override public void onCreate() { /*try { Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { e.printStackTrace(); }*/ super.onCreate(); //LeakCanary.install(this); Iconify.with(new MaterialModule()); FacebookSdk.sdkInitialize(getApplicationContext()); //this must be here! its have usage in MainActivity and UserPass //RestClient.getInstance().clearCache(); //AndroidGraphicFactory.createInstance(this); //Log.d("TaxiApplication", "onCreate()"); // The following line triggers the initialization of ACRA ACRA.init(this);
CrashReportSender mySender = new CrashReportSender();
sytolk/TaxiAndroidOpen
src/main/java/com/opentaxi/android/gcm/InstanceIdListener.java
// Path: src/main/java/com/opentaxi/android/TaxiApplication.java // @ReportsCrashes(logcatFilterByPid = true) //formKey = "", // public class TaxiApplication extends Application { //extends MultiDexApplication { // // public static String gcmId = ""; // //private static boolean havePlayService = true; // private static boolean requestsVisible = false; // //private static boolean requestsHistory = false; // //private static boolean requestsDetailsVisible = false; // private static boolean userPassVisible = false; // private static boolean mapVisible = false; // private static Integer lastRequestId; // private static boolean versionSend = false; // private static boolean serversUpdated = false; // private static boolean msgVisible = false; // private static String GCMRegistrationId; // // /*public static void setHavePlayService(boolean havePlayService) { // TaxiApplication.havePlayService = havePlayService; // } // // public static boolean isHavePlayService() { // return havePlayService; // }*/ // // public static boolean isRequestsVisible() { // return requestsVisible; // } // // public static void requestsResumed() { // requestsVisible = true; // } // // public static void requestsPaused() { // requestsVisible = false; // } // // /*public static boolean isRequestsDetailsVisible() { // return requestsDetailsVisible; // } // // public static void requestsDetailsResumed() { // requestsDetailsVisible = true; // } // // public static void requestsDetailsPaused() { // requestsDetailsVisible = false; // }*/ // // public static boolean isUserPassVisible() { // return userPassVisible; // } // // public static void userPassResumed() { // userPassVisible = true; // } // // public static void userPassPaused() { // userPassVisible = false; // } // // public static boolean isMapVisible() { // return mapVisible; // } // // public static void mapResumed() { // mapVisible = true; // } // // public static void mapPaused() { // mapVisible = false; // } // // public static Integer getLastRequestId() { // return lastRequestId; // } // // public static void setLastRequestId(Integer lastRequestId) { // TaxiApplication.lastRequestId = lastRequestId; // } // // public static boolean isVersionSend() { // return versionSend; // } // // public static void setVersionSend(boolean versionSend) { // TaxiApplication.versionSend = versionSend; // } // // public static boolean isServersUpdated() { // return serversUpdated; // } // // public static void setServersUpdated(boolean serversUpdated) { // TaxiApplication.serversUpdated = serversUpdated; // } // // public static boolean isMsgVisible() { // return msgVisible; // } // // public static void msgResumed() { // msgVisible = true; // } // // public static void msgPaused() { // msgVisible = false; // } // // public static String getGCMRegistrationId() { // return GCMRegistrationId; // } // // public static void setGCMRegistrationId(String GCMRegistrationId) { // TaxiApplication.GCMRegistrationId = GCMRegistrationId; // } // // @Override // public void onCreate() { // // /*try { // Class.forName("android.os.AsyncTask"); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // }*/ // // super.onCreate(); // //LeakCanary.install(this); // // Iconify.with(new MaterialModule()); // // FacebookSdk.sdkInitialize(getApplicationContext()); //this must be here! its have usage in MainActivity and UserPass // // //RestClient.getInstance().clearCache(); // // //AndroidGraphicFactory.createInstance(this); // // //Log.d("TaxiApplication", "onCreate()"); // // // The following line triggers the initialization of ACRA // ACRA.init(this); // CrashReportSender mySender = new CrashReportSender(); // ACRA.getErrorReporter().setReportSender(mySender); // // RestClient.getInstance().enableCache(getApplicationContext(), 1024L * 1024L * 5L); //5MB // //Iconics.registerFont(new GoogleMaterial()); // // /*// output debug to LogCat, with tag LittleFluffyLocationLibrary // //LocationLibrary.showDebugOutput(true); // // // in most cases the following initialising code using defaults is probably sufficient: // // // // LocationLibrary.initialiseLibrary(getBaseContext(), "com.opentaxi.android.service"); // // // // however for the purposes of the test app, we will request unrealistically frequent location broadcasts // // every 1 minute, and force a location update if there hasn't been one for 2 minutes. // LocationLibrary.initialiseLibrary(getBaseContext(), 30 * 1000, 60 * 1000, "com.opentaxi.android"); // LocationLibrary.useFineAccuracyForRequests(true); // LocationLibrary.showDebugOutput(true); // //LocationLibrary.forceLocationUpdate(getBaseContext()); // LocationLibrary.startAlarmAndListener(getBaseContext());*/ // } // }
import android.content.Intent; import com.google.android.gms.iid.InstanceIDListenerService; import com.opentaxi.android.TaxiApplication;
package com.opentaxi.android.gcm; /** * Created by stanimir on 12/31/15. */ public class InstanceIdListener extends InstanceIDListenerService { /** * Fetch updated Instance ID token and notify our app's server of any changes (if applicable). */ @Override public void onTokenRefresh() { //Log.i("onTokenRefresh", "Token:" + TaxiApplication.getGCMRegistrationId());
// Path: src/main/java/com/opentaxi/android/TaxiApplication.java // @ReportsCrashes(logcatFilterByPid = true) //formKey = "", // public class TaxiApplication extends Application { //extends MultiDexApplication { // // public static String gcmId = ""; // //private static boolean havePlayService = true; // private static boolean requestsVisible = false; // //private static boolean requestsHistory = false; // //private static boolean requestsDetailsVisible = false; // private static boolean userPassVisible = false; // private static boolean mapVisible = false; // private static Integer lastRequestId; // private static boolean versionSend = false; // private static boolean serversUpdated = false; // private static boolean msgVisible = false; // private static String GCMRegistrationId; // // /*public static void setHavePlayService(boolean havePlayService) { // TaxiApplication.havePlayService = havePlayService; // } // // public static boolean isHavePlayService() { // return havePlayService; // }*/ // // public static boolean isRequestsVisible() { // return requestsVisible; // } // // public static void requestsResumed() { // requestsVisible = true; // } // // public static void requestsPaused() { // requestsVisible = false; // } // // /*public static boolean isRequestsDetailsVisible() { // return requestsDetailsVisible; // } // // public static void requestsDetailsResumed() { // requestsDetailsVisible = true; // } // // public static void requestsDetailsPaused() { // requestsDetailsVisible = false; // }*/ // // public static boolean isUserPassVisible() { // return userPassVisible; // } // // public static void userPassResumed() { // userPassVisible = true; // } // // public static void userPassPaused() { // userPassVisible = false; // } // // public static boolean isMapVisible() { // return mapVisible; // } // // public static void mapResumed() { // mapVisible = true; // } // // public static void mapPaused() { // mapVisible = false; // } // // public static Integer getLastRequestId() { // return lastRequestId; // } // // public static void setLastRequestId(Integer lastRequestId) { // TaxiApplication.lastRequestId = lastRequestId; // } // // public static boolean isVersionSend() { // return versionSend; // } // // public static void setVersionSend(boolean versionSend) { // TaxiApplication.versionSend = versionSend; // } // // public static boolean isServersUpdated() { // return serversUpdated; // } // // public static void setServersUpdated(boolean serversUpdated) { // TaxiApplication.serversUpdated = serversUpdated; // } // // public static boolean isMsgVisible() { // return msgVisible; // } // // public static void msgResumed() { // msgVisible = true; // } // // public static void msgPaused() { // msgVisible = false; // } // // public static String getGCMRegistrationId() { // return GCMRegistrationId; // } // // public static void setGCMRegistrationId(String GCMRegistrationId) { // TaxiApplication.GCMRegistrationId = GCMRegistrationId; // } // // @Override // public void onCreate() { // // /*try { // Class.forName("android.os.AsyncTask"); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // }*/ // // super.onCreate(); // //LeakCanary.install(this); // // Iconify.with(new MaterialModule()); // // FacebookSdk.sdkInitialize(getApplicationContext()); //this must be here! its have usage in MainActivity and UserPass // // //RestClient.getInstance().clearCache(); // // //AndroidGraphicFactory.createInstance(this); // // //Log.d("TaxiApplication", "onCreate()"); // // // The following line triggers the initialization of ACRA // ACRA.init(this); // CrashReportSender mySender = new CrashReportSender(); // ACRA.getErrorReporter().setReportSender(mySender); // // RestClient.getInstance().enableCache(getApplicationContext(), 1024L * 1024L * 5L); //5MB // //Iconics.registerFont(new GoogleMaterial()); // // /*// output debug to LogCat, with tag LittleFluffyLocationLibrary // //LocationLibrary.showDebugOutput(true); // // // in most cases the following initialising code using defaults is probably sufficient: // // // // LocationLibrary.initialiseLibrary(getBaseContext(), "com.opentaxi.android.service"); // // // // however for the purposes of the test app, we will request unrealistically frequent location broadcasts // // every 1 minute, and force a location update if there hasn't been one for 2 minutes. // LocationLibrary.initialiseLibrary(getBaseContext(), 30 * 1000, 60 * 1000, "com.opentaxi.android"); // LocationLibrary.useFineAccuracyForRequests(true); // LocationLibrary.showDebugOutput(true); // //LocationLibrary.forceLocationUpdate(getBaseContext()); // LocationLibrary.startAlarmAndListener(getBaseContext());*/ // } // } // Path: src/main/java/com/opentaxi/android/gcm/InstanceIdListener.java import android.content.Intent; import com.google.android.gms.iid.InstanceIDListenerService; import com.opentaxi.android.TaxiApplication; package com.opentaxi.android.gcm; /** * Created by stanimir on 12/31/15. */ public class InstanceIdListener extends InstanceIDListenerService { /** * Fetch updated Instance ID token and notify our app's server of any changes (if applicable). */ @Override public void onTokenRefresh() { //Log.i("onTokenRefresh", "Token:" + TaxiApplication.getGCMRegistrationId());
if (TaxiApplication.getGCMRegistrationId() == null) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/DefaultAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // }
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import java.util.Collection; import java.util.Collections; import java.util.Map;
package org.cyclops.everlastingabilities.api.capability; /** * Default implementation of {@link IAbilityStore} for storing abilities as a capability. * @author rubensworks */ public class DefaultAbilityStore implements IAbilityStore { protected final Map<IAbilityType, Integer> abilityTypes = Maps.newLinkedHashMap(); public DefaultAbilityStore() { } public DefaultAbilityStore(DefaultMutableAbilityStore abilityStore) { setAbilities(abilityStore.abilityTypes); } @Override public void setAbilities(Map<IAbilityType, Integer> abilityTypes) { this.abilityTypes.clear(); this.abilityTypes.putAll(abilityTypes); } @Override public boolean hasAbilityType(IAbilityType abilityType) { return abilityTypes.containsKey(abilityType); } @Override public Collection<IAbilityType> getAbilityTypes() { return abilityTypes.keySet(); } @Override
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/DefaultAbilityStore.java import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import java.util.Collection; import java.util.Collections; import java.util.Map; package org.cyclops.everlastingabilities.api.capability; /** * Default implementation of {@link IAbilityStore} for storing abilities as a capability. * @author rubensworks */ public class DefaultAbilityStore implements IAbilityStore { protected final Map<IAbilityType, Integer> abilityTypes = Maps.newLinkedHashMap(); public DefaultAbilityStore() { } public DefaultAbilityStore(DefaultMutableAbilityStore abilityStore) { setAbilities(abilityStore.abilityTypes); } @Override public void setAbilities(Map<IAbilityType, Integer> abilityTypes) { this.abilityTypes.clear(); this.abilityTypes.putAll(abilityTypes); } @Override public boolean hasAbilityType(IAbilityType abilityType) { return abilityTypes.containsKey(abilityType); } @Override public Collection<IAbilityType> getAbilityTypes() { return abilityTypes.keySet(); } @Override
public Collection<Ability> getAbilities() {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/ability/AbilityTypeStepAssist.java
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/ability/config/AbilityStepAssistConfig.java // public class AbilityStepAssistConfig extends AbilityConfig<AbilityTypeStepAssist> { // // @ConfigurableProperty(category = "ability", comment = "Forces the default step height value to 0.6 when this ability is deactivated.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean forceDefaultStepHeight = true; // // @ConfigurableProperty(category = "ability", comment = "Rarity of this ability.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int rarity = Rarity.COMMON.ordinal(); // // @ConfigurableProperty(category = "ability", comment = "The maximum ability level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int maxLevel = 3; // // @ConfigurableProperty(category = "ability", comment = "The xp required per level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int xpPerLevel = 25; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by initially spawning players.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnPlayerSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by spawning mobs.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnMobSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by combining totems in a crafting grid.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnCraft = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained in loot chests.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnLoot = true; // // public AbilityStepAssistConfig() { // super("step_assist", // eConfig -> new AbilityTypeStepAssist(eConfig.getNamedId(), () -> rarity, () -> maxLevel, () -> xpPerLevel, // () -> obtainableOnPlayerSpawn, () -> obtainableOnMobSpawn, () -> obtainableOnCraft, () -> obtainableOnLoot)); // } // // }
import net.minecraft.entity.player.PlayerEntity; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.ability.config.AbilityStepAssistConfig; import java.util.function.Supplier;
package org.cyclops.everlastingabilities.ability; /** * Ability type for flight. * @author rubensworks */ public class AbilityTypeStepAssist extends AbilityTypeDefault { private static final String PLAYER_NBT_KEY = Reference.MOD_ID + ":" + "stepAssist"; public AbilityTypeStepAssist(String id, Supplier<Integer> rarity, Supplier<Integer> maxLevel, Supplier<Integer> baseXpPerLevel, Supplier<Boolean> obtainableOnPlayerSpawn, Supplier<Boolean> obtainableOnMobSpawn, Supplier<Boolean> obtainableOnCraft, Supplier<Boolean> obtainableOnLoot) { super(id, rarity, maxLevel, baseXpPerLevel, obtainableOnPlayerSpawn, obtainableOnMobSpawn, obtainableOnCraft, obtainableOnLoot); } @Override public void onTick(PlayerEntity player, int level) { player.stepHeight = player.isCrouching() ? 0.5F : level; } @Override public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel) { if (oldLevel > 0 && newLevel == 0) { float stepHeight = 0.6F; if(player.getPersistentData().contains(PLAYER_NBT_KEY)) {
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/ability/config/AbilityStepAssistConfig.java // public class AbilityStepAssistConfig extends AbilityConfig<AbilityTypeStepAssist> { // // @ConfigurableProperty(category = "ability", comment = "Forces the default step height value to 0.6 when this ability is deactivated.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean forceDefaultStepHeight = true; // // @ConfigurableProperty(category = "ability", comment = "Rarity of this ability.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int rarity = Rarity.COMMON.ordinal(); // // @ConfigurableProperty(category = "ability", comment = "The maximum ability level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int maxLevel = 3; // // @ConfigurableProperty(category = "ability", comment = "The xp required per level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int xpPerLevel = 25; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by initially spawning players.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnPlayerSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by spawning mobs.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnMobSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by combining totems in a crafting grid.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnCraft = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained in loot chests.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnLoot = true; // // public AbilityStepAssistConfig() { // super("step_assist", // eConfig -> new AbilityTypeStepAssist(eConfig.getNamedId(), () -> rarity, () -> maxLevel, () -> xpPerLevel, // () -> obtainableOnPlayerSpawn, () -> obtainableOnMobSpawn, () -> obtainableOnCraft, () -> obtainableOnLoot)); // } // // } // Path: src/main/java/org/cyclops/everlastingabilities/ability/AbilityTypeStepAssist.java import net.minecraft.entity.player.PlayerEntity; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.ability.config.AbilityStepAssistConfig; import java.util.function.Supplier; package org.cyclops.everlastingabilities.ability; /** * Ability type for flight. * @author rubensworks */ public class AbilityTypeStepAssist extends AbilityTypeDefault { private static final String PLAYER_NBT_KEY = Reference.MOD_ID + ":" + "stepAssist"; public AbilityTypeStepAssist(String id, Supplier<Integer> rarity, Supplier<Integer> maxLevel, Supplier<Integer> baseXpPerLevel, Supplier<Boolean> obtainableOnPlayerSpawn, Supplier<Boolean> obtainableOnMobSpawn, Supplier<Boolean> obtainableOnCraft, Supplier<Boolean> obtainableOnLoot) { super(id, rarity, maxLevel, baseXpPerLevel, obtainableOnPlayerSpawn, obtainableOnMobSpawn, obtainableOnCraft, obtainableOnLoot); } @Override public void onTick(PlayerEntity player, int level) { player.stepHeight = player.isCrouching() ? 0.5F : level; } @Override public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel) { if (oldLevel > 0 && newLevel == 0) { float stepHeight = 0.6F; if(player.getPersistentData().contains(PLAYER_NBT_KEY)) {
if (!AbilityStepAssistConfig.forceDefaultStepHeight) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/ability/AbilityTypePowerStare.java
// Path: src/main/java/org/cyclops/everlastingabilities/ability/config/AbilityPowerStareConfig.java // public class AbilityPowerStareConfig extends AbilityConfig<AbilityTypePowerStare> { // // @ConfigurableProperty(category = "ability", comment = "Rarity of this ability.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int rarity = Rarity.UNCOMMON.ordinal(); // // @ConfigurableProperty(category = "ability", comment = "The maximum ability level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int maxLevel = 5; // // @ConfigurableProperty(category = "ability", comment = "The xp required per level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int xpPerLevel = 50; // // @ConfigurableProperty(category = "ability", comment = "Require sneak to activate.", configLocation = ModConfig.Type.SERVER) // public static boolean requireSneak = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by initially spawning players.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnPlayerSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by spawning mobs.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnMobSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by combining totems in a crafting grid.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnCraft = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained in loot chests.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnLoot = true; // // public AbilityPowerStareConfig() { // super("power_stare", // eConfig -> new AbilityTypePowerStare(eConfig.getNamedId(), () -> rarity, () -> maxLevel, () -> xpPerLevel, // () -> obtainableOnPlayerSpawn, () -> obtainableOnMobSpawn, () -> obtainableOnCraft, () -> obtainableOnLoot)); // } // // }
import net.minecraft.entity.Entity; import net.minecraft.entity.passive.TameableEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.world.World; import org.cyclops.cyclopscore.helper.MinecraftHelpers; import org.cyclops.everlastingabilities.ability.config.AbilityPowerStareConfig; import java.util.List; import java.util.function.Supplier;
package org.cyclops.everlastingabilities.ability; /** * Ability type for pushing in the direction your looking mobs away. * @author rubensworks */ public class AbilityTypePowerStare extends AbilityTypeDefault { private static final int TICK_MODULUS = MinecraftHelpers.SECOND_IN_TICKS / 4; public AbilityTypePowerStare(String id, Supplier<Integer> rarity, Supplier<Integer> maxLevel, Supplier<Integer> baseXpPerLevel, Supplier<Boolean> obtainableOnPlayerSpawn, Supplier<Boolean> obtainableOnMobSpawn, Supplier<Boolean> obtainableOnCraft, Supplier<Boolean> obtainableOnLoot) { super(id, rarity, maxLevel, baseXpPerLevel, obtainableOnPlayerSpawn, obtainableOnMobSpawn, obtainableOnCraft, obtainableOnLoot); } @Override public void onTick(PlayerEntity player, int level) {
// Path: src/main/java/org/cyclops/everlastingabilities/ability/config/AbilityPowerStareConfig.java // public class AbilityPowerStareConfig extends AbilityConfig<AbilityTypePowerStare> { // // @ConfigurableProperty(category = "ability", comment = "Rarity of this ability.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int rarity = Rarity.UNCOMMON.ordinal(); // // @ConfigurableProperty(category = "ability", comment = "The maximum ability level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int maxLevel = 5; // // @ConfigurableProperty(category = "ability", comment = "The xp required per level.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static int xpPerLevel = 50; // // @ConfigurableProperty(category = "ability", comment = "Require sneak to activate.", configLocation = ModConfig.Type.SERVER) // public static boolean requireSneak = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by initially spawning players.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnPlayerSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by spawning mobs.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnMobSpawn = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained by combining totems in a crafting grid.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnCraft = true; // // @ConfigurableProperty(category = "ability", comment = "If this can be obtained in loot chests.", isCommandable = true, configLocation = ModConfig.Type.SERVER) // public static boolean obtainableOnLoot = true; // // public AbilityPowerStareConfig() { // super("power_stare", // eConfig -> new AbilityTypePowerStare(eConfig.getNamedId(), () -> rarity, () -> maxLevel, () -> xpPerLevel, // () -> obtainableOnPlayerSpawn, () -> obtainableOnMobSpawn, () -> obtainableOnCraft, () -> obtainableOnLoot)); // } // // } // Path: src/main/java/org/cyclops/everlastingabilities/ability/AbilityTypePowerStare.java import net.minecraft.entity.Entity; import net.minecraft.entity.passive.TameableEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.world.World; import org.cyclops.cyclopscore.helper.MinecraftHelpers; import org.cyclops.everlastingabilities.ability.config.AbilityPowerStareConfig; import java.util.List; import java.util.function.Supplier; package org.cyclops.everlastingabilities.ability; /** * Ability type for pushing in the direction your looking mobs away. * @author rubensworks */ public class AbilityTypePowerStare extends AbilityTypeDefault { private static final int TICK_MODULUS = MinecraftHelpers.SECOND_IN_TICKS / 4; public AbilityTypePowerStare(String id, Supplier<Integer> rarity, Supplier<Integer> maxLevel, Supplier<Integer> baseXpPerLevel, Supplier<Boolean> obtainableOnPlayerSpawn, Supplier<Boolean> obtainableOnMobSpawn, Supplier<Boolean> obtainableOnCraft, Supplier<Boolean> obtainableOnLoot) { super(id, rarity, maxLevel, baseXpPerLevel, obtainableOnPlayerSpawn, obtainableOnMobSpawn, obtainableOnCraft, obtainableOnLoot); } @Override public void onTick(PlayerEntity player, int level) {
if ( AbilityPowerStareConfig.requireSneak && !player.isCrouching() ) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/IMutableAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // }
import lombok.NonNull; import org.cyclops.everlastingabilities.api.Ability;
package org.cyclops.everlastingabilities.api.capability; /** * Extension of the {@link IAbilityStore} that allows insertion and deletion of abilities. * @author rubensworks */ public interface IMutableAbilityStore extends IAbilityStore { /** * Add the given ability. * @param ability The ability. * @param doAdd If the addition should actually be done. * @return The ability part that was added. */ @NonNull
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/IMutableAbilityStore.java import lombok.NonNull; import org.cyclops.everlastingabilities.api.Ability; package org.cyclops.everlastingabilities.api.capability; /** * Extension of the {@link IAbilityStore} that allows insertion and deletion of abilities. * @author rubensworks */ public interface IMutableAbilityStore extends IAbilityStore { /** * Add the given ability. * @param ability The ability. * @param doAdd If the addition should actually be done. * @return The ability part that was added. */ @NonNull
public Ability addAbility(Ability ability, boolean doAdd);
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig;
package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) {
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) {
return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null)
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig;
package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0;
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0;
for (Ability ability : abilityStore.getAbilities()) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig;
package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0; for (Ability ability : abilityStore.getAbilities()) { maxRarity = Math.max(maxRarity, ability.getAbilityType().getRarity().ordinal()); } return Rarity.values()[maxRarity]; }) .orElse(super.getRarity(itemStack)); } public static ItemStack getTotem(Ability ability) {
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0; for (Ability ability : abilityStore.getAbilities()) { maxRarity = Math.max(maxRarity, ability.getAbilityType().getRarity().ordinal()); } return Rarity.values()[maxRarity]; }) .orElse(super.getRarity(itemStack)); } public static ItemStack getTotem(Ability ability) {
ItemStack itemStack = new ItemStack(RegistryEntries.ITEM_ABILITY_TOTEM);
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig;
package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0; for (Ability ability : abilityStore.getAbilities()) { maxRarity = Math.max(maxRarity, ability.getAbilityType().getRarity().ordinal()); } return Rarity.values()[maxRarity]; }) .orElse(super.getRarity(itemStack)); } public static ItemStack getTotem(Ability ability) { ItemStack itemStack = new ItemStack(RegistryEntries.ITEM_ABILITY_TOTEM); itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .ifPresent(mutableAbilityStore -> mutableAbilityStore.addAbility(ability, true)); return itemStack; } @Override public void fillItemGroup(ItemGroup group, NonNullList<ItemStack> items) { if (this.isInGroup(group)) {
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0; for (Ability ability : abilityStore.getAbilities()) { maxRarity = Math.max(maxRarity, ability.getAbilityType().getRarity().ordinal()); } return Rarity.values()[maxRarity]; }) .orElse(super.getRarity(itemStack)); } public static ItemStack getTotem(Ability ability) { ItemStack itemStack = new ItemStack(RegistryEntries.ITEM_ABILITY_TOTEM); itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .ifPresent(mutableAbilityStore -> mutableAbilityStore.addAbility(ability, true)); return itemStack; } @Override public void fillItemGroup(ItemGroup group, NonNullList<ItemStack> items) { if (this.isInGroup(group)) {
for (IAbilityType abilityType : AbilityTypes.REGISTRY.getValues()) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig;
package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0; for (Ability ability : abilityStore.getAbilities()) { maxRarity = Math.max(maxRarity, ability.getAbilityType().getRarity().ordinal()); } return Rarity.values()[maxRarity]; }) .orElse(super.getRarity(itemStack)); } public static ItemStack getTotem(Ability ability) { ItemStack itemStack = new ItemStack(RegistryEntries.ITEM_ABILITY_TOTEM); itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .ifPresent(mutableAbilityStore -> mutableAbilityStore.addAbility(ability, true)); return itemStack; } @Override public void fillItemGroup(ItemGroup group, NonNullList<ItemStack> items) { if (this.isInGroup(group)) {
// Path: src/main/java/org/cyclops/everlastingabilities/RegistryEntries.java // public class RegistryEntries { // // @ObjectHolder("everlastingabilities:ability_bottle") // public static final Item ITEM_ABILITY_BOTTLE = null; // @ObjectHolder("everlastingabilities:ability_totem") // public static final Item ITEM_ABILITY_TOTEM = null; // // @ObjectHolder("everlastingabilities:ability_container") // public static final ContainerType<ContainerAbilityContainer> CONTAINER_ABILITYCONTAINER = null; // // @ObjectHolder("everlastingabilities:crafting_special_totem_recycle") // public static final SpecialRecipeSerializer<TotemRecycleRecipe> RECIPESERIALIZER_TOTEM_RECYCLE = null; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/item/ItemAbilityTotem.java import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Rarity; import net.minecraft.util.NonNullList; import org.cyclops.everlastingabilities.RegistryEntries; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; package org.cyclops.everlastingabilities.item; /** * A totem with abilities. * @author rubensworks */ public class ItemAbilityTotem extends ItemGuiAbilityContainer { public ItemAbilityTotem(Properties properties) { super(properties); } @Override public boolean canMoveFromPlayer() { return false; } @Override public Rarity getRarity(ItemStack itemStack) { return itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .map(abilityStore -> { int maxRarity = 0; for (Ability ability : abilityStore.getAbilities()) { maxRarity = Math.max(maxRarity, ability.getAbilityType().getRarity().ordinal()); } return Rarity.values()[maxRarity]; }) .orElse(super.getRarity(itemStack)); } public static ItemStack getTotem(Ability ability) { ItemStack itemStack = new ItemStack(RegistryEntries.ITEM_ABILITY_TOTEM); itemStack.getCapability(MutableAbilityStoreConfig.CAPABILITY, null) .ifPresent(mutableAbilityStore -> mutableAbilityStore.addAbility(ability, true)); return itemStack; } @Override public void fillItemGroup(ItemGroup group, NonNullList<ItemStack> items) { if (this.isInGroup(group)) {
for (IAbilityType abilityType : AbilityTypes.REGISTRY.getValues()) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/IAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // }
import lombok.NonNull; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentUtils; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import java.util.Collection; import java.util.Map;
package org.cyclops.everlastingabilities.api.capability; /** * Capability type for storing capabilities. * @author rubensworks */ public interface IAbilityStore { public void setAbilities(Map<IAbilityType, Integer> abilityTypes); public boolean hasAbilityType(IAbilityType abilityType); public Collection<IAbilityType> getAbilityTypes();
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/IAbilityStore.java import lombok.NonNull; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentUtils; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import java.util.Collection; import java.util.Map; package org.cyclops.everlastingabilities.api.capability; /** * Capability type for storing capabilities. * @author rubensworks */ public interface IAbilityStore { public void setAbilities(Map<IAbilityType, Integer> abilityTypes); public boolean hasAbilityType(IAbilityType abilityType); public Collection<IAbilityType> getAbilityTypes();
public Collection<Ability> getAbilities();
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/DefaultMutableAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // }
import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType;
package org.cyclops.everlastingabilities.api.capability; /** * Default implementation of {@link IAbilityStore} for storing abilities as a capability. * @author rubensworks */ public class DefaultMutableAbilityStore extends DefaultAbilityStore implements IMutableAbilityStore { public DefaultMutableAbilityStore() { } public DefaultMutableAbilityStore(DefaultAbilityStore abilityStore) { setAbilities(abilityStore.abilityTypes); } @Override
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/DefaultMutableAbilityStore.java import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; package org.cyclops.everlastingabilities.api.capability; /** * Default implementation of {@link IAbilityStore} for storing abilities as a capability. * @author rubensworks */ public class DefaultMutableAbilityStore extends DefaultAbilityStore implements IMutableAbilityStore { public DefaultMutableAbilityStore() { } public DefaultMutableAbilityStore(DefaultAbilityStore abilityStore) { setAbilities(abilityStore.abilityTypes); } @Override
public Ability addAbility(Ability ability, boolean doAdd) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/DefaultMutableAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // }
import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType;
package org.cyclops.everlastingabilities.api.capability; /** * Default implementation of {@link IAbilityStore} for storing abilities as a capability. * @author rubensworks */ public class DefaultMutableAbilityStore extends DefaultAbilityStore implements IMutableAbilityStore { public DefaultMutableAbilityStore() { } public DefaultMutableAbilityStore(DefaultAbilityStore abilityStore) { setAbilities(abilityStore.abilityTypes); } @Override public Ability addAbility(Ability ability, boolean doAdd) {
// Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/DefaultMutableAbilityStore.java import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; package org.cyclops.everlastingabilities.api.capability; /** * Default implementation of {@link IAbilityStore} for storing abilities as a capability. * @author rubensworks */ public class DefaultMutableAbilityStore extends DefaultAbilityStore implements IMutableAbilityStore { public DefaultMutableAbilityStore() { } public DefaultMutableAbilityStore(DefaultAbilityStore abilityStore) { setAbilities(abilityStore.abilityTypes); } @Override public Ability addAbility(Ability ability, boolean doAdd) {
IAbilityType abilityType = ability.getAbilityType();
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/command/argument/ArgumentTypeAbility.java
// Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // }
import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.minecraft.command.ISuggestionProvider; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.registries.IForgeRegistryEntry; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors;
package org.cyclops.everlastingabilities.command.argument; /** * An argument type for an ability. * @author rubensworks */ public class ArgumentTypeAbility implements ArgumentType<IAbilityType> { @Override public IAbilityType parse(StringReader reader) throws CommandSyntaxException { ResourceLocation id = ResourceLocation.read(reader);
// Path: src/main/java/org/cyclops/everlastingabilities/api/AbilityTypes.java // @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD) // public class AbilityTypes { // // public static IForgeRegistry<IAbilityType> REGISTRY; // // @SubscribeEvent // public static void onRegistriesCreate(RegistryEvent.NewRegistry event) { // REGISTRY = new RegistryBuilder<IAbilityType>() // .setName(new ResourceLocation("everlastingabilities", "abilities")) // .setType(IAbilityType.class) // .create(); // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // Path: src/main/java/org/cyclops/everlastingabilities/command/argument/ArgumentTypeAbility.java import com.mojang.brigadier.StringReader; import com.mojang.brigadier.arguments.ArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.SuggestionsBuilder; import net.minecraft.command.ISuggestionProvider; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.registries.IForgeRegistryEntry; import org.cyclops.everlastingabilities.api.AbilityTypes; import org.cyclops.everlastingabilities.api.IAbilityType; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; package org.cyclops.everlastingabilities.command.argument; /** * An argument type for an ability. * @author rubensworks */ public class ArgumentTypeAbility implements ArgumentType<IAbilityType> { @Override public IAbilityType parse(StringReader reader) throws CommandSyntaxException { ResourceLocation id = ResourceLocation.read(reader);
IAbilityType abilityType = AbilityTypes.REGISTRY.getValue(id);
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/ItemStackMutableAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import lombok.NonNull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import java.util.Collection; import java.util.Map;
package org.cyclops.everlastingabilities.api.capability; /** * Wrapper for an item ability store. * TODO: This is just to avoid a Forge bug where cap NBT is not always sent to the client. * @author rubensworks */ public class ItemStackMutableAbilityStore implements IMutableAbilityStore { private static final String NBT_STORE = Reference.MOD_ID + ":abilityStoreStack"; private final ItemStack itemStack; public ItemStackMutableAbilityStore(ItemStack itemStack) { this.itemStack = itemStack; } protected IMutableAbilityStore getInnerStore() { IMutableAbilityStore store = new DefaultMutableAbilityStore(); CompoundNBT root = itemStack.getOrCreateTag(); if (!root.contains(NBT_STORE)) { root.put(NBT_STORE, new ListNBT()); } INBT nbt = root.get(NBT_STORE);
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/ItemStackMutableAbilityStore.java import lombok.NonNull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import java.util.Collection; import java.util.Map; package org.cyclops.everlastingabilities.api.capability; /** * Wrapper for an item ability store. * TODO: This is just to avoid a Forge bug where cap NBT is not always sent to the client. * @author rubensworks */ public class ItemStackMutableAbilityStore implements IMutableAbilityStore { private static final String NBT_STORE = Reference.MOD_ID + ":abilityStoreStack"; private final ItemStack itemStack; public ItemStackMutableAbilityStore(ItemStack itemStack) { this.itemStack = itemStack; } protected IMutableAbilityStore getInnerStore() { IMutableAbilityStore store = new DefaultMutableAbilityStore(); CompoundNBT root = itemStack.getOrCreateTag(); if (!root.contains(NBT_STORE)) { root.put(NBT_STORE, new ListNBT()); } INBT nbt = root.get(NBT_STORE);
MutableAbilityStoreConfig.CAPABILITY.readNBT(store, null, nbt);
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/ItemStackMutableAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import lombok.NonNull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import java.util.Collection; import java.util.Map;
package org.cyclops.everlastingabilities.api.capability; /** * Wrapper for an item ability store. * TODO: This is just to avoid a Forge bug where cap NBT is not always sent to the client. * @author rubensworks */ public class ItemStackMutableAbilityStore implements IMutableAbilityStore { private static final String NBT_STORE = Reference.MOD_ID + ":abilityStoreStack"; private final ItemStack itemStack; public ItemStackMutableAbilityStore(ItemStack itemStack) { this.itemStack = itemStack; } protected IMutableAbilityStore getInnerStore() { IMutableAbilityStore store = new DefaultMutableAbilityStore(); CompoundNBT root = itemStack.getOrCreateTag(); if (!root.contains(NBT_STORE)) { root.put(NBT_STORE, new ListNBT()); } INBT nbt = root.get(NBT_STORE); MutableAbilityStoreConfig.CAPABILITY.readNBT(store, null, nbt); return store; } protected IMutableAbilityStore setInnerStore(IMutableAbilityStore store) { CompoundNBT root = itemStack.getOrCreateTag(); INBT nbt = MutableAbilityStoreConfig.CAPABILITY.writeNBT(store, null); root.put(NBT_STORE, nbt); return store; } @NonNull @Override
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/ItemStackMutableAbilityStore.java import lombok.NonNull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import java.util.Collection; import java.util.Map; package org.cyclops.everlastingabilities.api.capability; /** * Wrapper for an item ability store. * TODO: This is just to avoid a Forge bug where cap NBT is not always sent to the client. * @author rubensworks */ public class ItemStackMutableAbilityStore implements IMutableAbilityStore { private static final String NBT_STORE = Reference.MOD_ID + ":abilityStoreStack"; private final ItemStack itemStack; public ItemStackMutableAbilityStore(ItemStack itemStack) { this.itemStack = itemStack; } protected IMutableAbilityStore getInnerStore() { IMutableAbilityStore store = new DefaultMutableAbilityStore(); CompoundNBT root = itemStack.getOrCreateTag(); if (!root.contains(NBT_STORE)) { root.put(NBT_STORE, new ListNBT()); } INBT nbt = root.get(NBT_STORE); MutableAbilityStoreConfig.CAPABILITY.readNBT(store, null, nbt); return store; } protected IMutableAbilityStore setInnerStore(IMutableAbilityStore store) { CompoundNBT root = itemStack.getOrCreateTag(); INBT nbt = MutableAbilityStoreConfig.CAPABILITY.writeNBT(store, null); root.put(NBT_STORE, nbt); return store; } @NonNull @Override
public Ability addAbility(Ability ability, boolean doAdd) {
CyclopsMC/EverlastingAbilities
src/main/java/org/cyclops/everlastingabilities/api/capability/ItemStackMutableAbilityStore.java
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // }
import lombok.NonNull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import java.util.Collection; import java.util.Map;
MutableAbilityStoreConfig.CAPABILITY.readNBT(store, null, nbt); return store; } protected IMutableAbilityStore setInnerStore(IMutableAbilityStore store) { CompoundNBT root = itemStack.getOrCreateTag(); INBT nbt = MutableAbilityStoreConfig.CAPABILITY.writeNBT(store, null); root.put(NBT_STORE, nbt); return store; } @NonNull @Override public Ability addAbility(Ability ability, boolean doAdd) { IMutableAbilityStore store = getInnerStore(); Ability ret = store.addAbility(ability, doAdd); setInnerStore(store); return ret; } @NonNull @Override public Ability removeAbility(Ability ability, boolean doRemove) { IMutableAbilityStore store = getInnerStore(); Ability ret = store.removeAbility(ability, doRemove); setInnerStore(store); return ret; } @Override
// Path: src/main/java/org/cyclops/everlastingabilities/Reference.java // @SuppressWarnings("javadoc") // public class Reference { // // // Mod info // public static final String MOD_ID = "everlastingabilities"; // public static final String GA_TRACKING_ID = "UA-65307010-9"; // public static final String VERSION_URL = "https://raw.githubusercontent.com/CyclopsMC/Versions/master/" + MinecraftHelpers.getMinecraftVersionMajorMinor() + "/EverlastingAbilities.txt"; // // // Paths // public static final String TEXTURE_PATH_GUI = "textures/gui/"; // public static final String TEXTURE_PATH_SKINS = "textures/skins/"; // public static final String TEXTURE_PATH_MODELS = "textures/models/"; // public static final String TEXTURE_PATH_ENTITIES = "textures/entities/"; // public static final String TEXTURE_PATH_GUIBACKGROUNDS = "textures/gui/title/background/"; // public static final String TEXTURE_PATH_ITEMS = "textures/items/"; // public static final String TEXTURE_PATH_PARTICLES = "textures/particles/"; // public static final String MODEL_PATH = "models/"; // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/Ability.java // public class Ability implements Comparable<Ability> { // // public static final Ability EMPTY = new Ability(new AbilityType("", "", () -> Rarity.COMMON, () -> 0, () -> 0, () -> true, () -> true, () -> true, () -> true), 0); // // private final IAbilityType abilityType; // private final int level; // // public Ability(@Nonnull IAbilityType abilityType, int level) { // this.abilityType = Objects.requireNonNull(abilityType); // this.level = level; // } // // public IAbilityType getAbilityType() { // return abilityType; // } // // public int getLevel() { // return level; // } // // @Override // public String toString() { // return String.format("[%s @ %s]", abilityType.getTranslationKey(), level); // } // // @Override // public int compareTo(Ability other) { // return this.toString().compareTo(other.toString()); // } // // public ITextComponent getTextComponent() { // return new StringTextComponent("[") // .append(new TranslationTextComponent(abilityType.getTranslationKey())) // .appendString(" @ " + level + "]"); // } // // public boolean isEmpty() { // return getLevel() <= 0; // } // // } // // Path: src/main/java/org/cyclops/everlastingabilities/api/IAbilityType.java // public interface IAbilityType extends IForgeRegistryEntry<IAbilityType> { // // public String getTranslationKey(); // public String getUnlocalizedDescription(); // public Rarity getRarity(); // public int getMaxLevel(); // public default int getMaxLevelInfinitySafe() { // return getMaxLevel() < 0 ? Integer.MAX_VALUE : getMaxLevel(); // } // public int getBaseXpPerLevel(); // public boolean isObtainableOnPlayerSpawn(); // public boolean isObtainableOnMobSpawn(); // public boolean isObtainableOnCraft(); // public boolean isObtainableOnLoot(); // // public void onTick(PlayerEntity player, int level); // public void onChangedLevel(PlayerEntity player, int oldLevel, int newLevel); // // } // // Path: src/main/java/org/cyclops/everlastingabilities/capability/MutableAbilityStoreConfig.java // public class MutableAbilityStoreConfig extends CapabilityConfig { // // /** // * The unique instance. // */ // public static MutableAbilityStoreConfig _instance; // // @CapabilityInject(IMutableAbilityStore.class) // public static Capability<IMutableAbilityStore> CAPABILITY = null; // // /** // * Make a new instance. // */ // public MutableAbilityStoreConfig() { // super(EverlastingAbilities._instance, // "mutableAbilityStore", // IMutableAbilityStore.class, // new AbilityStoreStorage(), // DefaultMutableAbilityStore::new); // } // } // Path: src/main/java/org/cyclops/everlastingabilities/api/capability/ItemStackMutableAbilityStore.java import lombok.NonNull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import org.cyclops.everlastingabilities.Reference; import org.cyclops.everlastingabilities.api.Ability; import org.cyclops.everlastingabilities.api.IAbilityType; import org.cyclops.everlastingabilities.capability.MutableAbilityStoreConfig; import java.util.Collection; import java.util.Map; MutableAbilityStoreConfig.CAPABILITY.readNBT(store, null, nbt); return store; } protected IMutableAbilityStore setInnerStore(IMutableAbilityStore store) { CompoundNBT root = itemStack.getOrCreateTag(); INBT nbt = MutableAbilityStoreConfig.CAPABILITY.writeNBT(store, null); root.put(NBT_STORE, nbt); return store; } @NonNull @Override public Ability addAbility(Ability ability, boolean doAdd) { IMutableAbilityStore store = getInnerStore(); Ability ret = store.addAbility(ability, doAdd); setInnerStore(store); return ret; } @NonNull @Override public Ability removeAbility(Ability ability, boolean doRemove) { IMutableAbilityStore store = getInnerStore(); Ability ret = store.removeAbility(ability, doRemove); setInnerStore(store); return ret; } @Override
public void setAbilities(Map<IAbilityType, Integer> abilityTypes) {
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/helper/DatabaseHelper.java
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Article.java // public class Article { // private String id; // private String title; // private String text; // private String category; // private String cachefile; // private ArrayList<String> tags; // // public ArrayList<String> getTags() { // return tags; // } // // public void setTags(ArrayList<String> tags) { // this.tags = tags; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getCachefile() { // return cachefile; // } // // public void setCachefile(String cachefile) { // this.cachefile = cachefile; // } // // public Article() {} // // public Article(String id, String title, String text, String category, ArrayList<String> tags) { // this.id = id; // this.title = title; // this.text = text; // this.category = category; // this.tags = tags; // } // } // // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Feedback.java // public class Feedback { // // private String title; // private String description; // private int upvotes; // // public Feedback() { // } // // public Feedback(String title, String description, int upvotes) { // this.title = title; // this.description = description; // this.upvotes = upvotes; // // } // // public int getUpvotes() { // return upvotes; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import org.owasp.seraphimdroid.model.Article; import org.owasp.seraphimdroid.model.Feedback; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
if (cursor.getString(0).equals(Integer.toString(id))){ usages = Integer.parseInt(cursor.getString(2)); } } while (cursor.moveToNext()); } cursor.close(); return usages; } public void removeFeatureUsage(int id){ SQLiteDatabase db = this.getWritableDatabase(); int new_val = 0; ContentValues cv = new ContentValues(); cv.put("uses", new_val); db.update("usage", cv, "id="+id, null); } public void addFeatureUsage(int id) { SQLiteDatabase db = this.getWritableDatabase(); int exist = getFeatureUsage(id); int new_val = exist + 1; ContentValues cv = new ContentValues(); cv.put("uses", new_val); db.update("usage", cv, "id="+id, null); } // Feedback Helper Functions
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Article.java // public class Article { // private String id; // private String title; // private String text; // private String category; // private String cachefile; // private ArrayList<String> tags; // // public ArrayList<String> getTags() { // return tags; // } // // public void setTags(ArrayList<String> tags) { // this.tags = tags; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getCachefile() { // return cachefile; // } // // public void setCachefile(String cachefile) { // this.cachefile = cachefile; // } // // public Article() {} // // public Article(String id, String title, String text, String category, ArrayList<String> tags) { // this.id = id; // this.title = title; // this.text = text; // this.category = category; // this.tags = tags; // } // } // // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Feedback.java // public class Feedback { // // private String title; // private String description; // private int upvotes; // // public Feedback() { // } // // public Feedback(String title, String description, int upvotes) { // this.title = title; // this.description = description; // this.upvotes = upvotes; // // } // // public int getUpvotes() { // return upvotes; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/helper/DatabaseHelper.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import org.owasp.seraphimdroid.model.Article; import org.owasp.seraphimdroid.model.Feedback; import java.util.ArrayList; import java.util.Arrays; import java.util.List; if (cursor.getString(0).equals(Integer.toString(id))){ usages = Integer.parseInt(cursor.getString(2)); } } while (cursor.moveToNext()); } cursor.close(); return usages; } public void removeFeatureUsage(int id){ SQLiteDatabase db = this.getWritableDatabase(); int new_val = 0; ContentValues cv = new ContentValues(); cv.put("uses", new_val); db.update("usage", cv, "id="+id, null); } public void addFeatureUsage(int id) { SQLiteDatabase db = this.getWritableDatabase(); int exist = getFeatureUsage(id); int new_val = exist + 1; ContentValues cv = new ContentValues(); cv.put("uses", new_val); db.update("usage", cv, "id="+id, null); } // Feedback Helper Functions
public void addNewFeedback(ArrayList<Feedback> list) {
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/helper/DatabaseHelper.java
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Article.java // public class Article { // private String id; // private String title; // private String text; // private String category; // private String cachefile; // private ArrayList<String> tags; // // public ArrayList<String> getTags() { // return tags; // } // // public void setTags(ArrayList<String> tags) { // this.tags = tags; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getCachefile() { // return cachefile; // } // // public void setCachefile(String cachefile) { // this.cachefile = cachefile; // } // // public Article() {} // // public Article(String id, String title, String text, String category, ArrayList<String> tags) { // this.id = id; // this.title = title; // this.text = text; // this.category = category; // this.tags = tags; // } // } // // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Feedback.java // public class Feedback { // // private String title; // private String description; // private int upvotes; // // public Feedback() { // } // // public Feedback(String title, String description, int upvotes) { // this.title = title; // this.description = description; // this.upvotes = upvotes; // // } // // public int getUpvotes() { // return upvotes; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import org.owasp.seraphimdroid.model.Article; import org.owasp.seraphimdroid.model.Feedback; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
db.insert(TABLE_FEEDBACK, null, cv); cv.clear(); } db.close(); } public ArrayList<Feedback> getAllFeedback() { ArrayList<Feedback> feedbacks = new ArrayList<>(); String selectQuery = "SELECT * FROM " + TABLE_FEEDBACK; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Feedback fb = new Feedback(); fb.setTitle(cursor.getString(0)); fb.setDescription(cursor.getString(1)); fb.setUpvotes(Integer.parseInt(cursor.getString(2))); feedbacks.add(fb); } while (cursor.moveToNext()); } cursor.close(); return feedbacks; } // Article Helper Functions
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Article.java // public class Article { // private String id; // private String title; // private String text; // private String category; // private String cachefile; // private ArrayList<String> tags; // // public ArrayList<String> getTags() { // return tags; // } // // public void setTags(ArrayList<String> tags) { // this.tags = tags; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getCachefile() { // return cachefile; // } // // public void setCachefile(String cachefile) { // this.cachefile = cachefile; // } // // public Article() {} // // public Article(String id, String title, String text, String category, ArrayList<String> tags) { // this.id = id; // this.title = title; // this.text = text; // this.category = category; // this.tags = tags; // } // } // // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Feedback.java // public class Feedback { // // private String title; // private String description; // private int upvotes; // // public Feedback() { // } // // public Feedback(String title, String description, int upvotes) { // this.title = title; // this.description = description; // this.upvotes = upvotes; // // } // // public int getUpvotes() { // return upvotes; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/helper/DatabaseHelper.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import org.owasp.seraphimdroid.model.Article; import org.owasp.seraphimdroid.model.Feedback; import java.util.ArrayList; import java.util.Arrays; import java.util.List; db.insert(TABLE_FEEDBACK, null, cv); cv.clear(); } db.close(); } public ArrayList<Feedback> getAllFeedback() { ArrayList<Feedback> feedbacks = new ArrayList<>(); String selectQuery = "SELECT * FROM " + TABLE_FEEDBACK; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { Feedback fb = new Feedback(); fb.setTitle(cursor.getString(0)); fb.setDescription(cursor.getString(1)); fb.setUpvotes(Integer.parseInt(cursor.getString(2))); feedbacks.add(fb); } while (cursor.moveToNext()); } cursor.close(); return feedbacks; } // Article Helper Functions
public void addNewArticles(ArrayList<Article> list) {
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/BlockerFragment.java
// Path: Resources/src/org/owasp/seraphimdroid/adapter/TabsPagerAdapter.java // public class TabsPagerAdapter extends FragmentStatePagerAdapter{ // // public TabsPagerAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int index) { // // switch (index) { // case 0: // // Top Rated fragment activity // return new CallLogFragment(); // case 1: // // Games fragment activity // return new SMSLogFragment(); // // case 2: // // Movies fragment activity // return new USSDLogFragment(); // } // // return null; // } // // @Override // public int getCount() { // // get item count - equal to number of tabs // return 3; // } // // }
import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import org.owasp.seraphimdroid.adapter.TabsPagerAdapter;
package org.owasp.seraphimdroid; public class BlockerFragment extends Fragment implements OnPageChangeListener, OnTabChangeListener { private TabHost tabHost; private ViewPager viewPager; private int tabNo = 5; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { tabNo = getActivity().getIntent().getIntExtra("TAB_NO", 5); } catch (Exception e) { e.printStackTrace(); } View view = inflater.inflate(R.layout.fragment_blocker, container, false); tabHost = (TabHost) view.findViewById(R.id.tabhost); tabHost.setup(); initTabs(); viewPager = (ViewPager) view.findViewById(R.id.viewpager);
// Path: Resources/src/org/owasp/seraphimdroid/adapter/TabsPagerAdapter.java // public class TabsPagerAdapter extends FragmentStatePagerAdapter{ // // public TabsPagerAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int index) { // // switch (index) { // case 0: // // Top Rated fragment activity // return new CallLogFragment(); // case 1: // // Games fragment activity // return new SMSLogFragment(); // // case 2: // // Movies fragment activity // return new USSDLogFragment(); // } // // return null; // } // // @Override // public int getCount() { // // get item count - equal to number of tabs // return 3; // } // // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/BlockerFragment.java import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import org.owasp.seraphimdroid.adapter.TabsPagerAdapter; package org.owasp.seraphimdroid; public class BlockerFragment extends Fragment implements OnPageChangeListener, OnTabChangeListener { private TabHost tabHost; private ViewPager viewPager; private int tabNo = 5; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { tabNo = getActivity().getIntent().getIntExtra("TAB_NO", 5); } catch (Exception e) { e.printStackTrace(); } View view = inflater.inflate(R.layout.fragment_blocker, container, false); tabHost = (TabHost) view.findViewById(R.id.tabhost); tabHost.setup(); initTabs(); viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new TabsPagerAdapter(getActivity()
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/ReportActivity.java
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/helper/ConnectionHelper.java // public class ConnectionHelper { // // private Context _context; // // public ConnectionHelper(Context context){ // this._context = context; // } // // public boolean isConnectingToInternet(){ // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // for (int i = 0; i < info.length; i++) // if (info[i].getState() == NetworkInfo.State.CONNECTED) { // return true; // } // } // return false; // } // }
import android.app.Activity; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import org.owasp.seraphimdroid.helper.ConnectionHelper;
// Feedback fb = new Feedback(title, description, upvotes); // feedbackList.add(fb); // // } catch (JSONException e) { // Log.e(TAG, "JSON Parsing error: " + e.getMessage()); // Toast.makeText(ReportActivity.this, "Some Error Occured", Toast.LENGTH_SHORT).show(); // } // } // db.addNewFeedback(feedbackList); // adapter.notifyDataSetChanged(); // } // swipeRefreshLayout.setRefreshing(false); // } // }, new Response.ErrorListener() { // // @Override // public void onErrorResponse(VolleyError error) { // Toast.makeText(getApplicationContext(), "You are Offline", Toast.LENGTH_LONG).show(); // // feedbackList.addAll(db.getAllFeedback()); // adapter.notifyDataSetChanged(); // swipeRefreshLayout.setRefreshing(false); // } // }); // RequestQueue requestQueue = Volley.newRequestQueue(this); // requestQueue.add(jar); // } @Override public void onClick(View view) {
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/helper/ConnectionHelper.java // public class ConnectionHelper { // // private Context _context; // // public ConnectionHelper(Context context){ // this._context = context; // } // // public boolean isConnectingToInternet(){ // ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivity != null) // { // NetworkInfo[] info = connectivity.getAllNetworkInfo(); // if (info != null) // for (int i = 0; i < info.length; i++) // if (info[i].getState() == NetworkInfo.State.CONNECTED) { // return true; // } // } // return false; // } // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/ReportActivity.java import android.app.Activity; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; import org.owasp.seraphimdroid.helper.ConnectionHelper; // Feedback fb = new Feedback(title, description, upvotes); // feedbackList.add(fb); // // } catch (JSONException e) { // Log.e(TAG, "JSON Parsing error: " + e.getMessage()); // Toast.makeText(ReportActivity.this, "Some Error Occured", Toast.LENGTH_SHORT).show(); // } // } // db.addNewFeedback(feedbackList); // adapter.notifyDataSetChanged(); // } // swipeRefreshLayout.setRefreshing(false); // } // }, new Response.ErrorListener() { // // @Override // public void onErrorResponse(VolleyError error) { // Toast.makeText(getApplicationContext(), "You are Offline", Toast.LENGTH_LONG).show(); // // feedbackList.addAll(db.getAllFeedback()); // adapter.notifyDataSetChanged(); // swipeRefreshLayout.setRefreshing(false); // } // }); // RequestQueue requestQueue = Volley.newRequestQueue(this); // requestQueue.add(jar); // } @Override public void onClick(View view) {
ConnectionHelper ch = new ConnectionHelper(ReportActivity.this.getApplicationContext());
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/receiver/BootReceiver.java
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/services/SIMCheckService.java // public class SIMCheckService extends IntentService { // // String idSIM1; // int idSIM2; // Boolean isSIM1Detected, isSIM2Detected; // Context context; // static TelephonyManager telephony; // SharedPreferences defaultPrefs; // // public SIMCheckService() { // super("SIMCheckService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // // context = getApplicationContext(); // telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // defaultPrefs = PreferenceManager.getDefaultSharedPreferences(context); // // // isSIM1Detected = telephony.getDataState()==telephony.SIM_STATE_READY; // if(telephony.getSimSerialNumber()!=null) { // idSIM1 = telephony.getSimSerialNumber() + telephony.getNetworkOperator() + telephony.getNetworkCountryIso(); // } // // String oldSIM1 = null; // if(defaultPrefs.contains("sim_1")) { // oldSIM1 = defaultPrefs.getString("sim_1", ""); // } // // //SIM not found // if(idSIM1==null) return; // // //SIM Check // if(oldSIM1==null || (wasPresent(idSIM1, oldSIM1)==false)) { // //show lock // Toast.makeText(getApplicationContext(), "SIM Change Detected", Toast.LENGTH_SHORT).show(); // showLock(idSIM1); // return; // } // // } // // private Boolean wasPresent(String id, String oldSIM) { // if(oldSIM!=null ) { // if(oldSIM.equals(id+"")) { // return true; // } // return false; // } // return false; // } // // private void showLock(final String id) { // Intent passwordAct = new Intent(context, PasswordActivity.class); // passwordAct.putExtra("PACKAGE_NAME", "SIM Change"); // passwordAct.putExtra("device_id", id+""); // passwordAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); // context.startActivity(passwordAct); // } // // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import org.owasp.seraphimdroid.services.SIMCheckService;
package org.owasp.seraphimdroid.receiver; public class BootReceiver extends BroadcastReceiver { private AlarmManager alarmMgr; private PendingIntent alarmIntent; @Override public void onReceive(Context context, Intent arg1) { if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) { //Alarm Manager for Settings Check alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, SettingsCheckAlarmReceiver.class); alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0); SharedPreferences defaults = PreferenceManager .getDefaultSharedPreferences(context); java.util.Calendar calendar = java.util.Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); //Run at Midnight calendar.set(java.util.Calendar.HOUR_OF_DAY, 0); calendar.set(java.util.Calendar.MINUTE, 0); alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), defaults.getInt("settings_interval", 24*60*60*1000), alarmIntent); //SIM Card Service
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/services/SIMCheckService.java // public class SIMCheckService extends IntentService { // // String idSIM1; // int idSIM2; // Boolean isSIM1Detected, isSIM2Detected; // Context context; // static TelephonyManager telephony; // SharedPreferences defaultPrefs; // // public SIMCheckService() { // super("SIMCheckService"); // } // // @Override // protected void onHandleIntent(Intent intent) { // // context = getApplicationContext(); // telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // defaultPrefs = PreferenceManager.getDefaultSharedPreferences(context); // // // isSIM1Detected = telephony.getDataState()==telephony.SIM_STATE_READY; // if(telephony.getSimSerialNumber()!=null) { // idSIM1 = telephony.getSimSerialNumber() + telephony.getNetworkOperator() + telephony.getNetworkCountryIso(); // } // // String oldSIM1 = null; // if(defaultPrefs.contains("sim_1")) { // oldSIM1 = defaultPrefs.getString("sim_1", ""); // } // // //SIM not found // if(idSIM1==null) return; // // //SIM Check // if(oldSIM1==null || (wasPresent(idSIM1, oldSIM1)==false)) { // //show lock // Toast.makeText(getApplicationContext(), "SIM Change Detected", Toast.LENGTH_SHORT).show(); // showLock(idSIM1); // return; // } // // } // // private Boolean wasPresent(String id, String oldSIM) { // if(oldSIM!=null ) { // if(oldSIM.equals(id+"")) { // return true; // } // return false; // } // return false; // } // // private void showLock(final String id) { // Intent passwordAct = new Intent(context, PasswordActivity.class); // passwordAct.putExtra("PACKAGE_NAME", "SIM Change"); // passwordAct.putExtra("device_id", id+""); // passwordAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); // context.startActivity(passwordAct); // } // // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/receiver/BootReceiver.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import org.owasp.seraphimdroid.services.SIMCheckService; package org.owasp.seraphimdroid.receiver; public class BootReceiver extends BroadcastReceiver { private AlarmManager alarmMgr; private PendingIntent alarmIntent; @Override public void onReceive(Context context, Intent arg1) { if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) { //Alarm Manager for Settings Check alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, SettingsCheckAlarmReceiver.class); alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0); SharedPreferences defaults = PreferenceManager .getDefaultSharedPreferences(context); java.util.Calendar calendar = java.util.Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); //Run at Midnight calendar.set(java.util.Calendar.HOUR_OF_DAY, 0); calendar.set(java.util.Calendar.MINUTE, 0); alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), defaults.getInt("settings_interval", 24*60*60*1000), alarmIntent); //SIM Card Service
context.startService(new Intent(context, SIMCheckService.class));
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/ServiceLockFragment.java
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/adapter/ServicesLockerAdapter.java // public class ServicesLockerAdapter extends BaseAdapter { // // Context context; // private List<String> lockedServices; // // public ServicesLockerAdapter(Context context) { // this.context = context; // lockedServices = new ArrayList<String>(10); // generateLockedServices(); // } // // @Override // public int getCount() { // return 3; // } // // @Override // public Object getItem(int position) { // return labels[position]; // } // // @Override // public long getItemId(int position) { // return 0; // } // // @Override // public View getView(final int position, View view, ViewGroup parent) { // if (view == null) { // LayoutInflater inflater = LayoutInflater.from(context); // view = inflater.inflate(R.layout.app_locker_item, parent, false); // } // // final String service = (String) getItem(position); // // // Initializing Views. // TextView tvLabel = (TextView) view // .findViewById(R.id.tv_app_locker_label); // tvLabel.setText(labels[position]); // TextView tvAppType = (TextView) view // .findViewById(R.id.tv_app_locker_app_type); // tvAppType.setText(descriptions[position]); // ImageView imgIcon = (ImageView) view.findViewById(R.id.app_locker_icon); // imgIcon.setBackgroundResource(icons[position]); // // ToggleButton tb = (ToggleButton) view.findViewById(R.id.tb_is_locked); // // if (lockedServices.contains(service)) { // tb.setChecked(true); // tb.setText("Locked"); // } else { // tb.setChecked(false); // tb.setText("Unlocked"); // } // // tb.setTag(service); // tb.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View view) { // ToggleButton tb = (ToggleButton) view; // String tag = (String) tb.getTag(); // // DatabaseHelper dbHelper = new DatabaseHelper(context); // SQLiteDatabase db = dbHelper.getWritableDatabase(); // Cursor cursor = db.rawQuery( // "SELECT * FROM services WHERE service_name=\'" + tag // + "\'", null); // // if (tag.equals(service)) { // if (tb.isChecked()) { // // if (!cursor.moveToNext()) { // ContentValues cv = new ContentValues(); // cv.put("service_name", tag); // db.insert(DatabaseHelper.TABLE_SERVICES_LOCKS, null, cv); // Toast.makeText(context, "Locked: " + service, // Toast.LENGTH_SHORT).show(); // } // } else { // // if (cursor.moveToNext()) { // String[] whereArgs = { tag }; // db.delete(DatabaseHelper.TABLE_SERVICES_LOCKS, // "service_name=?", whereArgs); // Toast.makeText(context, "Unlocked: " + service, // Toast.LENGTH_SHORT).show(); // } // // } // } // cursor.close(); // db.close(); // dbHelper.close(); // generateLockedServices(); // } // }); // // return view; // } // // private void generateLockedServices() { // lockedServices.clear(); // DatabaseHelper dbHelper = new DatabaseHelper(this.context); // SQLiteDatabase db = dbHelper.getReadableDatabase(); // String[] selections = { "service_name" }; // Cursor cursor = db.query(DatabaseHelper.TABLE_SERVICES_LOCKS, selections, null, // null, null, null, null); // while (cursor.moveToNext()) { // lockedServices.add(cursor.getString(0)); // } // cursor.close(); // db.close(); // dbHelper.close(); // notifyDataSetChanged(); // } // // String[] labels = { // "WiFi", // "Bluetooth", // "Mobile Network Data" // }; // // String[] descriptions = { // "Prevent turning on/off WiFi", // "Prevent turning on/off Bluetooth", // "Prevent turning on/off Mobile Data" // }; // // int[] icons = { // R.drawable.icon_wifi, // R.drawable.icon_bluetooth, // R.drawable.icon_data // }; // // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import org.owasp.seraphimdroid.adapter.ServicesLockerAdapter;
package org.owasp.seraphimdroid; public class ServiceLockFragment extends Fragment{ private ListView lvServicesLockerList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_services_locker, container, false); lvServicesLockerList = (ListView) view.findViewById(R.id.lv_app_locker); lvServicesLockerList
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/adapter/ServicesLockerAdapter.java // public class ServicesLockerAdapter extends BaseAdapter { // // Context context; // private List<String> lockedServices; // // public ServicesLockerAdapter(Context context) { // this.context = context; // lockedServices = new ArrayList<String>(10); // generateLockedServices(); // } // // @Override // public int getCount() { // return 3; // } // // @Override // public Object getItem(int position) { // return labels[position]; // } // // @Override // public long getItemId(int position) { // return 0; // } // // @Override // public View getView(final int position, View view, ViewGroup parent) { // if (view == null) { // LayoutInflater inflater = LayoutInflater.from(context); // view = inflater.inflate(R.layout.app_locker_item, parent, false); // } // // final String service = (String) getItem(position); // // // Initializing Views. // TextView tvLabel = (TextView) view // .findViewById(R.id.tv_app_locker_label); // tvLabel.setText(labels[position]); // TextView tvAppType = (TextView) view // .findViewById(R.id.tv_app_locker_app_type); // tvAppType.setText(descriptions[position]); // ImageView imgIcon = (ImageView) view.findViewById(R.id.app_locker_icon); // imgIcon.setBackgroundResource(icons[position]); // // ToggleButton tb = (ToggleButton) view.findViewById(R.id.tb_is_locked); // // if (lockedServices.contains(service)) { // tb.setChecked(true); // tb.setText("Locked"); // } else { // tb.setChecked(false); // tb.setText("Unlocked"); // } // // tb.setTag(service); // tb.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View view) { // ToggleButton tb = (ToggleButton) view; // String tag = (String) tb.getTag(); // // DatabaseHelper dbHelper = new DatabaseHelper(context); // SQLiteDatabase db = dbHelper.getWritableDatabase(); // Cursor cursor = db.rawQuery( // "SELECT * FROM services WHERE service_name=\'" + tag // + "\'", null); // // if (tag.equals(service)) { // if (tb.isChecked()) { // // if (!cursor.moveToNext()) { // ContentValues cv = new ContentValues(); // cv.put("service_name", tag); // db.insert(DatabaseHelper.TABLE_SERVICES_LOCKS, null, cv); // Toast.makeText(context, "Locked: " + service, // Toast.LENGTH_SHORT).show(); // } // } else { // // if (cursor.moveToNext()) { // String[] whereArgs = { tag }; // db.delete(DatabaseHelper.TABLE_SERVICES_LOCKS, // "service_name=?", whereArgs); // Toast.makeText(context, "Unlocked: " + service, // Toast.LENGTH_SHORT).show(); // } // // } // } // cursor.close(); // db.close(); // dbHelper.close(); // generateLockedServices(); // } // }); // // return view; // } // // private void generateLockedServices() { // lockedServices.clear(); // DatabaseHelper dbHelper = new DatabaseHelper(this.context); // SQLiteDatabase db = dbHelper.getReadableDatabase(); // String[] selections = { "service_name" }; // Cursor cursor = db.query(DatabaseHelper.TABLE_SERVICES_LOCKS, selections, null, // null, null, null, null); // while (cursor.moveToNext()) { // lockedServices.add(cursor.getString(0)); // } // cursor.close(); // db.close(); // dbHelper.close(); // notifyDataSetChanged(); // } // // String[] labels = { // "WiFi", // "Bluetooth", // "Mobile Network Data" // }; // // String[] descriptions = { // "Prevent turning on/off WiFi", // "Prevent turning on/off Bluetooth", // "Prevent turning on/off Mobile Data" // }; // // int[] icons = { // R.drawable.icon_wifi, // R.drawable.icon_bluetooth, // R.drawable.icon_data // }; // // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/ServiceLockFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import org.owasp.seraphimdroid.adapter.ServicesLockerAdapter; package org.owasp.seraphimdroid; public class ServiceLockFragment extends Fragment{ private ListView lvServicesLockerList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_services_locker, container, false); lvServicesLockerList = (ListView) view.findViewById(R.id.lv_app_locker); lvServicesLockerList
.setAdapter(new ServicesLockerAdapter(getActivity()));
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/adapter/FeedbackListAdapter.java
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Feedback.java // public class Feedback { // // private String title; // private String description; // private int upvotes; // // public Feedback() { // } // // public Feedback(String title, String description, int upvotes) { // this.title = title; // this.description = description; // this.upvotes = upvotes; // // } // // public int getUpvotes() { // return upvotes; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.owasp.seraphimdroid.R; import org.owasp.seraphimdroid.model.Feedback; import java.util.List;
package org.owasp.seraphimdroid.adapter; /** * Created by addiittya on 30/06/16. */ public class FeedbackListAdapter extends BaseAdapter { private Activity activity; private LayoutInflater inflater;
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/model/Feedback.java // public class Feedback { // // private String title; // private String description; // private int upvotes; // // public Feedback() { // } // // public Feedback(String title, String description, int upvotes) { // this.title = title; // this.description = description; // this.upvotes = upvotes; // // } // // public int getUpvotes() { // return upvotes; // } // // public void setUpvotes(int upvotes) { // this.upvotes = upvotes; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/adapter/FeedbackListAdapter.java import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.owasp.seraphimdroid.R; import org.owasp.seraphimdroid.model.Feedback; import java.util.List; package org.owasp.seraphimdroid.adapter; /** * Created by addiittya on 30/06/16. */ public class FeedbackListAdapter extends BaseAdapter { private Activity activity; private LayoutInflater inflater;
private List<Feedback> fbList;
nikolamilosevic86/owasp-seraphimdroid
Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/receiver/LockLauncher.java
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/services/AppLockService.java // public class AppLockService extends Service { // // private Handler handler; // private Context context; // private Thread launchChecker; // // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public void onCreate() { // handler = new Handler(getMainLooper()); // context = getApplicationContext(); // launchChecker = new org.owasp.seraphimdroid.services.CheckAppLaunchThread(handler, context); // super.onCreate(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // while (true) { // if (!launchChecker.isAlive()) // launchChecker.start(); // return START_STICKY; // // } // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; import org.owasp.seraphimdroid.services.AppLockService;
package org.owasp.seraphimdroid.receiver; public class LockLauncher extends BroadcastReceiver { private static final String TAG = "LockLauncher"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_BOOT_COMPLETED) || action.equals(Intent.ACTION_SCREEN_ON)) {
// Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/services/AppLockService.java // public class AppLockService extends Service { // // private Handler handler; // private Context context; // private Thread launchChecker; // // @Override // public IBinder onBind(Intent intent) { // return null; // } // // @Override // public void onCreate() { // handler = new Handler(getMainLooper()); // context = getApplicationContext(); // launchChecker = new org.owasp.seraphimdroid.services.CheckAppLaunchThread(handler, context); // super.onCreate(); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // while (true) { // if (!launchChecker.isAlive()) // launchChecker.start(); // return START_STICKY; // // } // } // } // Path: Seraphimdroid/app/src/main/java/org/owasp/seraphimdroid/receiver/LockLauncher.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; import org.owasp.seraphimdroid.services.AppLockService; package org.owasp.seraphimdroid.receiver; public class LockLauncher extends BroadcastReceiver { private static final String TAG = "LockLauncher"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_BOOT_COMPLETED) || action.equals(Intent.ACTION_SCREEN_ON)) {
context.startService(new Intent(context, AppLockService.class));
nikolamilosevic86/owasp-seraphimdroid
Resources/src/org/owasp/seraphimdroid/BlockerFragment.java
// Path: Resources/src/org/owasp/seraphimdroid/adapter/TabsPagerAdapter.java // public class TabsPagerAdapter extends FragmentStatePagerAdapter{ // // public TabsPagerAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int index) { // // switch (index) { // case 0: // // Top Rated fragment activity // return new CallLogFragment(); // case 1: // // Games fragment activity // return new SMSLogFragment(); // // case 2: // // Movies fragment activity // return new USSDLogFragment(); // } // // return null; // } // // @Override // public int getCount() { // // get item count - equal to number of tabs // return 3; // } // // }
import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import org.owasp.seraphimdroid.adapter.TabsPagerAdapter;
package org.owasp.seraphimdroid; public class BlockerFragment extends Fragment implements OnPageChangeListener, OnTabChangeListener { private TabHost tabHost; private ViewPager viewPager; private int tabNo = 5; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { tabNo = getActivity().getIntent().getIntExtra("TAB_NO", 5); } catch (Exception e) { e.printStackTrace(); } View view = inflater.inflate(R.layout.fragment_blocker, container, false); tabHost = (TabHost) view.findViewById(R.id.tabhost); tabHost.setup(); initTabs(); viewPager = (ViewPager) view.findViewById(R.id.viewpager);
// Path: Resources/src/org/owasp/seraphimdroid/adapter/TabsPagerAdapter.java // public class TabsPagerAdapter extends FragmentStatePagerAdapter{ // // public TabsPagerAdapter(FragmentManager fm) { // super(fm); // } // // @Override // public Fragment getItem(int index) { // // switch (index) { // case 0: // // Top Rated fragment activity // return new CallLogFragment(); // case 1: // // Games fragment activity // return new SMSLogFragment(); // // case 2: // // Movies fragment activity // return new USSDLogFragment(); // } // // return null; // } // // @Override // public int getCount() { // // get item count - equal to number of tabs // return 3; // } // // } // Path: Resources/src/org/owasp/seraphimdroid/BlockerFragment.java import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; import org.owasp.seraphimdroid.adapter.TabsPagerAdapter; package org.owasp.seraphimdroid; public class BlockerFragment extends Fragment implements OnPageChangeListener, OnTabChangeListener { private TabHost tabHost; private ViewPager viewPager; private int tabNo = 5; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { tabNo = getActivity().getIntent().getIntExtra("TAB_NO", 5); } catch (Exception e) { e.printStackTrace(); } View view = inflater.inflate(R.layout.fragment_blocker, container, false); tabHost = (TabHost) view.findViewById(R.id.tabhost); tabHost.setup(); initTabs(); viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new TabsPagerAdapter(getActivity()
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnection.java
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // } // // Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnection extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnection(
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // } // // Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnection.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnection extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnection(
SignalFxReceiverEndpoint endpoint, int timeoutMs,
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnection.java
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // } // // Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnection extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnection( SignalFxReceiverEndpoint endpoint, int timeoutMs, HttpClientConnectionManager httpClientConnectionManager) { super(endpoint, timeoutMs, httpClientConnectionManager); } @Override protected HttpEntity getEntityForVersion(List<SignalFxProtocolBuffers.DataPoint> dataPoints) { return new InputStreamEntity(
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // } // // Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnection.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnection extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnection( SignalFxReceiverEndpoint endpoint, int timeoutMs, HttpClientConnectionManager httpClientConnectionManager) { super(endpoint, timeoutMs, httpClientConnectionManager); } @Override protected HttpEntity getEntityForVersion(List<SignalFxProtocolBuffers.DataPoint> dataPoints) { return new InputStreamEntity(
new ProtocolBufferStreamingInputStream<SignalFxProtocolBuffers.DataPoint>(
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnection.java
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // } // // Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnection extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnection( SignalFxReceiverEndpoint endpoint, int timeoutMs, HttpClientConnectionManager httpClientConnectionManager) { super(endpoint, timeoutMs, httpClientConnectionManager); } @Override protected HttpEntity getEntityForVersion(List<SignalFxProtocolBuffers.DataPoint> dataPoints) { return new InputStreamEntity( new ProtocolBufferStreamingInputStream<SignalFxProtocolBuffers.DataPoint>( dataPoints.iterator()), PROTO_TYPE); } @Override protected String getEndpointForAddDatapoints() { return "/v1/datapoint"; } @Override public Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes)
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // } // // Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnection.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnection extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnection( SignalFxReceiverEndpoint endpoint, int timeoutMs, HttpClientConnectionManager httpClientConnectionManager) { super(endpoint, timeoutMs, httpClientConnectionManager); } @Override protected HttpEntity getEntityForVersion(List<SignalFxProtocolBuffers.DataPoint> dataPoints) { return new InputStreamEntity( new ProtocolBufferStreamingInputStream<SignalFxProtocolBuffers.DataPoint>( dataPoints.iterator()), PROTO_TYPE); } @Override protected String getEndpointForAddDatapoints() { return "/v1/datapoint"; } @Override public Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes)
throws SignalFxMetricsException {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/signalflow/ChannelMessage.java
// Path: signalfx-java/src/main/java/com/signalfx/signalflow/StreamMessage.java // public static enum Kind { // // CONTROL("control-message",(byte) 1), // INFORMATION("message",(byte) 2), // EVENT("event",(byte) 3), // METADATA("metadata",(byte) 4), // DATA("data",(byte) 5), // ERROR("error",(byte) 6), // EXPIRED_TSID("expired-tsid",(byte) 10); // // private final String specName; // private final byte type; // // Kind(String specName, byte type) { // this.specName = specName; // this.type = type; // } // // public byte getBinaryType() { // return type; // } // // public String toString() { // return this.specName; // } // // private static final Map<String, Kind> SPECNAME_KINDS = new HashMap<String, Kind>(); // private static final Map<Integer, Kind> BINARYTYPE_KINDS = new HashMap<Integer, Kind>(); // static { // for (Kind kind : Kind.values()) { // SPECNAME_KINDS.put(kind.specName, kind); // BINARYTYPE_KINDS.put(new Integer(kind.getBinaryType()), kind); // } // } // // public static Kind fromSpecName(String specName) { // Kind kind = SPECNAME_KINDS.get(specName); // Preconditions.checkArgument(kind != null); // return kind; // } // // public static Kind fromBinaryType(int binaryType) { // Kind kind = BINARYTYPE_KINDS.get(binaryType); // Preconditions.checkArgument(kind != null); // return kind; // } // };
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.signalfx.signalflow.StreamMessage.Kind;
/* * Copyright (C) 2016 SignalFx, Inc. All rights reserved. */ package com.signalfx.signalflow; /** * Base class for stream messages received from a SignalFlow computation. * * @author dgriff */ public abstract class ChannelMessage { /** * Enumeration of types of channel messages */ public static enum Type {
// Path: signalfx-java/src/main/java/com/signalfx/signalflow/StreamMessage.java // public static enum Kind { // // CONTROL("control-message",(byte) 1), // INFORMATION("message",(byte) 2), // EVENT("event",(byte) 3), // METADATA("metadata",(byte) 4), // DATA("data",(byte) 5), // ERROR("error",(byte) 6), // EXPIRED_TSID("expired-tsid",(byte) 10); // // private final String specName; // private final byte type; // // Kind(String specName, byte type) { // this.specName = specName; // this.type = type; // } // // public byte getBinaryType() { // return type; // } // // public String toString() { // return this.specName; // } // // private static final Map<String, Kind> SPECNAME_KINDS = new HashMap<String, Kind>(); // private static final Map<Integer, Kind> BINARYTYPE_KINDS = new HashMap<Integer, Kind>(); // static { // for (Kind kind : Kind.values()) { // SPECNAME_KINDS.put(kind.specName, kind); // BINARYTYPE_KINDS.put(new Integer(kind.getBinaryType()), kind); // } // } // // public static Kind fromSpecName(String specName) { // Kind kind = SPECNAME_KINDS.get(specName); // Preconditions.checkArgument(kind != null); // return kind; // } // // public static Kind fromBinaryType(int binaryType) { // Kind kind = BINARYTYPE_KINDS.get(binaryType); // Preconditions.checkArgument(kind != null); // return kind; // } // }; // Path: signalfx-java/src/main/java/com/signalfx/signalflow/ChannelMessage.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.signalfx.signalflow.StreamMessage.Kind; /* * Copyright (C) 2016 SignalFx, Inc. All rights reserved. */ package com.signalfx.signalflow; /** * Base class for stream messages received from a SignalFlow computation. * * @author dgriff */ public abstract class ChannelMessage { /** * Enumeration of types of channel messages */ public static enum Type {
STREAM_START(Kind.CONTROL),
signalfx/signalfx-java
signalfx-codahale/src/main/java/com/signalfx/codahale/reporter/MetricMetadata.java
// Path: signalfx-codahale/src/main/java/com/signalfx/codahale/metrics/MetricBuilder.java // public interface MetricBuilder<T extends Metric> { // public T newMetric(); // // public boolean isInstance(Metric metric); // // public MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() { // @Override // public Counter newMetric() { // return new Counter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Counter.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new Histogram(new ExponentiallyDecayingReservoir()); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> RESETTING_HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new ResettingHistogram(); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() { // @Override // public Meter newMetric() { // return new Meter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Meter.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new Timer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> RESETTING_TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new ResettingTimer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // }
import java.util.Map; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Optional; import com.signalfx.codahale.metrics.MetricBuilder; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.codahale.reporter; /** * Allows users to modify a metric with different source or metric parts than the default we pick * from codahale. Note: This class <b>must</b> be thread safe. */ public interface MetricMetadata { public static final String SOURCE = "source"; public static final String METRIC = "metric"; public Map<String, String> getTags(Metric metric); public Optional<SignalFxProtocolBuffers.MetricType> getMetricType(Metric metric); /** * Create an object to tag a metric with data. Registering two different metrics with the same * metadata will result in an exception. In that case, use {@link #forBuilder(com.signalfx.codahale.metrics.MetricBuilder)} * @param metric The metric will tag. * @param <M> The type of metric. It is implied by the metric type. * @return An object to tag the given metric. */ public <M extends Metric> Tagger<M> forMetric(M metric); @Deprecated public <M extends Metric> Tagger<M> tagMetric(M metric); /** * Create a tagger for a type of objects. This is different than {@link #forMetric(com.codahale.metrics.Metric)} * because it will not use the builder to create a metric unless if it already exists. * @param metricBuilder The builder that creates metrics. * @param <M> The type of metric to create. * @return An object to tag metrics. */
// Path: signalfx-codahale/src/main/java/com/signalfx/codahale/metrics/MetricBuilder.java // public interface MetricBuilder<T extends Metric> { // public T newMetric(); // // public boolean isInstance(Metric metric); // // public MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() { // @Override // public Counter newMetric() { // return new Counter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Counter.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new Histogram(new ExponentiallyDecayingReservoir()); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> RESETTING_HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new ResettingHistogram(); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() { // @Override // public Meter newMetric() { // return new Meter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Meter.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new Timer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> RESETTING_TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new ResettingTimer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // } // Path: signalfx-codahale/src/main/java/com/signalfx/codahale/reporter/MetricMetadata.java import java.util.Map; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Optional; import com.signalfx.codahale.metrics.MetricBuilder; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.codahale.reporter; /** * Allows users to modify a metric with different source or metric parts than the default we pick * from codahale. Note: This class <b>must</b> be thread safe. */ public interface MetricMetadata { public static final String SOURCE = "source"; public static final String METRIC = "metric"; public Map<String, String> getTags(Metric metric); public Optional<SignalFxProtocolBuffers.MetricType> getMetricType(Metric metric); /** * Create an object to tag a metric with data. Registering two different metrics with the same * metadata will result in an exception. In that case, use {@link #forBuilder(com.signalfx.codahale.metrics.MetricBuilder)} * @param metric The metric will tag. * @param <M> The type of metric. It is implied by the metric type. * @return An object to tag the given metric. */ public <M extends Metric> Tagger<M> forMetric(M metric); @Deprecated public <M extends Metric> Tagger<M> tagMetric(M metric); /** * Create a tagger for a type of objects. This is different than {@link #forMetric(com.codahale.metrics.Metric)} * because it will not use the builder to create a metric unless if it already exists. * @param metricBuilder The builder that creates metrics. * @param <M> The type of metric to create. * @return An object to tag metrics. */
public <M extends Metric> BuilderTagger<M> forBuilder(MetricBuilder<M> metricBuilder);
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricError.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import com.signalfx.metrics.SignalFxMetricsException;
package com.signalfx.metrics.errorhandler; /** * An error that happened trying to send a metric. */ public interface MetricError { /** * A code value that represents the type of error * @return MetricErrorType code for the error */ MetricErrorType getMetricErrorType(); /** * Human readable message describing the error. * @return Easy to read message describing the error. */ String getMessage(); /** * An exception, if any, that triggered this error. Can be null! * @return The exception that triggered this error, or null if no exception caused this error. */
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricError.java import com.signalfx.metrics.SignalFxMetricsException; package com.signalfx.metrics.errorhandler; /** * An error that happened trying to send a metric. */ public interface MetricError { /** * A code value that represents the type of error * @return MetricErrorType code for the error */ MetricErrorType getMetricErrorType(); /** * Human readable message describing the error. * @return Easy to read message describing the error. */ String getMessage(); /** * An exception, if any, that triggered this error. Can be null! * @return The exception that triggered this error, or null if no exception caused this error. */
SignalFxMetricsException getException();
signalfx/signalfx-java
signalfx-codahale/src/main/java/com/signalfx/codahale/reporter/IncrementalCounter.java
// Path: signalfx-codahale/src/main/java/com/signalfx/codahale/metrics/MetricBuilder.java // public interface MetricBuilder<T extends Metric> { // public T newMetric(); // // public boolean isInstance(Metric metric); // // public MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() { // @Override // public Counter newMetric() { // return new Counter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Counter.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new Histogram(new ExponentiallyDecayingReservoir()); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> RESETTING_HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new ResettingHistogram(); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() { // @Override // public Meter newMetric() { // return new Meter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Meter.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new Timer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> RESETTING_TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new ResettingTimer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // }
import com.codahale.metrics.Counter; import com.codahale.metrics.Metric; import com.signalfx.codahale.metrics.MetricBuilder;
package com.signalfx.codahale.reporter; /** * <p> * An {@link com.signalfx.codahale.reporter.IncrementalCounter} is a counter that reports * incremental values to SignalFx rather than absolute counts. For example, * a regular {@link com.codahale.metrics.Counter} reports a monotonically increasing series of * values (1, 2, 3, 4, ...) while this class reports a series of increments (+1, +1, +1, +1), but * both represent the same rate of 1 unit per reporting interval. A * {@link com.codahale.metrics.Counter} created the regular Codahale way is the preferred way * to report incremental values to SignalFx when possible. * </p> * <p> * An example use case of this class would be if you wanted to count the number of requests to a webpage, * but didn't care about that as a dimension of the code serving the request. So instead * of reporting source=hostname metric=webpage.user_login.hits", which multiplies by the * number of different source=hostname that are reporting, you can report the metric as * source=webpage metric=user_login.hits and all servers will increment the same metric, even though * they have different rolling counts. * </p> * <p> * A {@link com.codahale.metrics.Counter} assumes metric type * {@link com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType#CUMULATIVE_COUNTER}, * while this class assumes metric type * {@link com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType#COUNTER} */ public class IncrementalCounter extends Counter { /** * The last value when {@link #getCountChange()} was called. */ private long lastValue; /** * Returns the difference between the current value of the counter and the value when this * function was last called. * * @return Counter difference */ public synchronized long getCountChange() { final long currentCount = getCount(); final long countChange = currentCount - lastValue; lastValue = currentCount; return countChange; }
// Path: signalfx-codahale/src/main/java/com/signalfx/codahale/metrics/MetricBuilder.java // public interface MetricBuilder<T extends Metric> { // public T newMetric(); // // public boolean isInstance(Metric metric); // // public MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() { // @Override // public Counter newMetric() { // return new Counter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Counter.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new Histogram(new ExponentiallyDecayingReservoir()); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> RESETTING_HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new ResettingHistogram(); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() { // @Override // public Meter newMetric() { // return new Meter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Meter.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new Timer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> RESETTING_TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new ResettingTimer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // } // Path: signalfx-codahale/src/main/java/com/signalfx/codahale/reporter/IncrementalCounter.java import com.codahale.metrics.Counter; import com.codahale.metrics.Metric; import com.signalfx.codahale.metrics.MetricBuilder; package com.signalfx.codahale.reporter; /** * <p> * An {@link com.signalfx.codahale.reporter.IncrementalCounter} is a counter that reports * incremental values to SignalFx rather than absolute counts. For example, * a regular {@link com.codahale.metrics.Counter} reports a monotonically increasing series of * values (1, 2, 3, 4, ...) while this class reports a series of increments (+1, +1, +1, +1), but * both represent the same rate of 1 unit per reporting interval. A * {@link com.codahale.metrics.Counter} created the regular Codahale way is the preferred way * to report incremental values to SignalFx when possible. * </p> * <p> * An example use case of this class would be if you wanted to count the number of requests to a webpage, * but didn't care about that as a dimension of the code serving the request. So instead * of reporting source=hostname metric=webpage.user_login.hits", which multiplies by the * number of different source=hostname that are reporting, you can report the metric as * source=webpage metric=user_login.hits and all servers will increment the same metric, even though * they have different rolling counts. * </p> * <p> * A {@link com.codahale.metrics.Counter} assumes metric type * {@link com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType#CUMULATIVE_COUNTER}, * while this class assumes metric type * {@link com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType#COUNTER} */ public class IncrementalCounter extends Counter { /** * The last value when {@link #getCountChange()} was called. */ private long lastValue; /** * Returns the difference between the current value of the counter and the value when this * function was last called. * * @return Counter difference */ public synchronized long getCountChange() { final long currentCount = getCount(); final long countChange = currentCount - lastValue; lastValue = currentCount; return countChange; }
public final static class Builder implements MetricBuilder<IncrementalCounter> {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs;
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs;
private final DataPointReceiverFactory dataPointReceiverFactory;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs; private final DataPointReceiverFactory dataPointReceiverFactory;
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs; private final DataPointReceiverFactory dataPointReceiverFactory;
private final EventReceiverFactory eventReceiverFactory;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs; private final DataPointReceiverFactory dataPointReceiverFactory; private final EventReceiverFactory eventReceiverFactory;
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs; private final DataPointReceiverFactory dataPointReceiverFactory; private final EventReceiverFactory eventReceiverFactory;
private final AuthToken authToken;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs; private final DataPointReceiverFactory dataPointReceiverFactory; private final EventReceiverFactory eventReceiverFactory; private final AuthToken authToken;
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; package com.signalfx.metrics.flush; /** * The primary java class to send metrics. To use this class, create a session, add points to * the session, and when you are done, close the session. For example: * * <pre> * {@code * AggregateMetricSender sender; * try (AggregateMetricSender.Session i = mf.createSession()) { * i.incrementCounter("testcounter2", 1); * i.setDatapoint( * SignalFxProtocolBuffers.DataPoint.newBuilder() * .setMetric("curtime") * .setValue( * SignalFxProtocolBuffers.Datum.newBuilder() * .setIntValue(System.currentTimeMillis())) * .addDimensions( * SignalFxProtocolBuffers.Dimension.newBuilder() * .setKey("source") * .setValue("java")) * .build()); * } * } * </pre> */ public class AggregateMetricSender { private final String defaultSourceName; private final Set<String> registeredMetricPairs; private final DataPointReceiverFactory dataPointReceiverFactory; private final EventReceiverFactory eventReceiverFactory; private final AuthToken authToken;
private final Collection<OnSendErrorHandler> onSendErrorHandlerCollection;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, dataPointReceiverFactory, null, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, null, eventReceiverFactory, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, DataPointReceiverFactory dataPointReceiverFactory, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this.defaultSourceName = requireNonNull(defaultSourceName, "defaultSourceName must be a non-null value"); this.dataPointReceiverFactory = dataPointReceiverFactory; this.eventReceiverFactory = eventReceiverFactory; this.authToken = authToken; this.onSendErrorHandlerCollection = onSendErrorHandlerCollection; this.registeredMetricPairs = new HashSet<String>(); } public String getDefaultSourceName() { return defaultSourceName; }
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, dataPointReceiverFactory, null, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, null, eventReceiverFactory, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, DataPointReceiverFactory dataPointReceiverFactory, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this.defaultSourceName = requireNonNull(defaultSourceName, "defaultSourceName must be a non-null value"); this.dataPointReceiverFactory = dataPointReceiverFactory; this.eventReceiverFactory = eventReceiverFactory; this.authToken = authToken; this.onSendErrorHandlerCollection = onSendErrorHandlerCollection; this.registeredMetricPairs = new HashSet<String>(); } public String getDefaultSourceName() { return defaultSourceName; }
private void communicateError(String message, MetricErrorType code,
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, dataPointReceiverFactory, null, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, null, eventReceiverFactory, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, DataPointReceiverFactory dataPointReceiverFactory, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this.defaultSourceName = requireNonNull(defaultSourceName, "defaultSourceName must be a non-null value"); this.dataPointReceiverFactory = dataPointReceiverFactory; this.eventReceiverFactory = eventReceiverFactory; this.authToken = authToken; this.onSendErrorHandlerCollection = onSendErrorHandlerCollection; this.registeredMetricPairs = new HashSet<String>(); } public String getDefaultSourceName() { return defaultSourceName; } private void communicateError(String message, MetricErrorType code,
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, dataPointReceiverFactory, null, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this(defaultSourceName, null, eventReceiverFactory, authToken, onSendErrorHandlerCollection); } public AggregateMetricSender(String defaultSourceName, DataPointReceiverFactory dataPointReceiverFactory, EventReceiverFactory eventReceiverFactory, AuthToken authToken, Collection<OnSendErrorHandler> onSendErrorHandlerCollection) { this.defaultSourceName = requireNonNull(defaultSourceName, "defaultSourceName must be a non-null value"); this.dataPointReceiverFactory = dataPointReceiverFactory; this.eventReceiverFactory = eventReceiverFactory; this.authToken = authToken; this.onSendErrorHandlerCollection = onSendErrorHandlerCollection; this.registeredMetricPairs = new HashSet<String>(); } public String getDefaultSourceName() { return defaultSourceName; } private void communicateError(String message, MetricErrorType code,
SignalFxMetricsException signalfxMetricsException) {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
@Override public Session setGauge(String source, String metric, long value) { setDatapoint(source, metric, SignalFxProtocolBuffers.MetricType.GAUGE, value); return this; } @Override public Session setGauge(String metric, double value) { return setGauge(defaultSourceName, metric, value); } @Override public Session setGauge(String source, String metric, double value) { setDatapoint(source, metric, SignalFxProtocolBuffers.MetricType.GAUGE, value); return this; } private void check(String metricPair, com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType metricType) { if (!registeredMetricPairs.contains(metricPair)) { toBeRegisteredMetricPairs.put(metricPair, metricType); } } @Override public void close() { final String authTokenStr; try { authTokenStr = authToken.getAuthToken();
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; @Override public Session setGauge(String source, String metric, long value) { setDatapoint(source, metric, SignalFxProtocolBuffers.MetricType.GAUGE, value); return this; } @Override public Session setGauge(String metric, double value) { return setGauge(defaultSourceName, metric, value); } @Override public Session setGauge(String source, String metric, double value) { setDatapoint(source, metric, SignalFxProtocolBuffers.MetricType.GAUGE, value); return this; } private void check(String metricPair, com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType metricType) { if (!registeredMetricPairs.contains(metricPair)) { toBeRegisteredMetricPairs.put(metricPair, metricType); } } @Override public void close() { final String authTokenStr; try { authTokenStr = authToken.getAuthToken();
} catch (NoAuthTokenException e) {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
if (!registeredMetricPairs.contains(metricPair)) { toBeRegisteredMetricPairs.put(metricPair, metricType); } } @Override public void close() { final String authTokenStr; try { authTokenStr = authToken.getAuthToken(); } catch (NoAuthTokenException e) { communicateError("Unable to get auth token", MetricErrorType.AUTH_TOKEN_ERROR, e); return; } flushDatapoints(authTokenStr); flushEvents(authTokenStr); } private void flushDatapoints(String authTokenStr) { if (pointsToFlush.isEmpty()) { return; } if (dataPointReceiverFactory == null) { communicateError("DataPointReceiverFactory object is not set", MetricErrorType.DATAPOINT_SEND_ERROR, new SignalFxMetricsException()); return; }
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; if (!registeredMetricPairs.contains(metricPair)) { toBeRegisteredMetricPairs.put(metricPair, metricType); } } @Override public void close() { final String authTokenStr; try { authTokenStr = authToken.getAuthToken(); } catch (NoAuthTokenException e) { communicateError("Unable to get auth token", MetricErrorType.AUTH_TOKEN_ERROR, e); return; } flushDatapoints(authTokenStr); flushEvents(authTokenStr); } private void flushDatapoints(String authTokenStr) { if (pointsToFlush.isEmpty()) { return; } if (dataPointReceiverFactory == null) { communicateError("DataPointReceiverFactory object is not set", MetricErrorType.DATAPOINT_SEND_ERROR, new SignalFxMetricsException()); return; }
DataPointReceiver dataPointReceiver = dataPointReceiverFactory
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // }
import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set;
} Iterator<SignalFxProtocolBuffers.DataPoint> i = pointsToFlush.iterator(); while (i.hasNext()) { SignalFxProtocolBuffers.DataPoint currentEntry = i.next(); if (!registeredMetricPairs.contains(currentEntry.getMetric())) { i.remove(); } } try { dataPointReceiver.addDataPoints(authTokenStr, pointsToFlush); } catch (SignalFxMetricsException e) { communicateError("Unable to send datapoints", MetricErrorType.DATAPOINT_SEND_ERROR, e); } } private void flushEvents(String authTokenStr) { if (eventsToFlush.isEmpty()) { return; } if (eventReceiverFactory == null) { communicateError("EventReceiverFactory object is not set", MetricErrorType.EVENT_SEND_ERROR, new SignalFxMetricsException()); return; } try {
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/AuthToken.java // public interface AuthToken { // String getAuthToken() throws NoAuthTokenException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/auth/NoAuthTokenException.java // @SuppressWarnings("serial") // public class NoAuthTokenException extends SignalFxMetricsException { // public NoAuthTokenException(String message) { // super(message); // } // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java // public interface DataPointReceiver { // void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints) // throws SignalFxMetricsException; // // void backfillDataPoints(String auth, String metric, String metricType, String orgId, Map<String,String> dimensions, // List<SignalFxProtocolBuffers.PointValue> datumPoints) // throws SignalFxMetricsException; // // Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiverFactory.java // public interface DataPointReceiverFactory { // /** // * @return A newly created datapoint receiver. // */ // DataPointReceiver createDataPointReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java // public interface EventReceiver { // void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events) // throws SignalFxMetricsException; // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiverFactory.java // public interface EventReceiverFactory { // /** // * @return A newly cleated event receiver. // */ // EventReceiver createEventReceiver(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/MetricErrorType.java // public enum MetricErrorType { // CONNECTION_ERROR, // REGISTRATION_ERROR, // INTERUPTED, // AUTH_TOKEN_ERROR, // QUEUE_FULL, // DATAPOINT_SEND_ERROR, // EVENT_SEND_ERROR // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/errorhandler/OnSendErrorHandler.java // public interface OnSendErrorHandler { // void handleError(MetricError metricError); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/flush/AggregateMetricSender.java import static java.util.Objects.requireNonNull; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.auth.AuthToken; import com.signalfx.metrics.auth.NoAuthTokenException; import com.signalfx.metrics.connection.DataPointReceiver; import com.signalfx.metrics.connection.DataPointReceiverFactory; import com.signalfx.metrics.connection.EventReceiver; import com.signalfx.metrics.connection.EventReceiverFactory; import com.signalfx.metrics.errorhandler.MetricErrorImpl; import com.signalfx.metrics.errorhandler.MetricErrorType; import com.signalfx.metrics.errorhandler.OnSendErrorHandler; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import java.io.Closeable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; } Iterator<SignalFxProtocolBuffers.DataPoint> i = pointsToFlush.iterator(); while (i.hasNext()) { SignalFxProtocolBuffers.DataPoint currentEntry = i.next(); if (!registeredMetricPairs.contains(currentEntry.getMetric())) { i.remove(); } } try { dataPointReceiver.addDataPoints(authTokenStr, pointsToFlush); } catch (SignalFxMetricsException e) { communicateError("Unable to send datapoints", MetricErrorType.DATAPOINT_SEND_ERROR, e); } } private void flushEvents(String authTokenStr) { if (eventsToFlush.isEmpty()) { return; } if (eventReceiverFactory == null) { communicateError("EventReceiverFactory object is not set", MetricErrorType.EVENT_SEND_ERROR, new SignalFxMetricsException()); return; } try {
EventReceiver eventReceiver = eventReceiverFactory.createEventReceiver();
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnectionV2.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnectionV2 extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnectionV2(
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnectionV2.java import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnectionV2 extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnectionV2(
SignalFxReceiverEndpoint endpoint, int timeoutMs,
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnectionV2.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnectionV2 extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnectionV2( SignalFxReceiverEndpoint endpoint, int timeoutMs, HttpClientConnectionManager httpClientConnectionManager) { super(endpoint, timeoutMs, httpClientConnectionManager); } @Override protected String getEndpointForAddDatapoints() { return "/v2/datapoint"; } @Override protected HttpEntity getEntityForVersion(List<SignalFxProtocolBuffers.DataPoint> dataPoints) { byte[] bodyBytes = SignalFxProtocolBuffers.DataPointUploadMessage.newBuilder() .addAllDatapoints(dataPoints).build().toByteArray(); return new ByteArrayEntity(bodyBytes, PROTO_TYPE); } @Override public Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes)
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverConnectionV2.java import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverConnectionV2 extends AbstractHttpDataPointProtobufReceiverConnection { public HttpDataPointProtobufReceiverConnectionV2( SignalFxReceiverEndpoint endpoint, int timeoutMs, HttpClientConnectionManager httpClientConnectionManager) { super(endpoint, timeoutMs, httpClientConnectionManager); } @Override protected String getEndpointForAddDatapoints() { return "/v2/datapoint"; } @Override protected HttpEntity getEntityForVersion(List<SignalFxProtocolBuffers.DataPoint> dataPoints) { byte[] bodyBytes = SignalFxProtocolBuffers.DataPointUploadMessage.newBuilder() .addAllDatapoints(dataPoints).build().toByteArray(); return new ByteArrayEntity(bodyBytes, PROTO_TYPE); } @Override public Map<String, Boolean> registerMetrics(String auth, Map<String, SignalFxProtocolBuffers.MetricType> metricTypes)
throws SignalFxMetricsException {
signalfx/signalfx-java
signalfx-codahale/src/main/java/com/signalfx/codahale/reporter/MetricMetadataImpl.java
// Path: signalfx-codahale/src/main/java/com/signalfx/codahale/metrics/MetricBuilder.java // public interface MetricBuilder<T extends Metric> { // public T newMetric(); // // public boolean isInstance(Metric metric); // // public MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() { // @Override // public Counter newMetric() { // return new Counter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Counter.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new Histogram(new ExponentiallyDecayingReservoir()); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> RESETTING_HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new ResettingHistogram(); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() { // @Override // public Meter newMetric() { // return new Meter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Meter.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new Timer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> RESETTING_TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new ResettingTimer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // }
import java.util.Collections; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.signalfx.codahale.metrics.MetricBuilder; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType;
return Optional.absent(); } else { return Optional.of(existingMetaData.metricType); } } @Override public <M extends Metric> Tagger<M> tagMetric(M metric) { return forMetric(metric); } @Override public <M extends Metric> Tagger<M> forMetric(M metric) { Metadata metadata = metaDataCollection.get(metric); if (metadata == null) { synchronized (this) { metadata = metaDataCollection.get(metric); if (metadata == null) { metadata = new Metadata(); Metadata oldMetaData = metaDataCollection.put(metric, metadata); Preconditions.checkArgument(oldMetaData == null, "Concurrency issue adding metadata"); } } } return new TaggerImpl<M>(metric, metadata); } @Override public <M extends Metric> BuilderTagger<M> forBuilder(
// Path: signalfx-codahale/src/main/java/com/signalfx/codahale/metrics/MetricBuilder.java // public interface MetricBuilder<T extends Metric> { // public T newMetric(); // // public boolean isInstance(Metric metric); // // public MetricBuilder<Counter> COUNTERS = new MetricBuilder<Counter>() { // @Override // public Counter newMetric() { // return new Counter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Counter.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new Histogram(new ExponentiallyDecayingReservoir()); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Histogram> RESETTING_HISTOGRAMS = new MetricBuilder<Histogram>() { // @Override // public Histogram newMetric() { // return new ResettingHistogram(); // } // // @Override // public boolean isInstance(Metric metric) { // return Histogram.class.isInstance(metric); // } // }; // // public MetricBuilder<Meter> METERS = new MetricBuilder<Meter>() { // @Override // public Meter newMetric() { // return new Meter(); // } // // @Override // public boolean isInstance(Metric metric) { // return Meter.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new Timer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // // public MetricBuilder<Timer> RESETTING_TIMERS = new MetricBuilder<Timer>() { // @Override // public Timer newMetric() { // return new ResettingTimer(); // } // // @Override // public boolean isInstance(Metric metric) { // return Timer.class.isInstance(metric); // } // }; // } // Path: signalfx-codahale/src/main/java/com/signalfx/codahale/reporter/MetricMetadataImpl.java import java.util.Collections; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.signalfx.codahale.metrics.MetricBuilder; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.MetricType; return Optional.absent(); } else { return Optional.of(existingMetaData.metricType); } } @Override public <M extends Metric> Tagger<M> tagMetric(M metric) { return forMetric(metric); } @Override public <M extends Metric> Tagger<M> forMetric(M metric) { Metadata metadata = metaDataCollection.get(metric); if (metadata == null) { synchronized (this) { metadata = metaDataCollection.get(metric); if (metadata == null) { metadata = new Metadata(); Metadata oldMetaData = metaDataCollection.put(metric, metadata); Preconditions.checkArgument(oldMetaData == null, "Concurrency issue adding metadata"); } } } return new TaggerImpl<M>(metric, metadata); } @Override public <M extends Metric> BuilderTagger<M> forBuilder(
MetricBuilder<M> metricBuilder) {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpEventProtobufReceiverFactory.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException;
package com.signalfx.metrics.connection; public class HttpEventProtobufReceiverFactory implements EventReceiverFactory { public static final int DEFAULT_TIMEOUT_MS = 2000; public static final int DEFAULT_VERSION = 2;
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpEventProtobufReceiverFactory.java import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; package com.signalfx.metrics.connection; public class HttpEventProtobufReceiverFactory implements EventReceiverFactory { public static final int DEFAULT_TIMEOUT_MS = 2000; public static final int DEFAULT_VERSION = 2;
private final SignalFxReceiverEndpoint endpoint;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpEventProtobufReceiverFactory.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException;
private HttpClientConnectionManager explicitHttpClientConnectionManager; private int timeoutMs = DEFAULT_TIMEOUT_MS; private int version = DEFAULT_VERSION; public HttpEventProtobufReceiverFactory(SignalFxReceiverEndpoint endpoint) { this.endpoint = endpoint; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(DEFAULT_TIMEOUT_MS); this.explicitHttpClientConnectionManager = null; } public HttpEventProtobufReceiverFactory setTimeoutMs(int timeoutMs) { this.timeoutMs = timeoutMs; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(timeoutMs); return this; } public HttpEventProtobufReceiverFactory setVersion(int version) { this.version = version; return this; } public void setHttpClientConnectionManager( HttpClientConnectionManager httpClientConnectionManager) { this.explicitHttpClientConnectionManager = httpClientConnectionManager; } @Override public EventReceiver createEventReceiver() throws
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpEventProtobufReceiverFactory.java import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; private HttpClientConnectionManager explicitHttpClientConnectionManager; private int timeoutMs = DEFAULT_TIMEOUT_MS; private int version = DEFAULT_VERSION; public HttpEventProtobufReceiverFactory(SignalFxReceiverEndpoint endpoint) { this.endpoint = endpoint; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(DEFAULT_TIMEOUT_MS); this.explicitHttpClientConnectionManager = null; } public HttpEventProtobufReceiverFactory setTimeoutMs(int timeoutMs) { this.timeoutMs = timeoutMs; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(timeoutMs); return this; } public HttpEventProtobufReceiverFactory setVersion(int version) { this.version = version; return this; } public void setHttpClientConnectionManager( HttpClientConnectionManager httpClientConnectionManager) { this.explicitHttpClientConnectionManager = httpClientConnectionManager; } @Override public EventReceiver createEventReceiver() throws
SignalFxMetricsException {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/StoredDataPointReceiver.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.Dimension;
package com.signalfx.metrics.connection; /** * Factory that just stores results to later be tested. * * @author jack */ public class StoredDataPointReceiver implements DataPointReceiver { public final List<SignalFxProtocolBuffers.DataPointOrBuilder> addDataPoints; private final Map<Pair<String, String>, List<SignalFxProtocolBuffers.Datum>> pointsFor; public final Map<String, SignalFxProtocolBuffers.MetricType> registeredMetrics; public boolean throwOnAdd = false; public StoredDataPointReceiver() { addDataPoints = Collections .synchronizedList(new ArrayList<SignalFxProtocolBuffers.DataPointOrBuilder>()); registeredMetrics = Collections.synchronizedMap(new HashMap<String, SignalFxProtocolBuffers.MetricType>()); pointsFor = Maps.newHashMap(); } @Override public void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints)
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/StoredDataPointReceiver.java import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.Dimension; package com.signalfx.metrics.connection; /** * Factory that just stores results to later be tested. * * @author jack */ public class StoredDataPointReceiver implements DataPointReceiver { public final List<SignalFxProtocolBuffers.DataPointOrBuilder> addDataPoints; private final Map<Pair<String, String>, List<SignalFxProtocolBuffers.Datum>> pointsFor; public final Map<String, SignalFxProtocolBuffers.MetricType> registeredMetrics; public boolean throwOnAdd = false; public StoredDataPointReceiver() { addDataPoints = Collections .synchronizedList(new ArrayList<SignalFxProtocolBuffers.DataPointOrBuilder>()); registeredMetrics = Collections.synchronizedMap(new HashMap<String, SignalFxProtocolBuffers.MetricType>()); pointsFor = Maps.newHashMap(); } @Override public void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints)
throws SignalFxMetricsException {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverFactory.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException;
package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverFactory implements DataPointReceiverFactory { public static final int DEFAULT_TIMEOUT_MS = 2000; public static final int DEFAULT_VERSION = 2;
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverFactory.java import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; package com.signalfx.metrics.connection; public class HttpDataPointProtobufReceiverFactory implements DataPointReceiverFactory { public static final int DEFAULT_TIMEOUT_MS = 2000; public static final int DEFAULT_VERSION = 2;
private final SignalFxReceiverEndpoint endpoint;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverFactory.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException;
private HttpClientConnectionManager explicitHttpClientConnectionManager; private int timeoutMs = DEFAULT_TIMEOUT_MS; private int version = DEFAULT_VERSION; public HttpDataPointProtobufReceiverFactory(SignalFxReceiverEndpoint endpoint) { this.endpoint = endpoint; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(DEFAULT_TIMEOUT_MS); this.explicitHttpClientConnectionManager = null; } public HttpDataPointProtobufReceiverFactory setTimeoutMs(int timeoutMs) { this.timeoutMs = timeoutMs; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(timeoutMs); return this; } public HttpDataPointProtobufReceiverFactory setVersion(int version) { this.version = version; return this; } public void setHttpClientConnectionManager( HttpClientConnectionManager httpClientConnectionManager) { this.explicitHttpClientConnectionManager = httpClientConnectionManager; } @Override public DataPointReceiver createDataPointReceiver() throws
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpDataPointProtobufReceiverFactory.java import org.apache.http.conn.HttpClientConnectionManager; import com.google.common.base.MoreObjects; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; private HttpClientConnectionManager explicitHttpClientConnectionManager; private int timeoutMs = DEFAULT_TIMEOUT_MS; private int version = DEFAULT_VERSION; public HttpDataPointProtobufReceiverFactory(SignalFxReceiverEndpoint endpoint) { this.endpoint = endpoint; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(DEFAULT_TIMEOUT_MS); this.explicitHttpClientConnectionManager = null; } public HttpDataPointProtobufReceiverFactory setTimeoutMs(int timeoutMs) { this.timeoutMs = timeoutMs; this.httpClientConnectionManager = HttpClientConnectionManagerFactory.withTimeoutMs(timeoutMs); return this; } public HttpDataPointProtobufReceiverFactory setVersion(int version) { this.version = version; return this; } public void setHttpClientConnectionManager( HttpClientConnectionManager httpClientConnectionManager) { this.explicitHttpClientConnectionManager = httpClientConnectionManager; } @Override public DataPointReceiver createDataPointReceiver() throws
SignalFxMetricsException {
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpEventProtobufReceiverConnectionV2.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // }
import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public class HttpEventProtobufReceiverConnectionV2 extends AbstractHttpEventProtobufReceiverConnection { public HttpEventProtobufReceiverConnectionV2(
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/HttpEventProtobufReceiverConnectionV2.java import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public class HttpEventProtobufReceiverConnectionV2 extends AbstractHttpEventProtobufReceiverConnection { public HttpEventProtobufReceiverConnectionV2(
SignalFxReceiverEndpoint endpoint, int timeoutMs,
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.util.List; import java.util.Map; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public interface DataPointReceiver { void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints)
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/DataPointReceiver.java import java.util.List; import java.util.Map; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public interface DataPointReceiver { void addDataPoints(String auth, List<SignalFxProtocolBuffers.DataPoint> dataPoints)
throws SignalFxMetricsException;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.util.List; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers;
package com.signalfx.metrics.connection; public interface EventReceiver { void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events)
// Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/metrics/connection/EventReceiver.java import java.util.List; import com.signalfx.metrics.SignalFxMetricsException; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers; package com.signalfx.metrics.connection; public interface EventReceiver { void addEvents(String auth, List<SignalFxProtocolBuffers.Event> events)
throws SignalFxMetricsException;
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/connection/AbstractHttpReceiverConnection.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.io.IOException; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.GzipCompressingEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException;
package com.signalfx.connection; public abstract class AbstractHttpReceiverConnection { protected static final Logger log = LoggerFactory.getLogger(AbstractHttpReceiverConnection.class); // Do not modify this line. It is auto replaced to a version number. public static final String VERSION_NUMBER = "1.0.14"; public static final String USER_AGENT = "SignalFx-java-client/" + VERSION_NUMBER; public static final String DISABLE_COMPRESSION_PROPERTY = "com.signalfx.public.java.disableHttpCompression"; protected static final ObjectMapper MAPPER = new ObjectMapper(); protected static final ContentType JSON_TYPE = ContentType.APPLICATION_JSON; protected final CloseableHttpClient client; protected final HttpHost host; protected final RequestConfig requestConfig;
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/connection/AbstractHttpReceiverConnection.java import java.io.IOException; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.GzipCompressingEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; package com.signalfx.connection; public abstract class AbstractHttpReceiverConnection { protected static final Logger log = LoggerFactory.getLogger(AbstractHttpReceiverConnection.class); // Do not modify this line. It is auto replaced to a version number. public static final String VERSION_NUMBER = "1.0.14"; public static final String USER_AGENT = "SignalFx-java-client/" + VERSION_NUMBER; public static final String DISABLE_COMPRESSION_PROPERTY = "com.signalfx.public.java.disableHttpCompression"; protected static final ObjectMapper MAPPER = new ObjectMapper(); protected static final ContentType JSON_TYPE = ContentType.APPLICATION_JSON; protected final CloseableHttpClient client; protected final HttpHost host; protected final RequestConfig requestConfig;
protected AbstractHttpReceiverConnection(SignalFxReceiverEndpoint endpoint, int timeoutMs,
signalfx/signalfx-java
signalfx-java/src/main/java/com/signalfx/connection/AbstractHttpReceiverConnection.java
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // }
import java.io.IOException; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.GzipCompressingEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException;
.setConnectTimeout(timeoutMs) .setProxy(proxy) .build(); } protected CloseableHttpResponse postToEndpoint(String auth, HttpEntity entity, String endpoint, boolean compress) throws IOException { if (compress) { entity = new GzipCompressingEntity(entity); } HttpPost post = new HttpPost(String.format("%s%s", host.toURI(), endpoint)); post.setConfig(requestConfig); if (auth != null) { post.setHeader("X-SF-TOKEN", auth); } post.setHeader("User-Agent", USER_AGENT); post.setEntity(entity); try { log.trace("Talking to endpoint {}", post); return client.execute(post); } catch (IOException e) { log.trace("Exception trying to execute {}", post, e); throw e; } } protected void checkHttpResponse(CloseableHttpResponse resp) throws
// Path: signalfx-java/src/main/java/com/signalfx/endpoint/SignalFxReceiverEndpoint.java // public interface SignalFxReceiverEndpoint { // String getScheme(); // String getHostname(); // int getPort(); // } // // Path: signalfx-java/src/main/java/com/signalfx/metrics/SignalFxMetricsException.java // public class SignalFxMetricsException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public SignalFxMetricsException() { // } // // public SignalFxMetricsException(String message) { // super(message); // } // // public SignalFxMetricsException(String message, Throwable cause) { // super(message, cause); // } // // public SignalFxMetricsException(Throwable cause) { // super(cause); // } // } // Path: signalfx-java/src/main/java/com/signalfx/connection/AbstractHttpReceiverConnection.java import java.io.IOException; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.GzipCompressingEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.signalfx.endpoint.SignalFxReceiverEndpoint; import com.signalfx.metrics.SignalFxMetricsException; .setConnectTimeout(timeoutMs) .setProxy(proxy) .build(); } protected CloseableHttpResponse postToEndpoint(String auth, HttpEntity entity, String endpoint, boolean compress) throws IOException { if (compress) { entity = new GzipCompressingEntity(entity); } HttpPost post = new HttpPost(String.format("%s%s", host.toURI(), endpoint)); post.setConfig(requestConfig); if (auth != null) { post.setHeader("X-SF-TOKEN", auth); } post.setHeader("User-Agent", USER_AGENT); post.setEntity(entity); try { log.trace("Talking to endpoint {}", post); return client.execute(post); } catch (IOException e) { log.trace("Exception trying to execute {}", post, e); throw e; } } protected void checkHttpResponse(CloseableHttpResponse resp) throws
SignalFxMetricsException {
signalfx/signalfx-java
signalfx-commons-protoc-java/src/test/java/com/signalfx/metrics/metric/ProtoBufTest.java
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Test; import com.github.os72.protobuf_3_11_1.InvalidProtocolBufferException; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.DataPoint; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.Datum; import com.google.common.base.Preconditions;
package com.signalfx.metrics.metric; /** * Simple protobuf test that shows protobufs are compiled and showing how to encode/decode them * @author jack */ @SuppressWarnings("MagicNumber") public class ProtoBufTest { @Test public void testProtoBuilders() throws InvalidProtocolBufferException { Datum D = Datum.newBuilder().setDoubleValue(1.1).build(); byte[] encoded = D.toByteArray(); Datum decoded = Datum.parseFrom(encoded); assertEquals(decoded, D); assertNotEquals(Datum.getDefaultInstance(), D); assertEquals(1.1, D.getDoubleValue(), .0001); } @Test public void testProtoStreaming() throws IOException { List<DataPoint> pointsToWrite = new ArrayList<DataPoint>(); pointsToWrite.add(DataPoint.newBuilder().setSource("tests").setMetric("testm"). setTimestamp(1234).setValue(Datum.newBuilder().setIntValue(12)).build()); pointsToWrite.add(DataPoint.newBuilder().setSource("tests").setMetric("testm"). setTimestamp(1235).setValue(Datum.newBuilder().setIntValue(13)).build()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (DataPoint dp: pointsToWrite) { dp.writeDelimitedTo(bout); } byte[] rawBytes = IOUtils.toByteArray(new ByteArrayInputStream(bout.toByteArray()));
// Path: signalfx-commons-protoc-java/src/main/java/com/signalfx/common/proto/ProtocolBufferStreamingInputStream.java // public final class ProtocolBufferStreamingInputStream<ProtocolBufferObject extends MessageLite> // extends InputStream { // // public static final int DEFAULT_STREAM_SIZE = 1024; // private final Iterator<ProtocolBufferObject> protoBufferIterator; // private final PeekableByteArrayOutputStream currentBytes; // // public ProtocolBufferStreamingInputStream( // Iterator<ProtocolBufferObject> protoBufferIterator) { // this.protoBufferIterator = protoBufferIterator; // this.currentBytes = new PeekableByteArrayOutputStream(DEFAULT_STREAM_SIZE); // } // // /** // * Fill in our byte buffer if we're out of space by reading the next protocol buffer object. // * // * @throws IOException // * If {@link MessageLite#writeDelimitedTo(java.io.OutputStream)} // * fails // */ // private void fillBytes() throws IOException { // if (currentBytes.available() > 0) { // return; // } // currentBytes.reset(); // while (protoBufferIterator.hasNext() && currentBytes.size() <= 1000) { // protoBufferIterator.next().writeDelimitedTo(currentBytes); // } // } // // @Override // public int read() throws IOException { // fillBytes(); // return currentBytes.read(); // } // // @Override // public int available() { // return currentBytes.available(); // } // // @Override // public void close() throws IOException { // super.close(); // currentBytes.close(); // } // // @Override // public int read(byte[] b, int off, int len) throws IOException { // int total_read = 0; // while (len > 0) { // fillBytes(); // int result = currentBytes.read(b, off, len); // if (result == -1) { // return total_read == 0 ? -1 : total_read; // } // len -= result; // total_read += result; // off += result; // } // return total_read; // } // } // Path: signalfx-commons-protoc-java/src/test/java/com/signalfx/metrics/metric/ProtoBufTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Test; import com.github.os72.protobuf_3_11_1.InvalidProtocolBufferException; import com.signalfx.common.proto.ProtocolBufferStreamingInputStream; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.DataPoint; import com.signalfx.metrics.protobuf.SignalFxProtocolBuffers.Datum; import com.google.common.base.Preconditions; package com.signalfx.metrics.metric; /** * Simple protobuf test that shows protobufs are compiled and showing how to encode/decode them * @author jack */ @SuppressWarnings("MagicNumber") public class ProtoBufTest { @Test public void testProtoBuilders() throws InvalidProtocolBufferException { Datum D = Datum.newBuilder().setDoubleValue(1.1).build(); byte[] encoded = D.toByteArray(); Datum decoded = Datum.parseFrom(encoded); assertEquals(decoded, D); assertNotEquals(Datum.getDefaultInstance(), D); assertEquals(1.1, D.getDoubleValue(), .0001); } @Test public void testProtoStreaming() throws IOException { List<DataPoint> pointsToWrite = new ArrayList<DataPoint>(); pointsToWrite.add(DataPoint.newBuilder().setSource("tests").setMetric("testm"). setTimestamp(1234).setValue(Datum.newBuilder().setIntValue(12)).build()); pointsToWrite.add(DataPoint.newBuilder().setSource("tests").setMetric("testm"). setTimestamp(1235).setValue(Datum.newBuilder().setIntValue(13)).build()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (DataPoint dp: pointsToWrite) { dp.writeDelimitedTo(bout); } byte[] rawBytes = IOUtils.toByteArray(new ByteArrayInputStream(bout.toByteArray()));
byte[] smartBytes = IOUtils.toByteArray(new ProtocolBufferStreamingInputStream<DataPoint>(pointsToWrite.iterator()));
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/Image.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/Image.java import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class Image implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/OrderItem.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 22/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/OrderItem.java import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 22/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class OrderItem implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/Dish.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import java.util.LinkedHashMap; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/Dish.java import java.util.LinkedHashMap; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class Dish implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/service/OrderItemService.java
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Dish.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Dish implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> reviews = new LinkedHashMap<>(); // // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/Menu.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Menu implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> mainDishes = new LinkedHashMap<>(); // private Map<String, Object> secondaryDishes = new LinkedHashMap<>(); // private Map<String, Object> otherDishes = new LinkedHashMap<>(); // private Map<String, Object> reviews = new LinkedHashMap<>(); // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/OrderItem.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class OrderItem implements Entity { // // private String id; // private String differentFeature; // private boolean paid; // private boolean ready; // private boolean delivered; // private String dishId; // private String menuId; // // @Override // public String getId() { // return this.id; // } // // @Override // public void setId(String id) { // this.id = id; // } // } // // Path: app/src/main/java/dev/wisebite/wisebite/firebase/Repository.java // public abstract class Repository<T extends Entity> implements ChildEventListener { // // private OnChangedListener listener; // // /** // * Just for the Firebase when needed // */ // public Repository () { // // } // // public interface OnChangedListener { // enum EventType {Added, Changed, Removed, Moved, Full} // // void onChanged(EventType type); // } // // public void setOnChangedListener(OnChangedListener listener) { // this.listener = listener; // } // // public abstract T insert(T item); // // public abstract T insertInternal(T item); // // public abstract T update(T item); // // public abstract T updateInternal(T item); // // public abstract void delete(String id); // // public abstract void deleteInternal(String id); // // public abstract boolean exists(String id); // // public abstract T get(String id); // // public abstract List<T> all(); // // protected void notifyChange(OnChangedListener.EventType type) { // if (listener != null){ // listener.onChanged(type); // } // } // // @Override // public void onChildAdded(DataSnapshot dataSnapshot, String s) { // insertInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Added); // } // // @Override // public void onChildChanged(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Changed); // } // // @Override // public void onChildRemoved(DataSnapshot dataSnapshot) { // deleteInternal(convert(dataSnapshot).getId()); // notifyChange(OnChangedListener.EventType.Removed); // } // // @Override // public void onChildMoved(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Moved); // } // // protected abstract T convert(DataSnapshot data); // // } // // Path: app/src/main/java/dev/wisebite/wisebite/utils/Service.java // public abstract class Service<T extends Entity> { // // protected final Repository<T> repository; // // public Service (Repository<T> repository){ // this.repository = repository; // } // // public T save(T item) { // if (repository.exists(item.getId())) return repository.update(item); // return repository.insert(item); // } // // public T get(String key) { // return repository.get(key); // } // // @SuppressWarnings("unused") // public void delete(String key){ // repository.delete(key); // } // // @SuppressWarnings("unused") // public int getAmount(){ // return repository.all().size(); // } // // public List<T> getAll() { // return repository.all(); // } // // public void setOnChangedListener(Repository.OnChangedListener listener){ // repository.setOnChangedListener(listener); // } // // }
import java.util.ArrayList; import dev.wisebite.wisebite.domain.Dish; import dev.wisebite.wisebite.domain.Menu; import dev.wisebite.wisebite.domain.OrderItem; import dev.wisebite.wisebite.firebase.Repository; import dev.wisebite.wisebite.utils.Service;
package dev.wisebite.wisebite.service; /** * Created by albert on 16/04/17. * @author albert */ public class OrderItemService extends Service<OrderItem> { private final Repository<Dish> dishRepository;
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Dish.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Dish implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> reviews = new LinkedHashMap<>(); // // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/Menu.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Menu implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> mainDishes = new LinkedHashMap<>(); // private Map<String, Object> secondaryDishes = new LinkedHashMap<>(); // private Map<String, Object> otherDishes = new LinkedHashMap<>(); // private Map<String, Object> reviews = new LinkedHashMap<>(); // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/OrderItem.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class OrderItem implements Entity { // // private String id; // private String differentFeature; // private boolean paid; // private boolean ready; // private boolean delivered; // private String dishId; // private String menuId; // // @Override // public String getId() { // return this.id; // } // // @Override // public void setId(String id) { // this.id = id; // } // } // // Path: app/src/main/java/dev/wisebite/wisebite/firebase/Repository.java // public abstract class Repository<T extends Entity> implements ChildEventListener { // // private OnChangedListener listener; // // /** // * Just for the Firebase when needed // */ // public Repository () { // // } // // public interface OnChangedListener { // enum EventType {Added, Changed, Removed, Moved, Full} // // void onChanged(EventType type); // } // // public void setOnChangedListener(OnChangedListener listener) { // this.listener = listener; // } // // public abstract T insert(T item); // // public abstract T insertInternal(T item); // // public abstract T update(T item); // // public abstract T updateInternal(T item); // // public abstract void delete(String id); // // public abstract void deleteInternal(String id); // // public abstract boolean exists(String id); // // public abstract T get(String id); // // public abstract List<T> all(); // // protected void notifyChange(OnChangedListener.EventType type) { // if (listener != null){ // listener.onChanged(type); // } // } // // @Override // public void onChildAdded(DataSnapshot dataSnapshot, String s) { // insertInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Added); // } // // @Override // public void onChildChanged(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Changed); // } // // @Override // public void onChildRemoved(DataSnapshot dataSnapshot) { // deleteInternal(convert(dataSnapshot).getId()); // notifyChange(OnChangedListener.EventType.Removed); // } // // @Override // public void onChildMoved(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Moved); // } // // protected abstract T convert(DataSnapshot data); // // } // // Path: app/src/main/java/dev/wisebite/wisebite/utils/Service.java // public abstract class Service<T extends Entity> { // // protected final Repository<T> repository; // // public Service (Repository<T> repository){ // this.repository = repository; // } // // public T save(T item) { // if (repository.exists(item.getId())) return repository.update(item); // return repository.insert(item); // } // // public T get(String key) { // return repository.get(key); // } // // @SuppressWarnings("unused") // public void delete(String key){ // repository.delete(key); // } // // @SuppressWarnings("unused") // public int getAmount(){ // return repository.all().size(); // } // // public List<T> getAll() { // return repository.all(); // } // // public void setOnChangedListener(Repository.OnChangedListener listener){ // repository.setOnChangedListener(listener); // } // // } // Path: app/src/main/java/dev/wisebite/wisebite/service/OrderItemService.java import java.util.ArrayList; import dev.wisebite.wisebite.domain.Dish; import dev.wisebite.wisebite.domain.Menu; import dev.wisebite.wisebite.domain.OrderItem; import dev.wisebite.wisebite.firebase.Repository; import dev.wisebite.wisebite.utils.Service; package dev.wisebite.wisebite.service; /** * Created by albert on 16/04/17. * @author albert */ public class OrderItemService extends Service<OrderItem> { private final Repository<Dish> dishRepository;
private final Repository<Menu> menuRepository;
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/OpenTime.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import java.util.Date; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/OpenTime.java import java.util.Date; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class OpenTime implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/Menu.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import java.util.LinkedHashMap; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/Menu.java import java.util.LinkedHashMap; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class Menu implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/activity/CreateRestaurantInfoActivity.java
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Restaurant.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Restaurant implements Entity { // // private String id; // private String name; // private String location; // private Integer phone; // private String description; // private String website; // private Integer numberOfTables; // // private Map<String, Object> openTimes = new LinkedHashMap<>(); // private Map<String, Object> menus = new LinkedHashMap<>(); // private Map<String, Object> dishes = new LinkedHashMap<>(); // private Map<String, Object> users = new LinkedHashMap<>(); // private Map<String, Object> externalOrders = new LinkedHashMap<>(); // private Map<String, Object> reviews = new LinkedHashMap<>(); // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/service/ServiceFactory.java // public final class ServiceFactory { // // private static DishService dishService; // private static ImageService imageService; // private static MenuService menuService; // private static OpenTimeService openTimeService; // private static OrderItemService orderItemService; // private static OrderService orderService; // private static RestaurantService restaurantService; // private static ReviewService reviewService; // private static UserService userService; // // public static DishService getDishService(Context context){ // if (dishService == null) // dishService = new DishService( // new DishRepository(context)); // return dishService; // } // // public static ImageService getImageService(Context context){ // if (imageService == null) // imageService = new ImageService( // new ImageRepository(context)); // return imageService; // } // // public static MenuService getMenuService(Context context){ // if (menuService == null) // menuService = new MenuService( // new MenuRepository(context), // new DishRepository(context)); // return menuService; // } // // public static OpenTimeService getOpenTimeService(Context context){ // if (openTimeService == null) // openTimeService = new OpenTimeService( // new OpenTimeRepository(context)); // return openTimeService; // } // // public static OrderItemService getOrderItemService(Context context){ // if (orderItemService == null) // orderItemService = new OrderItemService( // new OrderItemRepository(context), // new DishRepository(context), // new MenuRepository(context)); // return orderItemService; // } // // public static OrderService getOrderService(Context context){ // if (orderService == null) // orderService = new OrderService( // new OrderRepository(context), // new OrderItemRepository(context), // new DishRepository(context), // new MenuRepository(context), // new RestaurantRepository(context), // new UserRepository(context)); // return orderService; // } // // public static RestaurantService getRestaurantService(Context context){ // if (restaurantService == null) // restaurantService = new RestaurantService( // new RestaurantRepository(context), // new MenuRepository(context), // new DishRepository(context), // new ImageRepository(context), // new OpenTimeRepository(context), // new OrderRepository(context), // new OrderItemRepository(context), // new UserRepository(context), // new ReviewRepository(context)); // return restaurantService; // } // // public static ReviewService getReviewService(Context context) { // if (reviewService == null) { // reviewService = new ReviewService( // new ReviewRepository(context), // new RestaurantRepository(context), // new DishRepository(context), // new MenuRepository(context), // new UserRepository(context)); // } // return reviewService; // } // // public static UserService getUserService(Context context){ // if (userService == null) // userService = new UserService( // new UserRepository(context), // new ImageRepository(context), // new RestaurantRepository(context), // new OrderRepository(context), // new OrderItemRepository(context)); // return userService; // } // // public static Integer getServiceCount() { // return 9; // } // } // // Path: app/src/main/java/dev/wisebite/wisebite/utils/BaseActivity.java // public class BaseActivity extends AppCompatActivity { // // @Override // protected void onResume() { // super.onResume(); // Preferences.init(getApplicationContext()); // } // // @Override // public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { // super.onCreate(savedInstanceState, persistentState); // Preferences.init(getApplicationContext()); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import dev.wisebite.wisebite.R; import dev.wisebite.wisebite.domain.Restaurant; import dev.wisebite.wisebite.service.ServiceFactory; import dev.wisebite.wisebite.utils.BaseActivity;
package dev.wisebite.wisebite.activity; public class CreateRestaurantInfoActivity extends BaseActivity { private EditText inputName, inputLocation, inputPhone, inputDescription, inputWebsite, inputNumberOfTables; private TextInputLayout inputLayoutName, inputLayoutLocation, inputLayoutPhone, inputLayoutDescription, inputLayoutWebsite, inputLayoutNumberOfTables; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_restaurant_info); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Restaurant.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Restaurant implements Entity { // // private String id; // private String name; // private String location; // private Integer phone; // private String description; // private String website; // private Integer numberOfTables; // // private Map<String, Object> openTimes = new LinkedHashMap<>(); // private Map<String, Object> menus = new LinkedHashMap<>(); // private Map<String, Object> dishes = new LinkedHashMap<>(); // private Map<String, Object> users = new LinkedHashMap<>(); // private Map<String, Object> externalOrders = new LinkedHashMap<>(); // private Map<String, Object> reviews = new LinkedHashMap<>(); // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/service/ServiceFactory.java // public final class ServiceFactory { // // private static DishService dishService; // private static ImageService imageService; // private static MenuService menuService; // private static OpenTimeService openTimeService; // private static OrderItemService orderItemService; // private static OrderService orderService; // private static RestaurantService restaurantService; // private static ReviewService reviewService; // private static UserService userService; // // public static DishService getDishService(Context context){ // if (dishService == null) // dishService = new DishService( // new DishRepository(context)); // return dishService; // } // // public static ImageService getImageService(Context context){ // if (imageService == null) // imageService = new ImageService( // new ImageRepository(context)); // return imageService; // } // // public static MenuService getMenuService(Context context){ // if (menuService == null) // menuService = new MenuService( // new MenuRepository(context), // new DishRepository(context)); // return menuService; // } // // public static OpenTimeService getOpenTimeService(Context context){ // if (openTimeService == null) // openTimeService = new OpenTimeService( // new OpenTimeRepository(context)); // return openTimeService; // } // // public static OrderItemService getOrderItemService(Context context){ // if (orderItemService == null) // orderItemService = new OrderItemService( // new OrderItemRepository(context), // new DishRepository(context), // new MenuRepository(context)); // return orderItemService; // } // // public static OrderService getOrderService(Context context){ // if (orderService == null) // orderService = new OrderService( // new OrderRepository(context), // new OrderItemRepository(context), // new DishRepository(context), // new MenuRepository(context), // new RestaurantRepository(context), // new UserRepository(context)); // return orderService; // } // // public static RestaurantService getRestaurantService(Context context){ // if (restaurantService == null) // restaurantService = new RestaurantService( // new RestaurantRepository(context), // new MenuRepository(context), // new DishRepository(context), // new ImageRepository(context), // new OpenTimeRepository(context), // new OrderRepository(context), // new OrderItemRepository(context), // new UserRepository(context), // new ReviewRepository(context)); // return restaurantService; // } // // public static ReviewService getReviewService(Context context) { // if (reviewService == null) { // reviewService = new ReviewService( // new ReviewRepository(context), // new RestaurantRepository(context), // new DishRepository(context), // new MenuRepository(context), // new UserRepository(context)); // } // return reviewService; // } // // public static UserService getUserService(Context context){ // if (userService == null) // userService = new UserService( // new UserRepository(context), // new ImageRepository(context), // new RestaurantRepository(context), // new OrderRepository(context), // new OrderItemRepository(context)); // return userService; // } // // public static Integer getServiceCount() { // return 9; // } // } // // Path: app/src/main/java/dev/wisebite/wisebite/utils/BaseActivity.java // public class BaseActivity extends AppCompatActivity { // // @Override // protected void onResume() { // super.onResume(); // Preferences.init(getApplicationContext()); // } // // @Override // public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { // super.onCreate(savedInstanceState, persistentState); // Preferences.init(getApplicationContext()); // } // // } // Path: app/src/main/java/dev/wisebite/wisebite/activity/CreateRestaurantInfoActivity.java import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TextInputLayout; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import dev.wisebite.wisebite.R; import dev.wisebite.wisebite.domain.Restaurant; import dev.wisebite.wisebite.service.ServiceFactory; import dev.wisebite.wisebite.utils.BaseActivity; package dev.wisebite.wisebite.activity; public class CreateRestaurantInfoActivity extends BaseActivity { private EditText inputName, inputLocation, inputPhone, inputDescription, inputWebsite, inputNumberOfTables; private TextInputLayout inputLayoutName, inputLayoutLocation, inputLayoutPhone, inputLayoutDescription, inputLayoutWebsite, inputLayoutNumberOfTables; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_restaurant_info); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ServiceFactory.getRestaurantService(CreateRestaurantInfoActivity.this);
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/Order.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import java.util.Date; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 22/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/Order.java import java.util.Date; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 22/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class Order implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/service/DishService.java
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Dish.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Dish implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> reviews = new LinkedHashMap<>(); // // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/OrderItem.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class OrderItem implements Entity { // // private String id; // private String differentFeature; // private boolean paid; // private boolean ready; // private boolean delivered; // private String dishId; // private String menuId; // // @Override // public String getId() { // return this.id; // } // // @Override // public void setId(String id) { // this.id = id; // } // } // // Path: app/src/main/java/dev/wisebite/wisebite/firebase/Repository.java // public abstract class Repository<T extends Entity> implements ChildEventListener { // // private OnChangedListener listener; // // /** // * Just for the Firebase when needed // */ // public Repository () { // // } // // public interface OnChangedListener { // enum EventType {Added, Changed, Removed, Moved, Full} // // void onChanged(EventType type); // } // // public void setOnChangedListener(OnChangedListener listener) { // this.listener = listener; // } // // public abstract T insert(T item); // // public abstract T insertInternal(T item); // // public abstract T update(T item); // // public abstract T updateInternal(T item); // // public abstract void delete(String id); // // public abstract void deleteInternal(String id); // // public abstract boolean exists(String id); // // public abstract T get(String id); // // public abstract List<T> all(); // // protected void notifyChange(OnChangedListener.EventType type) { // if (listener != null){ // listener.onChanged(type); // } // } // // @Override // public void onChildAdded(DataSnapshot dataSnapshot, String s) { // insertInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Added); // } // // @Override // public void onChildChanged(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Changed); // } // // @Override // public void onChildRemoved(DataSnapshot dataSnapshot) { // deleteInternal(convert(dataSnapshot).getId()); // notifyChange(OnChangedListener.EventType.Removed); // } // // @Override // public void onChildMoved(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Moved); // } // // protected abstract T convert(DataSnapshot data); // // } // // Path: app/src/main/java/dev/wisebite/wisebite/utils/Service.java // public abstract class Service<T extends Entity> { // // protected final Repository<T> repository; // // public Service (Repository<T> repository){ // this.repository = repository; // } // // public T save(T item) { // if (repository.exists(item.getId())) return repository.update(item); // return repository.insert(item); // } // // public T get(String key) { // return repository.get(key); // } // // @SuppressWarnings("unused") // public void delete(String key){ // repository.delete(key); // } // // @SuppressWarnings("unused") // public int getAmount(){ // return repository.all().size(); // } // // public List<T> getAll() { // return repository.all(); // } // // public void setOnChangedListener(Repository.OnChangedListener listener){ // repository.setOnChangedListener(listener); // } // // }
import java.util.ArrayList; import java.util.Map; import dev.wisebite.wisebite.domain.Dish; import dev.wisebite.wisebite.domain.OrderItem; import dev.wisebite.wisebite.firebase.Repository; import dev.wisebite.wisebite.utils.Service;
package dev.wisebite.wisebite.service; /** * Created by albert on 16/04/17. * @author albert */ public class DishService extends Service<Dish> { public DishService(Repository<Dish> repository) { super(repository); } public ArrayList<Dish> parseDishMapToDishModel(Map<String, Object> dishesMap) { ArrayList<Dish> dishes = new ArrayList<>(); if (dishesMap != null) { for (String dishKey : dishesMap.keySet()) { dishes.add(repository.get(dishKey)); } } return dishes; }
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Dish.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Dish implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> reviews = new LinkedHashMap<>(); // // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/OrderItem.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class OrderItem implements Entity { // // private String id; // private String differentFeature; // private boolean paid; // private boolean ready; // private boolean delivered; // private String dishId; // private String menuId; // // @Override // public String getId() { // return this.id; // } // // @Override // public void setId(String id) { // this.id = id; // } // } // // Path: app/src/main/java/dev/wisebite/wisebite/firebase/Repository.java // public abstract class Repository<T extends Entity> implements ChildEventListener { // // private OnChangedListener listener; // // /** // * Just for the Firebase when needed // */ // public Repository () { // // } // // public interface OnChangedListener { // enum EventType {Added, Changed, Removed, Moved, Full} // // void onChanged(EventType type); // } // // public void setOnChangedListener(OnChangedListener listener) { // this.listener = listener; // } // // public abstract T insert(T item); // // public abstract T insertInternal(T item); // // public abstract T update(T item); // // public abstract T updateInternal(T item); // // public abstract void delete(String id); // // public abstract void deleteInternal(String id); // // public abstract boolean exists(String id); // // public abstract T get(String id); // // public abstract List<T> all(); // // protected void notifyChange(OnChangedListener.EventType type) { // if (listener != null){ // listener.onChanged(type); // } // } // // @Override // public void onChildAdded(DataSnapshot dataSnapshot, String s) { // insertInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Added); // } // // @Override // public void onChildChanged(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Changed); // } // // @Override // public void onChildRemoved(DataSnapshot dataSnapshot) { // deleteInternal(convert(dataSnapshot).getId()); // notifyChange(OnChangedListener.EventType.Removed); // } // // @Override // public void onChildMoved(DataSnapshot dataSnapshot, String s) { // updateInternal(convert(dataSnapshot)); // notifyChange(OnChangedListener.EventType.Moved); // } // // protected abstract T convert(DataSnapshot data); // // } // // Path: app/src/main/java/dev/wisebite/wisebite/utils/Service.java // public abstract class Service<T extends Entity> { // // protected final Repository<T> repository; // // public Service (Repository<T> repository){ // this.repository = repository; // } // // public T save(T item) { // if (repository.exists(item.getId())) return repository.update(item); // return repository.insert(item); // } // // public T get(String key) { // return repository.get(key); // } // // @SuppressWarnings("unused") // public void delete(String key){ // repository.delete(key); // } // // @SuppressWarnings("unused") // public int getAmount(){ // return repository.all().size(); // } // // public List<T> getAll() { // return repository.all(); // } // // public void setOnChangedListener(Repository.OnChangedListener listener){ // repository.setOnChangedListener(listener); // } // // } // Path: app/src/main/java/dev/wisebite/wisebite/service/DishService.java import java.util.ArrayList; import java.util.Map; import dev.wisebite.wisebite.domain.Dish; import dev.wisebite.wisebite.domain.OrderItem; import dev.wisebite.wisebite.firebase.Repository; import dev.wisebite.wisebite.utils.Service; package dev.wisebite.wisebite.service; /** * Created by albert on 16/04/17. * @author albert */ public class DishService extends Service<Dish> { public DishService(Repository<Dish> repository) { super(repository); } public ArrayList<Dish> parseDishMapToDishModel(Map<String, Object> dishesMap) { ArrayList<Dish> dishes = new ArrayList<>(); if (dishesMap != null) { for (String dishKey : dishesMap.keySet()) { dishes.add(repository.get(dishKey)); } } return dishes; }
public String getName(OrderItem orderItem) {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/Restaurant.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import java.util.LinkedHashMap; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/Restaurant.java import java.util.LinkedHashMap; import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 13/03/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class Restaurant implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/User.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 14/04/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/User.java import java.util.Map; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 14/04/17. * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class User implements Entity {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/utils/Utils.java
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Menu.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Menu implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> mainDishes = new LinkedHashMap<>(); // private Map<String, Object> secondaryDishes = new LinkedHashMap<>(); // private Map<String, Object> otherDishes = new LinkedHashMap<>(); // private Map<String, Object> reviews = new LinkedHashMap<>(); // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/OpenTime.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class OpenTime implements Entity { // // private String id; // private Date startDate; // private Date endDate; // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // }
import android.os.Build; import android.widget.TimePicker; import java.util.Calendar; import java.util.Date; import dev.wisebite.wisebite.R; import dev.wisebite.wisebite.domain.Menu; import dev.wisebite.wisebite.domain.OpenTime;
firstHour = firstTimePicker.getHour(); firstMinute = firstTimePicker.getMinute(); secondHour = secondTimePicker.getHour(); secondMinute = secondTimePicker.getMinute(); } else { firstHour = firstTimePicker.getCurrentHour(); firstMinute = firstTimePicker.getCurrentMinute(); secondHour = secondTimePicker.getCurrentHour(); secondMinute = secondTimePicker.getCurrentMinute(); } return datesToString(firstHour, firstMinute, secondHour, secondMinute); } public static String parseStartEndDate(Date startDate, Date endDate) { int firstHour, firstMinute, secondHour, secondMinute; Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); firstHour = calendar.get(Calendar.HOUR_OF_DAY); firstMinute = calendar.get(Calendar.MINUTE); calendar.setTime(endDate); secondHour = calendar.get(Calendar.HOUR_OF_DAY); secondMinute = calendar.get(Calendar.MINUTE); return datesToString(firstHour, firstMinute, secondHour, secondMinute); } @SuppressWarnings("deprecation")
// Path: app/src/main/java/dev/wisebite/wisebite/domain/Menu.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class Menu implements Entity { // // private String id; // private String name; // private Double price; // private String description; // // private Map<String, Object> mainDishes = new LinkedHashMap<>(); // private Map<String, Object> secondaryDishes = new LinkedHashMap<>(); // private Map<String, Object> otherDishes = new LinkedHashMap<>(); // private Map<String, Object> reviews = new LinkedHashMap<>(); // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // // Path: app/src/main/java/dev/wisebite/wisebite/domain/OpenTime.java // @Getter // @Setter // @AllArgsConstructor(suppressConstructorProperties = true) // @NoArgsConstructor // @ToString // @Builder // public class OpenTime implements Entity { // // private String id; // private Date startDate; // private Date endDate; // // @Override // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // } // Path: app/src/main/java/dev/wisebite/wisebite/utils/Utils.java import android.os.Build; import android.widget.TimePicker; import java.util.Calendar; import java.util.Date; import dev.wisebite.wisebite.R; import dev.wisebite.wisebite.domain.Menu; import dev.wisebite.wisebite.domain.OpenTime; firstHour = firstTimePicker.getHour(); firstMinute = firstTimePicker.getMinute(); secondHour = secondTimePicker.getHour(); secondMinute = secondTimePicker.getMinute(); } else { firstHour = firstTimePicker.getCurrentHour(); firstMinute = firstTimePicker.getCurrentMinute(); secondHour = secondTimePicker.getCurrentHour(); secondMinute = secondTimePicker.getCurrentMinute(); } return datesToString(firstHour, firstMinute, secondHour, secondMinute); } public static String parseStartEndDate(Date startDate, Date endDate) { int firstHour, firstMinute, secondHour, secondMinute; Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); firstHour = calendar.get(Calendar.HOUR_OF_DAY); firstMinute = calendar.get(Calendar.MINUTE); calendar.setTime(endDate); secondHour = calendar.get(Calendar.HOUR_OF_DAY); secondMinute = calendar.get(Calendar.MINUTE); return datesToString(firstHour, firstMinute, secondHour, secondMinute); } @SuppressWarnings("deprecation")
public static OpenTime createOpenTimeByTimePicker(TimePicker firstTimePicker, TimePicker secondTimePicker, Integer viewId) {
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/domain/Review.java
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // }
import java.util.Date; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder;
package dev.wisebite.wisebite.domain; /** * Created by albert on 3/06/17. * * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
// Path: app/src/main/java/dev/wisebite/wisebite/utils/Entity.java // public interface Entity extends Serializable { // // String getId(); // // void setId(String id); // // } // Path: app/src/main/java/dev/wisebite/wisebite/domain/Review.java import java.util.Date; import dev.wisebite.wisebite.utils.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Builder; package dev.wisebite.wisebite.domain; /** * Created by albert on 3/06/17. * * @author albert */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) @NoArgsConstructor @ToString @Builder
public class Review implements Entity {
Mark-Kovalyov/CardRaytracerBenchmark
java-mt/src/main/java/mayton/CardRaytraceRecursiveAction.java
// Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int HEIGHT = 512; // // Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int WIDTH = 512;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.ThreadContext; import javax.annotation.Nonnull; import java.awt.Color; import java.awt.image.BufferedImage; import java.nio.file.Path; import java.util.Random; import java.util.concurrent.RecursiveAction; import static java.lang.Math.ceil; import static java.lang.Math.pow; import static java.lang.Math.sqrt; import static mayton.CardRaytracerMt.HEIGHT; import static mayton.CardRaytracerMt.WIDTH;
for (int x = rect.x2 - 1; x >= rect.x1; x--) { Vector p = COLOR_DARK_GRAY_VECTOR; for (int r = 0; r < SUB_SAMPLES; r++) { Vector t = a.prod(random.nextDouble() - 0.5).prod(99.0).sum(b.prod(random.nextDouble() - 0.5).prod(99.0)); p = sampler(CAMERA_ASPECT_VECTOR.sum(t), t.prod(-1.0).sum(a.prod(random.nextDouble() + x).sum(b.prod(random.nextDouble() + y)).sum(c).prod(16.0)).norm() ).prod(3.5).sum(p); } int red = (int) p.x; int green = (int) p.y; int blue = (int) p.z; image[xx + yy * width] = red << 16 | green << 8 | blue ; xx--; } yy--; } if (drawMargins) { for (int x = 0; x < width; x += 2) { image[x] = Color.GREEN.getRGB(); } for (int y = 0; y < height; y += 2) { image[y * width] = Color.GREEN.getRGB(); } } synchronized (mutexImage) { // TODO: This is fat and ugly code to copy rectangle into BufferedImage. Should be improoved with copy collections int xd = rect.x1; int yd = rect.y1;
// Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int HEIGHT = 512; // // Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int WIDTH = 512; // Path: java-mt/src/main/java/mayton/CardRaytraceRecursiveAction.java import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.ThreadContext; import javax.annotation.Nonnull; import java.awt.Color; import java.awt.image.BufferedImage; import java.nio.file.Path; import java.util.Random; import java.util.concurrent.RecursiveAction; import static java.lang.Math.ceil; import static java.lang.Math.pow; import static java.lang.Math.sqrt; import static mayton.CardRaytracerMt.HEIGHT; import static mayton.CardRaytracerMt.WIDTH; for (int x = rect.x2 - 1; x >= rect.x1; x--) { Vector p = COLOR_DARK_GRAY_VECTOR; for (int r = 0; r < SUB_SAMPLES; r++) { Vector t = a.prod(random.nextDouble() - 0.5).prod(99.0).sum(b.prod(random.nextDouble() - 0.5).prod(99.0)); p = sampler(CAMERA_ASPECT_VECTOR.sum(t), t.prod(-1.0).sum(a.prod(random.nextDouble() + x).sum(b.prod(random.nextDouble() + y)).sum(c).prod(16.0)).norm() ).prod(3.5).sum(p); } int red = (int) p.x; int green = (int) p.y; int blue = (int) p.z; image[xx + yy * width] = red << 16 | green << 8 | blue ; xx--; } yy--; } if (drawMargins) { for (int x = 0; x < width; x += 2) { image[x] = Color.GREEN.getRGB(); } for (int y = 0; y < height; y += 2) { image[y * width] = Color.GREEN.getRGB(); } } synchronized (mutexImage) { // TODO: This is fat and ugly code to copy rectangle into BufferedImage. Should be improoved with copy collections int xd = rect.x1; int yd = rect.y1;
int x1 = WIDTH - xd - 1;
Mark-Kovalyov/CardRaytracerBenchmark
java-mt/src/main/java/mayton/CardRaytraceRecursiveAction.java
// Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int HEIGHT = 512; // // Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int WIDTH = 512;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.ThreadContext; import javax.annotation.Nonnull; import java.awt.Color; import java.awt.image.BufferedImage; import java.nio.file.Path; import java.util.Random; import java.util.concurrent.RecursiveAction; import static java.lang.Math.ceil; import static java.lang.Math.pow; import static java.lang.Math.sqrt; import static mayton.CardRaytracerMt.HEIGHT; import static mayton.CardRaytracerMt.WIDTH;
p = sampler(CAMERA_ASPECT_VECTOR.sum(t), t.prod(-1.0).sum(a.prod(random.nextDouble() + x).sum(b.prod(random.nextDouble() + y)).sum(c).prod(16.0)).norm() ).prod(3.5).sum(p); } int red = (int) p.x; int green = (int) p.y; int blue = (int) p.z; image[xx + yy * width] = red << 16 | green << 8 | blue ; xx--; } yy--; } if (drawMargins) { for (int x = 0; x < width; x += 2) { image[x] = Color.GREEN.getRGB(); } for (int y = 0; y < height; y += 2) { image[y * width] = Color.GREEN.getRGB(); } } synchronized (mutexImage) { // TODO: This is fat and ugly code to copy rectangle into BufferedImage. Should be improoved with copy collections int xd = rect.x1; int yd = rect.y1; int x1 = WIDTH - xd - 1; int x2 = WIDTH - xd - 1 - width; int i = 0; for (int y = 0; y < height; y++) {
// Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int HEIGHT = 512; // // Path: java-mt/src/main/java/mayton/CardRaytracerMt.java // static final int WIDTH = 512; // Path: java-mt/src/main/java/mayton/CardRaytraceRecursiveAction.java import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.ThreadContext; import javax.annotation.Nonnull; import java.awt.Color; import java.awt.image.BufferedImage; import java.nio.file.Path; import java.util.Random; import java.util.concurrent.RecursiveAction; import static java.lang.Math.ceil; import static java.lang.Math.pow; import static java.lang.Math.sqrt; import static mayton.CardRaytracerMt.HEIGHT; import static mayton.CardRaytracerMt.WIDTH; p = sampler(CAMERA_ASPECT_VECTOR.sum(t), t.prod(-1.0).sum(a.prod(random.nextDouble() + x).sum(b.prod(random.nextDouble() + y)).sum(c).prod(16.0)).norm() ).prod(3.5).sum(p); } int red = (int) p.x; int green = (int) p.y; int blue = (int) p.z; image[xx + yy * width] = red << 16 | green << 8 | blue ; xx--; } yy--; } if (drawMargins) { for (int x = 0; x < width; x += 2) { image[x] = Color.GREEN.getRGB(); } for (int y = 0; y < height; y += 2) { image[y * width] = Color.GREEN.getRGB(); } } synchronized (mutexImage) { // TODO: This is fat and ugly code to copy rectangle into BufferedImage. Should be improoved with copy collections int xd = rect.x1; int yd = rect.y1; int x1 = WIDTH - xd - 1; int x2 = WIDTH - xd - 1 - width; int i = 0; for (int y = 0; y < height; y++) {
int y1 = HEIGHT - yd - 1 - y;
ArchitectingHBase/examples
src/org/apache/solr/hadoop/morphline/MorphlineCounters.java
// Path: src/org/apache/solr/hadoop/Utils.java // @Beta // public final class Utils { // // private static final String LOG_CONFIG_FILE = "hadoop.log4j.configuration"; // // public static void setLogConfigFile(File file, Configuration conf) { // conf.set(LOG_CONFIG_FILE, file.getName()); // } // // public static void getLogConfigFile(Configuration conf) { // String log4jPropertiesFile = conf.get(LOG_CONFIG_FILE); // if (log4jPropertiesFile != null) { // PropertyConfigurator.configure(log4jPropertiesFile); // } // } // // public static String getShortClassName(Class clazz) { // return getShortClassName(clazz.getName()); // } // // public static String getShortClassName(String className) { // int i = className.lastIndexOf('.'); // regular class // int j = className.lastIndexOf('$'); // inner class // return className.substring(1 + Math.max(i, j)); // } // // }
import org.apache.solr.hadoop.Utils;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.morphline; public enum MorphlineCounters { FILES_READ (getClassName(MorphlineMapper.class) + ": Number of files read"), FILE_BYTES_READ (getClassName(MorphlineMapper.class) + ": Number of file bytes read"), DOCS_READ (getClassName(MorphlineMapper.class) + ": Number of documents read"), PARSER_OUTPUT_BYTES (getClassName(MorphlineMapper.class) + ": Number of document bytes generated by Tika parser"), ERRORS (getClassName(MorphlineMapper.class) + ": Number of errors"); private final String label; private MorphlineCounters(String label) { this.label = label; } public String toString() { return label; } private static String getClassName(Class clazz) {
// Path: src/org/apache/solr/hadoop/Utils.java // @Beta // public final class Utils { // // private static final String LOG_CONFIG_FILE = "hadoop.log4j.configuration"; // // public static void setLogConfigFile(File file, Configuration conf) { // conf.set(LOG_CONFIG_FILE, file.getName()); // } // // public static void getLogConfigFile(Configuration conf) { // String log4jPropertiesFile = conf.get(LOG_CONFIG_FILE); // if (log4jPropertiesFile != null) { // PropertyConfigurator.configure(log4jPropertiesFile); // } // } // // public static String getShortClassName(Class clazz) { // return getShortClassName(clazz.getName()); // } // // public static String getShortClassName(String className) { // int i = className.lastIndexOf('.'); // regular class // int j = className.lastIndexOf('$'); // inner class // return className.substring(1 + Math.max(i, j)); // } // // } // Path: src/org/apache/solr/hadoop/morphline/MorphlineCounters.java import org.apache.solr.hadoop.Utils; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.morphline; public enum MorphlineCounters { FILES_READ (getClassName(MorphlineMapper.class) + ": Number of files read"), FILE_BYTES_READ (getClassName(MorphlineMapper.class) + ": Number of file bytes read"), DOCS_READ (getClassName(MorphlineMapper.class) + ": Number of documents read"), PARSER_OUTPUT_BYTES (getClassName(MorphlineMapper.class) + ": Number of document bytes generated by Tika parser"), ERRORS (getClassName(MorphlineMapper.class) + ": Number of errors"); private final String label; private MorphlineCounters(String label) { this.label = label; } public String toString() { return label; } private static String getClassName(Class clazz) {
return Utils.getShortClassName(clazz);
ArchitectingHBase/examples
src/org/apache/solr/hadoop/dedup/RetainMostRecentUpdateConflictResolver.java
// Path: src/org/apache/solr/hadoop/HdfsFileFieldNames.java // public interface HdfsFileFieldNames { // // public static final String FILE_UPLOAD_URL = "file_upload_url"; // public static final String FILE_DOWNLOAD_URL = "file_download_url"; // public static final String FILE_SCHEME = "file_scheme"; // public static final String FILE_HOST = "file_host"; // public static final String FILE_PORT = "file_port"; // public static final String FILE_PATH = "file_path"; // public static final String FILE_NAME = "file_name"; // public static final String FILE_LENGTH = "file_length"; // public static final String FILE_LAST_MODIFIED = "file_last_modified"; // public static final String FILE_OWNER = "file_owner"; // public static final String FILE_GROUP = "file_group"; // public static final String FILE_PERMISSIONS_USER = "file_permissions_user"; // public static final String FILE_PERMISSIONS_GROUP = "file_permissions_group"; // public static final String FILE_PERMISSIONS_OTHER = "file_permissions_other"; // public static final String FILE_PERMISSIONS_STICKYBIT = "file_permissions_stickybit"; // // } // // Path: src/org/apache/solr/hadoop/Utils.java // @Beta // public final class Utils { // // private static final String LOG_CONFIG_FILE = "hadoop.log4j.configuration"; // // public static void setLogConfigFile(File file, Configuration conf) { // conf.set(LOG_CONFIG_FILE, file.getName()); // } // // public static void getLogConfigFile(Configuration conf) { // String log4jPropertiesFile = conf.get(LOG_CONFIG_FILE); // if (log4jPropertiesFile != null) { // PropertyConfigurator.configure(log4jPropertiesFile); // } // } // // public static String getShortClassName(Class clazz) { // return getShortClassName(clazz.getName()); // } // // public static String getShortClassName(String className) { // int i = className.lastIndexOf('.'); // regular class // int j = className.lastIndexOf('$'); // inner class // return className.substring(1 + Math.max(i, j)); // } // // }
import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer.Context; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.hadoop.HdfsFileFieldNames; import org.apache.solr.hadoop.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.dedup; /** * UpdateConflictResolver implementation that ignores all but the most recent * document version, based on a configurable numeric Solr field, which defaults * to the file_last_modified timestamp. */ public class RetainMostRecentUpdateConflictResolver implements UpdateConflictResolver, Configurable { private Configuration conf; private String orderByFieldName = ORDER_BY_FIELD_NAME_DEFAULT; public static final String ORDER_BY_FIELD_NAME_KEY = RetainMostRecentUpdateConflictResolver.class.getName() + ".orderByFieldName";
// Path: src/org/apache/solr/hadoop/HdfsFileFieldNames.java // public interface HdfsFileFieldNames { // // public static final String FILE_UPLOAD_URL = "file_upload_url"; // public static final String FILE_DOWNLOAD_URL = "file_download_url"; // public static final String FILE_SCHEME = "file_scheme"; // public static final String FILE_HOST = "file_host"; // public static final String FILE_PORT = "file_port"; // public static final String FILE_PATH = "file_path"; // public static final String FILE_NAME = "file_name"; // public static final String FILE_LENGTH = "file_length"; // public static final String FILE_LAST_MODIFIED = "file_last_modified"; // public static final String FILE_OWNER = "file_owner"; // public static final String FILE_GROUP = "file_group"; // public static final String FILE_PERMISSIONS_USER = "file_permissions_user"; // public static final String FILE_PERMISSIONS_GROUP = "file_permissions_group"; // public static final String FILE_PERMISSIONS_OTHER = "file_permissions_other"; // public static final String FILE_PERMISSIONS_STICKYBIT = "file_permissions_stickybit"; // // } // // Path: src/org/apache/solr/hadoop/Utils.java // @Beta // public final class Utils { // // private static final String LOG_CONFIG_FILE = "hadoop.log4j.configuration"; // // public static void setLogConfigFile(File file, Configuration conf) { // conf.set(LOG_CONFIG_FILE, file.getName()); // } // // public static void getLogConfigFile(Configuration conf) { // String log4jPropertiesFile = conf.get(LOG_CONFIG_FILE); // if (log4jPropertiesFile != null) { // PropertyConfigurator.configure(log4jPropertiesFile); // } // } // // public static String getShortClassName(Class clazz) { // return getShortClassName(clazz.getName()); // } // // public static String getShortClassName(String className) { // int i = className.lastIndexOf('.'); // regular class // int j = className.lastIndexOf('$'); // inner class // return className.substring(1 + Math.max(i, j)); // } // // } // Path: src/org/apache/solr/hadoop/dedup/RetainMostRecentUpdateConflictResolver.java import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer.Context; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.hadoop.HdfsFileFieldNames; import org.apache.solr.hadoop.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.dedup; /** * UpdateConflictResolver implementation that ignores all but the most recent * document version, based on a configurable numeric Solr field, which defaults * to the file_last_modified timestamp. */ public class RetainMostRecentUpdateConflictResolver implements UpdateConflictResolver, Configurable { private Configuration conf; private String orderByFieldName = ORDER_BY_FIELD_NAME_DEFAULT; public static final String ORDER_BY_FIELD_NAME_KEY = RetainMostRecentUpdateConflictResolver.class.getName() + ".orderByFieldName";
public static final String ORDER_BY_FIELD_NAME_DEFAULT = HdfsFileFieldNames.FILE_LAST_MODIFIED;
ArchitectingHBase/examples
src/org/apache/solr/hadoop/dedup/RetainMostRecentUpdateConflictResolver.java
// Path: src/org/apache/solr/hadoop/HdfsFileFieldNames.java // public interface HdfsFileFieldNames { // // public static final String FILE_UPLOAD_URL = "file_upload_url"; // public static final String FILE_DOWNLOAD_URL = "file_download_url"; // public static final String FILE_SCHEME = "file_scheme"; // public static final String FILE_HOST = "file_host"; // public static final String FILE_PORT = "file_port"; // public static final String FILE_PATH = "file_path"; // public static final String FILE_NAME = "file_name"; // public static final String FILE_LENGTH = "file_length"; // public static final String FILE_LAST_MODIFIED = "file_last_modified"; // public static final String FILE_OWNER = "file_owner"; // public static final String FILE_GROUP = "file_group"; // public static final String FILE_PERMISSIONS_USER = "file_permissions_user"; // public static final String FILE_PERMISSIONS_GROUP = "file_permissions_group"; // public static final String FILE_PERMISSIONS_OTHER = "file_permissions_other"; // public static final String FILE_PERMISSIONS_STICKYBIT = "file_permissions_stickybit"; // // } // // Path: src/org/apache/solr/hadoop/Utils.java // @Beta // public final class Utils { // // private static final String LOG_CONFIG_FILE = "hadoop.log4j.configuration"; // // public static void setLogConfigFile(File file, Configuration conf) { // conf.set(LOG_CONFIG_FILE, file.getName()); // } // // public static void getLogConfigFile(Configuration conf) { // String log4jPropertiesFile = conf.get(LOG_CONFIG_FILE); // if (log4jPropertiesFile != null) { // PropertyConfigurator.configure(log4jPropertiesFile); // } // } // // public static String getShortClassName(Class clazz) { // return getShortClassName(clazz.getName()); // } // // public static String getShortClassName(String className) { // int i = className.lastIndexOf('.'); // regular class // int j = className.lastIndexOf('$'); // inner class // return className.substring(1 + Math.max(i, j)); // } // // }
import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer.Context; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.hadoop.HdfsFileFieldNames; import org.apache.solr.hadoop.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.dedup; /** * UpdateConflictResolver implementation that ignores all but the most recent * document version, based on a configurable numeric Solr field, which defaults * to the file_last_modified timestamp. */ public class RetainMostRecentUpdateConflictResolver implements UpdateConflictResolver, Configurable { private Configuration conf; private String orderByFieldName = ORDER_BY_FIELD_NAME_DEFAULT; public static final String ORDER_BY_FIELD_NAME_KEY = RetainMostRecentUpdateConflictResolver.class.getName() + ".orderByFieldName"; public static final String ORDER_BY_FIELD_NAME_DEFAULT = HdfsFileFieldNames.FILE_LAST_MODIFIED;
// Path: src/org/apache/solr/hadoop/HdfsFileFieldNames.java // public interface HdfsFileFieldNames { // // public static final String FILE_UPLOAD_URL = "file_upload_url"; // public static final String FILE_DOWNLOAD_URL = "file_download_url"; // public static final String FILE_SCHEME = "file_scheme"; // public static final String FILE_HOST = "file_host"; // public static final String FILE_PORT = "file_port"; // public static final String FILE_PATH = "file_path"; // public static final String FILE_NAME = "file_name"; // public static final String FILE_LENGTH = "file_length"; // public static final String FILE_LAST_MODIFIED = "file_last_modified"; // public static final String FILE_OWNER = "file_owner"; // public static final String FILE_GROUP = "file_group"; // public static final String FILE_PERMISSIONS_USER = "file_permissions_user"; // public static final String FILE_PERMISSIONS_GROUP = "file_permissions_group"; // public static final String FILE_PERMISSIONS_OTHER = "file_permissions_other"; // public static final String FILE_PERMISSIONS_STICKYBIT = "file_permissions_stickybit"; // // } // // Path: src/org/apache/solr/hadoop/Utils.java // @Beta // public final class Utils { // // private static final String LOG_CONFIG_FILE = "hadoop.log4j.configuration"; // // public static void setLogConfigFile(File file, Configuration conf) { // conf.set(LOG_CONFIG_FILE, file.getName()); // } // // public static void getLogConfigFile(Configuration conf) { // String log4jPropertiesFile = conf.get(LOG_CONFIG_FILE); // if (log4jPropertiesFile != null) { // PropertyConfigurator.configure(log4jPropertiesFile); // } // } // // public static String getShortClassName(Class clazz) { // return getShortClassName(clazz.getName()); // } // // public static String getShortClassName(String className) { // int i = className.lastIndexOf('.'); // regular class // int j = className.lastIndexOf('$'); // inner class // return className.substring(1 + Math.max(i, j)); // } // // } // Path: src/org/apache/solr/hadoop/dedup/RetainMostRecentUpdateConflictResolver.java import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer.Context; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.hadoop.HdfsFileFieldNames; import org.apache.solr.hadoop.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.dedup; /** * UpdateConflictResolver implementation that ignores all but the most recent * document version, based on a configurable numeric Solr field, which defaults * to the file_last_modified timestamp. */ public class RetainMostRecentUpdateConflictResolver implements UpdateConflictResolver, Configurable { private Configuration conf; private String orderByFieldName = ORDER_BY_FIELD_NAME_DEFAULT; public static final String ORDER_BY_FIELD_NAME_KEY = RetainMostRecentUpdateConflictResolver.class.getName() + ".orderByFieldName"; public static final String ORDER_BY_FIELD_NAME_DEFAULT = HdfsFileFieldNames.FILE_LAST_MODIFIED;
public static final String COUNTER_GROUP = Utils.getShortClassName(RetainMostRecentUpdateConflictResolver.class);
ArchitectingHBase/examples
src/com/architecting/ch07/GoLive.java
// Path: src/com/architecting/ch07/MapReduceIndexerTool.java // static final class Options { // boolean goLive; // String collection; // String zkHost; // Integer goLiveThreads; // List<List<String>> shardUrls; // String inputTable; // Path outputDir; // int mappers; // int reducers; // int fanout; // Integer shards; // int maxSegments; // File solrHomeDir; // File log4jConfigFile; // }
import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.hadoop.fs.FileStatus; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CloudSolrServer; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.request.CoreAdminRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.architecting.ch07.MapReduceIndexerTool.Options;
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable * law or agreed to in writing, software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations under the License. */ package com.architecting.ch07; /** * The optional (parallel) GoLive phase merges the output shards of the previous phase into a set of * live customer facing Solr servers, typically a SolrCloud. */ class GoLive { private static final Logger LOG = LoggerFactory.getLogger(GoLive.class); // TODO: handle clusters with replicas
// Path: src/com/architecting/ch07/MapReduceIndexerTool.java // static final class Options { // boolean goLive; // String collection; // String zkHost; // Integer goLiveThreads; // List<List<String>> shardUrls; // String inputTable; // Path outputDir; // int mappers; // int reducers; // int fanout; // Integer shards; // int maxSegments; // File solrHomeDir; // File log4jConfigFile; // } // Path: src/com/architecting/ch07/GoLive.java import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.hadoop.fs.FileStatus; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CloudSolrServer; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.request.CoreAdminRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.architecting.ch07.MapReduceIndexerTool.Options; /* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable * law or agreed to in writing, software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations under the License. */ package com.architecting.ch07; /** * The optional (parallel) GoLive phase merges the output shards of the previous phase into a set of * live customer facing Solr servers, typically a SolrCloud. */ class GoLive { private static final Logger LOG = LoggerFactory.getLogger(GoLive.class); // TODO: handle clusters with replicas
public boolean goLive(Options options, FileStatus[] outDirs) {
ArchitectingHBase/examples
src/org/apache/solr/hadoop/dedup/SortingUpdateConflictResolver.java
// Path: src/org/apache/solr/hadoop/HdfsFileFieldNames.java // public interface HdfsFileFieldNames { // // public static final String FILE_UPLOAD_URL = "file_upload_url"; // public static final String FILE_DOWNLOAD_URL = "file_download_url"; // public static final String FILE_SCHEME = "file_scheme"; // public static final String FILE_HOST = "file_host"; // public static final String FILE_PORT = "file_port"; // public static final String FILE_PATH = "file_path"; // public static final String FILE_NAME = "file_name"; // public static final String FILE_LENGTH = "file_length"; // public static final String FILE_LAST_MODIFIED = "file_last_modified"; // public static final String FILE_OWNER = "file_owner"; // public static final String FILE_GROUP = "file_group"; // public static final String FILE_PERMISSIONS_USER = "file_permissions_user"; // public static final String FILE_PERMISSIONS_GROUP = "file_permissions_group"; // public static final String FILE_PERMISSIONS_OTHER = "file_permissions_other"; // public static final String FILE_PERMISSIONS_STICKYBIT = "file_permissions_stickybit"; // // }
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer.Context; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.hadoop.HdfsFileFieldNames;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.dedup; /** * UpdateConflictResolver implementation that orders colliding updates ascending * from least recent to most recent (partial) update, based on a configurable * numeric Solr field, which defaults to the file_last_modified timestamp. */ public class SortingUpdateConflictResolver implements UpdateConflictResolver, Configurable { private Configuration conf; private String orderByFieldName = ORDER_BY_FIELD_NAME_DEFAULT; public static final String ORDER_BY_FIELD_NAME_KEY = SortingUpdateConflictResolver.class.getName() + ".orderByFieldName";
// Path: src/org/apache/solr/hadoop/HdfsFileFieldNames.java // public interface HdfsFileFieldNames { // // public static final String FILE_UPLOAD_URL = "file_upload_url"; // public static final String FILE_DOWNLOAD_URL = "file_download_url"; // public static final String FILE_SCHEME = "file_scheme"; // public static final String FILE_HOST = "file_host"; // public static final String FILE_PORT = "file_port"; // public static final String FILE_PATH = "file_path"; // public static final String FILE_NAME = "file_name"; // public static final String FILE_LENGTH = "file_length"; // public static final String FILE_LAST_MODIFIED = "file_last_modified"; // public static final String FILE_OWNER = "file_owner"; // public static final String FILE_GROUP = "file_group"; // public static final String FILE_PERMISSIONS_USER = "file_permissions_user"; // public static final String FILE_PERMISSIONS_GROUP = "file_permissions_group"; // public static final String FILE_PERMISSIONS_OTHER = "file_permissions_other"; // public static final String FILE_PERMISSIONS_STICKYBIT = "file_permissions_stickybit"; // // } // Path: src/org/apache/solr/hadoop/dedup/SortingUpdateConflictResolver.java import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer.Context; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.hadoop.HdfsFileFieldNames; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.hadoop.dedup; /** * UpdateConflictResolver implementation that orders colliding updates ascending * from least recent to most recent (partial) update, based on a configurable * numeric Solr field, which defaults to the file_last_modified timestamp. */ public class SortingUpdateConflictResolver implements UpdateConflictResolver, Configurable { private Configuration conf; private String orderByFieldName = ORDER_BY_FIELD_NAME_DEFAULT; public static final String ORDER_BY_FIELD_NAME_KEY = SortingUpdateConflictResolver.class.getName() + ".orderByFieldName";
public static final String ORDER_BY_FIELD_NAME_DEFAULT = HdfsFileFieldNames.FILE_LAST_MODIFIED;
ni3po42/traction.mvc
Demo/src/main/java/ni3po42/android/tractiondemo/controllers/DemoADialogController.java
// Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/implementations/CommandArgument.java // public class CommandArgument // { // private String commandName; // private boolean eventCancelled; // private JSONObject tagProperties; // // public boolean isEventCancelled() // { // return eventCancelled; // } // // public void setEventCancelled(boolean isCancelled) // { // eventCancelled = isCancelled; // } // // public CommandArgument(String commandName) // { // this(commandName, null); // } // // public CommandArgument(String commandName, JSONObject tagProperties) // { // this.commandName = commandName; // this.eventCancelled = false; // this.tagProperties = tagProperties; // } // // public JSONObject getEventData() // { // return tagProperties; // } // // public String getCommandName() // { // return commandName; // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IOnExecuteListener.java // public interface IOnExecuteListener // { // void onExecuted(CommandArgument arg); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DialogModel.java // public interface DialogModel // { // String getSomeText(); // void setSomeText(String t); // // Command getClose(); // Command getOpen(); // }
import android.os.Bundle; import traction.mvc.controllers.FragmentController; import traction.mvc.implementations.CommandArgument; import traction.mvc.interfaces.IOnExecuteListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.DialogModel;
/* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class DemoADialogController extends FragmentController { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View.setContentView(R.layout.dialoglauncher); }; @Override public void onStart() { super.onStart();
// Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/implementations/CommandArgument.java // public class CommandArgument // { // private String commandName; // private boolean eventCancelled; // private JSONObject tagProperties; // // public boolean isEventCancelled() // { // return eventCancelled; // } // // public void setEventCancelled(boolean isCancelled) // { // eventCancelled = isCancelled; // } // // public CommandArgument(String commandName) // { // this(commandName, null); // } // // public CommandArgument(String commandName, JSONObject tagProperties) // { // this.commandName = commandName; // this.eventCancelled = false; // this.tagProperties = tagProperties; // } // // public JSONObject getEventData() // { // return tagProperties; // } // // public String getCommandName() // { // return commandName; // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IOnExecuteListener.java // public interface IOnExecuteListener // { // void onExecuted(CommandArgument arg); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DialogModel.java // public interface DialogModel // { // String getSomeText(); // void setSomeText(String t); // // Command getClose(); // Command getOpen(); // } // Path: Demo/src/main/java/ni3po42/android/tractiondemo/controllers/DemoADialogController.java import android.os.Bundle; import traction.mvc.controllers.FragmentController; import traction.mvc.implementations.CommandArgument; import traction.mvc.interfaces.IOnExecuteListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.DialogModel; /* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class DemoADialogController extends FragmentController { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View.setContentView(R.layout.dialoglauncher); }; @Override public void onStart() { super.onStart();
DialogModel model = View.getScope();
ni3po42/traction.mvc
Demo/src/main/java/ni3po42/android/tractiondemo/controllers/DemoADialogController.java
// Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/implementations/CommandArgument.java // public class CommandArgument // { // private String commandName; // private boolean eventCancelled; // private JSONObject tagProperties; // // public boolean isEventCancelled() // { // return eventCancelled; // } // // public void setEventCancelled(boolean isCancelled) // { // eventCancelled = isCancelled; // } // // public CommandArgument(String commandName) // { // this(commandName, null); // } // // public CommandArgument(String commandName, JSONObject tagProperties) // { // this.commandName = commandName; // this.eventCancelled = false; // this.tagProperties = tagProperties; // } // // public JSONObject getEventData() // { // return tagProperties; // } // // public String getCommandName() // { // return commandName; // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IOnExecuteListener.java // public interface IOnExecuteListener // { // void onExecuted(CommandArgument arg); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DialogModel.java // public interface DialogModel // { // String getSomeText(); // void setSomeText(String t); // // Command getClose(); // Command getOpen(); // }
import android.os.Bundle; import traction.mvc.controllers.FragmentController; import traction.mvc.implementations.CommandArgument; import traction.mvc.interfaces.IOnExecuteListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.DialogModel;
/* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class DemoADialogController extends FragmentController { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View.setContentView(R.layout.dialoglauncher); }; @Override public void onStart() { super.onStart(); DialogModel model = View.getScope();
// Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/implementations/CommandArgument.java // public class CommandArgument // { // private String commandName; // private boolean eventCancelled; // private JSONObject tagProperties; // // public boolean isEventCancelled() // { // return eventCancelled; // } // // public void setEventCancelled(boolean isCancelled) // { // eventCancelled = isCancelled; // } // // public CommandArgument(String commandName) // { // this(commandName, null); // } // // public CommandArgument(String commandName, JSONObject tagProperties) // { // this.commandName = commandName; // this.eventCancelled = false; // this.tagProperties = tagProperties; // } // // public JSONObject getEventData() // { // return tagProperties; // } // // public String getCommandName() // { // return commandName; // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IOnExecuteListener.java // public interface IOnExecuteListener // { // void onExecuted(CommandArgument arg); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DialogModel.java // public interface DialogModel // { // String getSomeText(); // void setSomeText(String t); // // Command getClose(); // Command getOpen(); // } // Path: Demo/src/main/java/ni3po42/android/tractiondemo/controllers/DemoADialogController.java import android.os.Bundle; import traction.mvc.controllers.FragmentController; import traction.mvc.implementations.CommandArgument; import traction.mvc.interfaces.IOnExecuteListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.DialogModel; /* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class DemoADialogController extends FragmentController { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View.setContentView(R.layout.dialoglauncher); }; @Override public void onStart() { super.onStart(); DialogModel model = View.getScope();
model.getOpen().setExecuteListener(new IOnExecuteListener() {
ni3po42/traction.mvc
Demo/src/main/java/ni3po42/android/tractiondemo/controllers/DemoADialogController.java
// Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/implementations/CommandArgument.java // public class CommandArgument // { // private String commandName; // private boolean eventCancelled; // private JSONObject tagProperties; // // public boolean isEventCancelled() // { // return eventCancelled; // } // // public void setEventCancelled(boolean isCancelled) // { // eventCancelled = isCancelled; // } // // public CommandArgument(String commandName) // { // this(commandName, null); // } // // public CommandArgument(String commandName, JSONObject tagProperties) // { // this.commandName = commandName; // this.eventCancelled = false; // this.tagProperties = tagProperties; // } // // public JSONObject getEventData() // { // return tagProperties; // } // // public String getCommandName() // { // return commandName; // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IOnExecuteListener.java // public interface IOnExecuteListener // { // void onExecuted(CommandArgument arg); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DialogModel.java // public interface DialogModel // { // String getSomeText(); // void setSomeText(String t); // // Command getClose(); // Command getOpen(); // }
import android.os.Bundle; import traction.mvc.controllers.FragmentController; import traction.mvc.implementations.CommandArgument; import traction.mvc.interfaces.IOnExecuteListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.DialogModel;
/* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class DemoADialogController extends FragmentController { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View.setContentView(R.layout.dialoglauncher); }; @Override public void onStart() { super.onStart(); DialogModel model = View.getScope(); model.getOpen().setExecuteListener(new IOnExecuteListener() { @Override
// Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/implementations/CommandArgument.java // public class CommandArgument // { // private String commandName; // private boolean eventCancelled; // private JSONObject tagProperties; // // public boolean isEventCancelled() // { // return eventCancelled; // } // // public void setEventCancelled(boolean isCancelled) // { // eventCancelled = isCancelled; // } // // public CommandArgument(String commandName) // { // this(commandName, null); // } // // public CommandArgument(String commandName, JSONObject tagProperties) // { // this.commandName = commandName; // this.eventCancelled = false; // this.tagProperties = tagProperties; // } // // public JSONObject getEventData() // { // return tagProperties; // } // // public String getCommandName() // { // return commandName; // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IOnExecuteListener.java // public interface IOnExecuteListener // { // void onExecuted(CommandArgument arg); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DialogModel.java // public interface DialogModel // { // String getSomeText(); // void setSomeText(String t); // // Command getClose(); // Command getOpen(); // } // Path: Demo/src/main/java/ni3po42/android/tractiondemo/controllers/DemoADialogController.java import android.os.Bundle; import traction.mvc.controllers.FragmentController; import traction.mvc.implementations.CommandArgument; import traction.mvc.interfaces.IOnExecuteListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.DialogModel; /* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class DemoADialogController extends FragmentController { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View.setContentView(R.layout.dialoglauncher); }; @Override public void onStart() { super.onStart(); DialogModel model = View.getScope(); model.getOpen().setExecuteListener(new IOnExecuteListener() { @Override
public void onExecuted(CommandArgument argument) {
ni3po42/traction.mvc
Demo/src/main/java/ni3po42/android/tractiondemo/controllers/MainController.java
// Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DemoFragmentChoice.java // public class DemoFragmentChoice // { // private Class<? extends Fragment> fragmentType; // private String name; // private String description; // // public DemoFragmentChoice(Class<? extends Fragment> fragmentType, String name, String description) // { // this.fragmentType = fragmentType; // this.name = name; // this.description = description; // } // // public Class<? extends Fragment> getFragmentType() // { // return fragmentType; // } // public void setFragmentType(Class<? extends Fragment> viewModelType) // { // this.fragmentType = viewModelType; // } // // public Fragment getFragment() // { // Fragment fragment = null; // try // { // fragment = getFragmentType().newInstance(); // } // catch (Throwable e) // { // } // if (fragment == null) // throw new RuntimeException("Cannot find View Model : " + getFragmentType().getName()); // return fragment; // } // // // public String getName() // { // return name; // } // // public void setName(String name) // { // this.name = name; // } // // public String getDescription() // { // return description; // } // // public void setDescription(String description) // { // this.description = description; // } // // } // // Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IObjectListener.java // public interface IObjectListener // { // public static class Utility // { // public static String generatePropagationId(String currentPropagationId, String currentSource) // { // if (currentSource == null || currentSource.equals("")) // return currentPropagationId; // else if (currentPropagationId == null || currentPropagationId.equals("")) // return currentSource; // else // return currentSource + "." + currentPropagationId; // } // } // // /** // * Fired when listener is signalled of something, anything really. // */ // void onEvent(String propagationId); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/IDemoSelectionModel.java // public interface IDemoSelectionModel // extends IProxyObservableObject // { // List<DemoFragmentChoice> getChoices(); // // Fragment getCurrentFragment(); // void setCurrentFragment(Fragment fragment); // // DemoFragmentChoice getChoice(); // void setChoice(DemoFragmentChoice choice); // } // // Path: traction/src/main/java/traction/mvc/observables/OnPropertyChangedEvent.java // public abstract class OnPropertyChangedEvent // implements IObjectListener // { // @Override // public void onEvent(String propagationId) { // //eh, nothing // } // // protected abstract void onChange(String propertyName, Object oldValue, Object newValue); // }
import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import ni3po42.android.tractiondemo.models.DemoFragmentChoice; import traction.mvc.controllers.FragmentController; import traction.mvc.interfaces.IObjectListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.IDemoSelectionModel; import traction.mvc.observables.OnPropertyChangedEvent;
/* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class MainController extends FragmentController { public final static String NoMultiViewModelSupport = "multiViewModelSupport"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) return; View.setContentView(R.layout.mainview); } @Override public void onStart() { super.onStart();
// Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/DemoFragmentChoice.java // public class DemoFragmentChoice // { // private Class<? extends Fragment> fragmentType; // private String name; // private String description; // // public DemoFragmentChoice(Class<? extends Fragment> fragmentType, String name, String description) // { // this.fragmentType = fragmentType; // this.name = name; // this.description = description; // } // // public Class<? extends Fragment> getFragmentType() // { // return fragmentType; // } // public void setFragmentType(Class<? extends Fragment> viewModelType) // { // this.fragmentType = viewModelType; // } // // public Fragment getFragment() // { // Fragment fragment = null; // try // { // fragment = getFragmentType().newInstance(); // } // catch (Throwable e) // { // } // if (fragment == null) // throw new RuntimeException("Cannot find View Model : " + getFragmentType().getName()); // return fragment; // } // // // public String getName() // { // return name; // } // // public void setName(String name) // { // this.name = name; // } // // public String getDescription() // { // return description; // } // // public void setDescription(String description) // { // this.description = description; // } // // } // // Path: traction/src/main/java/traction/mvc/controllers/FragmentController.java // public class FragmentController // extends Fragment // { // /** // * Helper to implement Controller logic. // */ // protected final ControllerHelper View = new ControllerHelper(this); // // @Override // public void onCreate(Bundle savedInstanceState) // { // super.onCreate(savedInstanceState); // setRetainInstance(true); // } // // @Override // public View onCreateView(LayoutInflater notUsed, ViewGroup container, Bundle savedInstanceState) // { // View v = View.inflateView(View.getContentView(), container, container != null); // IViewBinding vb = ViewFactory.getViewBinding(v); // if (vb != null) { // View.ensureMenuInflator(vb.getBindingInventory()); // } // return v; // } // // @Override // public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) // { // View.onCreateOptionsMenu(menu); // } // // @Override // public void onDestroyView() // { // super.onDestroyView(); // ViewFactory.DetachContext(getView()); // } // // @Override // public void onAttach(Activity activity) // { // super.onAttach(activity); // View.registerFragmentToActivity(this, activity); // } // // @Override // public void onDetach() // { // super.onDetach(); // View.unregisterFragmentFromActivity(this, getActivity()); // } // // @Override // public void onStart() // { // super.onStart(); // View.connectFragmentViewToParentView(this); // } // } // // Path: traction/src/main/java/traction/mvc/interfaces/IObjectListener.java // public interface IObjectListener // { // public static class Utility // { // public static String generatePropagationId(String currentPropagationId, String currentSource) // { // if (currentSource == null || currentSource.equals("")) // return currentPropagationId; // else if (currentPropagationId == null || currentPropagationId.equals("")) // return currentSource; // else // return currentSource + "." + currentPropagationId; // } // } // // /** // * Fired when listener is signalled of something, anything really. // */ // void onEvent(String propagationId); // } // // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/IDemoSelectionModel.java // public interface IDemoSelectionModel // extends IProxyObservableObject // { // List<DemoFragmentChoice> getChoices(); // // Fragment getCurrentFragment(); // void setCurrentFragment(Fragment fragment); // // DemoFragmentChoice getChoice(); // void setChoice(DemoFragmentChoice choice); // } // // Path: traction/src/main/java/traction/mvc/observables/OnPropertyChangedEvent.java // public abstract class OnPropertyChangedEvent // implements IObjectListener // { // @Override // public void onEvent(String propagationId) { // //eh, nothing // } // // protected abstract void onChange(String propertyName, Object oldValue, Object newValue); // } // Path: Demo/src/main/java/ni3po42/android/tractiondemo/controllers/MainController.java import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import ni3po42.android.tractiondemo.models.DemoFragmentChoice; import traction.mvc.controllers.FragmentController; import traction.mvc.interfaces.IObjectListener; import ni3po42.android.tractiondemo.R; import ni3po42.android.tractiondemo.models.IDemoSelectionModel; import traction.mvc.observables.OnPropertyChangedEvent; /* Copyright 2013 Tim Stratton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ni3po42.android.tractiondemo.controllers; public class MainController extends FragmentController { public final static String NoMultiViewModelSupport = "multiViewModelSupport"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) return; View.setContentView(R.layout.mainview); } @Override public void onStart() { super.onStart();
final IDemoSelectionModel model = View.getScope();
ni3po42/traction.mvc
Demo/src/main/java/ni3po42/android/tractiondemo/models/IMultiSelectionModel.java
// Path: traction/src/main/java/traction/mvc/observables/Command.java // public class Command // extends ObservableObject // implements IObservableCommand // { // private IOnExecuteListener executeListener; // // public Command() // { // setCanExecute(true); // } // // public Command(boolean initCanExecute) // { // setCanExecute(initCanExecute); // } // // public void setExecuteListener(IOnExecuteListener listener) // { // executeListener = listener; // } // // private boolean canExecute; // // @Override // protected IPropertyStore getPropertyStore() // { // //getProperty was overridden, this is not used. // return null; // } // // @SuppressWarnings("unchecked") // @Override // public Property<Object, Object> getProperty(String name) // { // Class<?> c = boolean.class; // //The only supported property on a command will be 'CanExecute', for now... // if (name.equals("CanExecute") && getSource() != null) // return (Property<Object, Object>) Property.of(getSource().getClass(), c, name); // return null; // } // // @Override // public boolean getCanExecute() // { // return canExecute; // } // // @Override // public void setCanExecute(boolean b) // { // if (canExecute == b) // return; // notifyListener("CanExecute", canExecute, canExecute = b); // } // // /** // * Is fired when execute(TArg) is called and CanExecute() is true // * @param arg : argument passed to execute method. Could very well be null. // */ // protected void onExecuted(CommandArgument arg) // { // if (executeListener != null) // executeListener.onExecuted(arg); // } // // @Override // public void execute(CommandArgument arg) // { // if (!getCanExecute()) // return; // // onExecuted(arg); // } // // } // // Path: traction/src/main/java/traction/mvc/observables/IProxyObservableObject.java // public interface IProxyObservableObject // { // /** // * Allow access to the composed IObservableObject // * @return // */ // ObservableObject getProxyObservableObject(); // // }
import java.util.List; import traction.mvc.observables.Command; import traction.mvc.observables.IProxyObservableObject;
package ni3po42.android.tractiondemo.models; public interface IMultiSelectionModel extends IProxyObservableObject { List<SelectableItem> getItems(); void setSelected(SelectableItem i); SelectableItem getSelected(); int getSelectedCount(); void setSelectedCount(int i);
// Path: traction/src/main/java/traction/mvc/observables/Command.java // public class Command // extends ObservableObject // implements IObservableCommand // { // private IOnExecuteListener executeListener; // // public Command() // { // setCanExecute(true); // } // // public Command(boolean initCanExecute) // { // setCanExecute(initCanExecute); // } // // public void setExecuteListener(IOnExecuteListener listener) // { // executeListener = listener; // } // // private boolean canExecute; // // @Override // protected IPropertyStore getPropertyStore() // { // //getProperty was overridden, this is not used. // return null; // } // // @SuppressWarnings("unchecked") // @Override // public Property<Object, Object> getProperty(String name) // { // Class<?> c = boolean.class; // //The only supported property on a command will be 'CanExecute', for now... // if (name.equals("CanExecute") && getSource() != null) // return (Property<Object, Object>) Property.of(getSource().getClass(), c, name); // return null; // } // // @Override // public boolean getCanExecute() // { // return canExecute; // } // // @Override // public void setCanExecute(boolean b) // { // if (canExecute == b) // return; // notifyListener("CanExecute", canExecute, canExecute = b); // } // // /** // * Is fired when execute(TArg) is called and CanExecute() is true // * @param arg : argument passed to execute method. Could very well be null. // */ // protected void onExecuted(CommandArgument arg) // { // if (executeListener != null) // executeListener.onExecuted(arg); // } // // @Override // public void execute(CommandArgument arg) // { // if (!getCanExecute()) // return; // // onExecuted(arg); // } // // } // // Path: traction/src/main/java/traction/mvc/observables/IProxyObservableObject.java // public interface IProxyObservableObject // { // /** // * Allow access to the composed IObservableObject // * @return // */ // ObservableObject getProxyObservableObject(); // // } // Path: Demo/src/main/java/ni3po42/android/tractiondemo/models/IMultiSelectionModel.java import java.util.List; import traction.mvc.observables.Command; import traction.mvc.observables.IProxyObservableObject; package ni3po42.android.tractiondemo.models; public interface IMultiSelectionModel extends IProxyObservableObject { List<SelectableItem> getItems(); void setSelected(SelectableItem i); SelectableItem getSelected(); int getSelectedCount(); void setSelectedCount(int i);
Command getCountSelected();