repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
Rubentxu/DreamsLibGdx
core/src/main/java/com/rubentxu/juegos/core/pantallas/BaseScreen.java
[ "public class DreamsGame extends BaseGame {\n\n public static boolean DEBUG = false;\n public static FPSLogger log;\n\n @Override\n public void create() {\n Gdx.input.setCatchBackKey(true);\n resourcesManager =new ResourcesManager();\n preferencesManager = PreferencesManager.instance;\n profileManager= new ProfileManager();\n levelManager=new LevelManager(this);\n audioManager =new AudioManager(this);\n\n log = new FPSLogger();\n setGameState(GameState.GAME_SHOW_SPLASH);\n }\n\n @Override\n public void dispose() {\n super.dispose();\n }\n\n @Override\n public void render() {\n super.render();\n log.log();\n }\n\n @Override\n public void resize(int width, int height) {\n super.resize(width, height);\n }\n\n @Override\n public void pause() {\n super.pause();\n }\n\n @Override\n public void resume() {\n super.resume();\n }\n\n}", "public class Constants {\n\n public static final float WORLD_HEIGHT = 16.875f; // 1080 / 64 =16.875 px\n public static final float WORLD_WIDTH = 30f; // 1920 / 64 = 30f px\n\n public static final float VIRTUAL_HEIGHT = 1080f; // 16.875 x 64 =1080 px\n public static final float VIRTUAL_WIDTH = 1920f; // 30 x 64 = 1920 px\n // Box2D config\n public static final float RUNNING_FRAME_DURATION = 0.02f;\n public static final int VELOCITY_ITERATIONS = 10;\n public static final int POSITION_ITERATIONS = 8;\n // Game attributes\n public static final String VERSION = \"0.3 Alpha\";\n public static final String LOG = \"Hero Dreams\";\n // Preferences\n public static final String PREFS_NAME = \"DreamsGame\";\n public static final String PREF_VOLUME_SOUND = \"volume.music\";\n public static final String PREF_VOLUME_MUSIC = \"volume.sound\";\n public static final String PREF_MUSIC_ENABLED = \"music.enabled\";\n public static final String PREF_SOUND_ENABLED = \"sound.enabled\";\n public static final String PREF_TOUCHPAD_ENABLED = \"touchpad.enabled\";\n // Profile\n public static final String PROFILE_DATA_FILE = \"data/profile.game\";\n public static final String INIT_PROFILE_DATA_FILE = \"data/initProfile.game\";\n\n //Name elements GUI STATS\n public static final String LABEL_SCORE= \"Puntuacion\";\n public static final String SCORE= \"Score\";\n public static final String IMAGE_LIVES= \"ImageLives\";\n public static final String LIVES= \"Lives\";\n\n // Name World Events\n public static final int COLLET_COIN = 1;\n}", "public enum GameState {\n GAME_RUNNING,\n GAME_PAUSED,\n GAME_UPDATE,\n GAME_OVER,\n GAME_WIN,\n GAME_LEVELWIN,\n GAME_IDLE,\n GAME_SLOWMOTION,\n GAME_BACK,\n SCREEN_TRANSITION,\n GAME_EXIT ,\n GAME_SHOW_MENU,\n GAME_SHOW_SCORE,\n GAME_SHOW_LEVEL_MENU,\n GAME_SHOW_SPLASH,\n GAME_SHOW_OPTIONS, GAME_SHOW_HIGHSCORES, GAME_SHOW_GAME;\n}", "public interface ScreenTransition {\n public float getDuration();\n\n public void render(SpriteBatch batch, Texture currScreen, Texture nextScreen, float alpha);\n\n}", "public class ScreenTransitionSlide implements ScreenTransition {\n public static final int LEFT = 1;\n public static final int RIGHT = 2;\n public static final int UP = 3;\n public static final int DOWN = 4;\n private static final ScreenTransitionSlide instance =\n new ScreenTransitionSlide();\n private float duration;\n private int direction;\n private boolean slideOut;\n private Interpolation easing;\n\n public static ScreenTransitionSlide init(float duration,\n int direction, boolean slideOut, Interpolation easing) {\n instance.duration = duration;\n instance.direction = direction;\n instance.slideOut = slideOut;\n instance.easing = easing;\n return instance;\n }\n\n @Override\n public float getDuration() {\n return duration;\n }\n\n @Override\n public void render(SpriteBatch batch, Texture currScreen, Texture nextScreen, float alpha) {\n float w = currScreen.getWidth();\n float h = currScreen.getHeight();\n float x = 0;\n float y = 0;\n if (easing != null) alpha = easing.apply(alpha);\n\n switch (direction) {\n case LEFT:\n x = -w * alpha;\n if (!slideOut) x += w;\n break;\n case RIGHT:\n x = w * alpha;\n if (!slideOut) x -= w;\n break;\n case UP:\n y = h * alpha;\n if (!slideOut) y -= h;\n break;\n case DOWN:\n y = -h * alpha;\n if (!slideOut) y += h;\n break;\n }\n\n Texture texBottom = slideOut ? nextScreen : currScreen;\n Texture texTop = slideOut ? currScreen : nextScreen;\n\n Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);\n batch.begin();\n batch.draw(texBottom, 0, 0, 0, 0, w, h, 1, 1, 0, 0, 0,\n currScreen.getWidth(), currScreen.getHeight(),\n false, true);\n batch.draw(texTop, x, y, 0, 0, w, h, 1, 1, 0, 0, 0, nextScreen.getWidth(), nextScreen.getHeight(), false, true);\n batch.end();\n }\n}" ]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.rubentxu.juegos.core.DreamsGame; import com.rubentxu.juegos.core.constantes.Constants; import com.rubentxu.juegos.core.constantes.GameState; import com.rubentxu.juegos.core.pantallas.transiciones.ScreenTransition; import com.rubentxu.juegos.core.pantallas.transiciones.ScreenTransitionSlide; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeIn;
package com.rubentxu.juegos.core.pantallas; public abstract class BaseScreen implements Screen { protected final DreamsGame game; protected Stage stage; protected Table mainTable; protected Window dialog; protected Label message; protected Stack container; protected float width; protected float height; public static SCREEN CURRENT_SCREEN = SCREEN.SPLASH; //private ScreenTransition transition = ScreenTransitionFade.init(0.75f);
private ScreenTransition transition = ScreenTransitionSlide.init(0.7f,
3
davidmoten/rxjava2-jdbc
rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/GetterTx.java
[ "public class Tuple2<T1, T2> {\n\n private final T1 value1;\n private final T2 value2;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n */\n public Tuple2(T1 value1, T2 value2) {\n this.value1 = value1;\n this.value2 = value2;\n }\n\n /**\n * Returns a new instance.\n * \n * @param r\n * first element\n * @param s\n * second element \n * @param <R> type of first element\n * @param <S>\n * type of second element\n * \n * @return tuple\n */\n public static <R, S> Tuple2<R, S> create(R r, S s) {\n return new Tuple2<R, S>(r, s);\n }\n\n /**\n * Returns the first element of the tuple.\n * \n * @return first element\n */\n public T1 value1() {\n return value1;\n }\n\n /**\n * Returns the first element of the tuple.\n * \n * @return first element\n */\n public T1 _1() {\n return value1;\n }\n\n /**\n * Returns the 2nd element of the tuple.\n * \n * @return second element\n */\n public T2 value2() {\n return value2;\n }\n\n /**\n * Returns the 2nd element of the tuple.\n * \n * @return second element\n */\n public T2 _2() {\n return value2;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Tuple2<?, ?> other = (Tuple2<?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple2 [value1=\" + value1 + \", value2=\" + value2 + \"]\";\n }\n\n}", "public class Tuple3<T1, T2, T3> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n\n /**\n * Constructor.\n * \n * @param value1 first element \n * @param value2 second element\n * @param value3 third element\n */\n public Tuple3(T1 value1, T2 value2, T3 value3) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n }\n \n public static <T1,T2,T3> Tuple3<T1,T2,T3> create(T1 value1, T2 value2, T3 value3) {\n return new Tuple3<T1,T2,T3>(value1, value2, value3);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Tuple3<?, ?, ?> other = (Tuple3<?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple3 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3 + \"]\";\n }\n\n}", "public class Tuple4<T1, T2, T3, T4> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n\n /**\n * Constructor.\n * \n * @param value1 first element\n * @param value2 second element\n * @param value3 third element\n * @param value4 fourth element\n */\n public Tuple4(T1 value1, T2 value2, T3 value3, T4 value4) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n }\n\n public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> create(T1 value1, T2 value2, T3 value3, T4 value4) {\n return new Tuple4<T1, T2, T3, T4>(value1, value2, value3, value4);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Tuple4<?, ?, ?, ?> other = (Tuple4<?, ?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n if (value4 == null) {\n if (other.value4 != null)\n return false;\n } else if (!value4.equals(other.value4))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple4 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3 + \", value4=\" + value4 + \"]\";\n }\n\n}", "public class Tuple5<T1, T2, T3, T4, T5> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n private final T5 value5;\n\n /**\n * Constructor.\n * \n * @param value1 first element\n * @param value2 second element\n * @param value3 third element\n * @param value4 fourth element\n * @param value5 fifth element\n */\n public Tuple5(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n this.value5 = value5;\n }\n\n public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> create(T1 value1, T2 value2, T3 value3, T4 value4,\n T5 value5) {\n return new Tuple5<T1, T2, T3, T4, T5>(value1, value2, value3, value4, value5);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T5 value5() {\n return value5;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n public T5 _5() {\n return value5;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n result = prime * result + ((value5 == null) ? 0 : value5.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Tuple5<?, ?, ?, ?, ?> other = (Tuple5<?, ?, ?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n if (value4 == null) {\n if (other.value4 != null)\n return false;\n } else if (!value4.equals(other.value4))\n return false;\n if (value5 == null) {\n if (other.value5 != null)\n return false;\n } else if (!value5.equals(other.value5))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple5 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3 + \", value4=\" + value4\n + \", value5=\" + value5 + \"]\";\n }\n\n}", "public class Tuple6<T1, T2, T3, T4, T5, T6> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n private final T5 value5;\n private final T6 value6;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n * @param value3\n * third element\n * @param value4\n * fourth element\n * @param value5\n * fifth element\n * @param value6\n * sixth element\n */\n public Tuple6(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n this.value5 = value5;\n this.value6 = value6;\n }\n\n public static <T1, T2, T3, T4, T5, T6> Tuple6<T1, T2, T3, T4, T5, T6> create(T1 value1,\n T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) {\n return new Tuple6<T1, T2, T3, T4, T5, T6>(value1, value2, value3, value4, value5, value6);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T5 value5() {\n return value5;\n }\n\n public T6 value6() {\n return value6;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n public T5 _5() {\n return value5;\n }\n\n public T6 _6() {\n return value6;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n result = prime * result + ((value5 == null) ? 0 : value5.hashCode());\n result = prime * result + ((value6 == null) ? 0 : value6.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Tuple6<?, ?, ?, ?, ?, ?> other = (Tuple6<?, ?, ?, ?, ?, ?>) obj;\n if (value1 == null) {\n if (other.value1 != null)\n return false;\n } else if (!value1.equals(other.value1))\n return false;\n if (value2 == null) {\n if (other.value2 != null)\n return false;\n } else if (!value2.equals(other.value2))\n return false;\n if (value3 == null) {\n if (other.value3 != null)\n return false;\n } else if (!value3.equals(other.value3))\n return false;\n if (value4 == null) {\n if (other.value4 != null)\n return false;\n } else if (!value4.equals(other.value4))\n return false;\n if (value5 == null) {\n if (other.value5 != null)\n return false;\n } else if (!value5.equals(other.value5))\n return false;\n if (value6 == null) {\n if (other.value6 != null)\n return false;\n } else if (!value6.equals(other.value6))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tuple6 [value1=\" + value1 + \", value2=\" + value2 + \", value3=\" + value3\n + \", value4=\" + value4 + \", value5=\" + value5 + \", value6=\" + value6 + \"]\";\n }\n}", "public class Tuple7<T1, T2, T3, T4, T5, T6, T7> {\n\n private final T1 value1;\n private final T2 value2;\n private final T3 value3;\n private final T4 value4;\n private final T5 value5;\n private final T6 value6;\n private final T7 value7;\n\n /**\n * Constructor.\n * \n * @param value1\n * first element\n * @param value2\n * second element\n * @param value3\n * third element\n * @param value4\n * fourth element\n * @param value5\n * fifth element\n * @param value6\n * sixth element\n * @param value7\n * seventh element\n */\n public Tuple7(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) {\n this.value1 = value1;\n this.value2 = value2;\n this.value3 = value3;\n this.value4 = value4;\n this.value5 = value5;\n this.value6 = value6;\n this.value7 = value7;\n }\n\n public static <T1, T2, T3, T4, T5, T6, T7> Tuple7<T1, T2, T3, T4, T5, T6, T7> create(T1 value1,\n T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) {\n return new Tuple7<T1, T2, T3, T4, T5, T6, T7>(value1, value2, value3, value4, value5,\n value6, value7);\n }\n\n public T1 value1() {\n return value1;\n }\n\n public T2 value2() {\n return value2;\n }\n\n public T3 value3() {\n return value3;\n }\n\n public T4 value4() {\n return value4;\n }\n\n public T5 value5() {\n return value5;\n }\n\n public T6 value6() {\n return value6;\n }\n\n public T7 value7() {\n return value7;\n }\n\n public T1 _1() {\n return value1;\n }\n\n public T2 _2() {\n return value2;\n }\n\n public T3 _3() {\n return value3;\n }\n\n public T4 _4() {\n return value4;\n }\n\n public T5 _5() {\n return value5;\n }\n\n public T6 _6() {\n return value6;\n }\n\n public T7 _7() {\n return value7;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((value1 == null) ? 0 : value1.hashCode());\n result = prime * result + ((value2 == null) ? 0 : value2.hashCode());\n result = prime * result + ((value3 == null) ? 0 : value3.hashCode());\n result = prime * result + ((value4 == null) ? 0 : value4.hashCode());\n result = prime * result + ((value5 == null) ? 0 : value5.hashCode());\n result = prime * result + ((value6 == null) ? 0 : value6.hashCode());\n result = prime * result + ((value7 == null) ? 0 : value7.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n @SuppressWarnings(\"rawtypes\")\n final Tuple7 other = (Tuple7) obj;\n return Objects.equals(value1, other.value1) //\n && Objects.equals(value2, other.value2) //\n && Objects.equals(value3, other.value3) //\n && Objects.equals(value4, other.value4) //\n && Objects.equals(value5, other.value5) //\n && Objects.equals(value6, other.value6) //\n && Objects.equals(value7, other.value7);\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"Tuple7 [value1=\");\n builder.append(value1);\n builder.append(\", value2=\");\n builder.append(value2);\n builder.append(\", value3=\");\n builder.append(value3);\n builder.append(\", value4=\");\n builder.append(value4);\n builder.append(\", value5=\");\n builder.append(value5);\n builder.append(\", value6=\");\n builder.append(value6);\n builder.append(\", value7=\");\n builder.append(value7);\n builder.append(\"]\");\n return builder.toString();\n }\n\n}", "public class TupleN<T> {\n\n private final List<T> list;\n\n /**\n * Constructor.\n * \n * @param list\n * values of the elements in the tuple\n */\n public TupleN(List<T> list) {\n this.list = list;\n }\n\n @SafeVarargs\n public static <T> TupleN<T> create(T... array) {\n return new TupleN<T>(Arrays.asList(array));\n }\n\n public List<T> values() {\n // defensive copy\n return new ArrayList<T>(list);\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((list == null) ? 0 : list.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n TupleN<?> other = (TupleN<?>) obj;\n if (list == null) {\n if (other.list != null)\n return false;\n } else if (!list.equals(other.list))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"TupleN [values=\" + list + \"]\";\n }\n\n}", "public final class Tuples {\n\n /**\n * Private constructor to prevent instantiation.\n */\n private Tuples() {\n // prevent instantiation.\n }\n\n public static <T> ResultSetMapper<T> single(final Class<T> cls) {\n Preconditions.checkNotNull(cls, \"cls cannot be null\");\n return new ResultSetMapper<T>() {\n\n @Override\n public T apply(ResultSet rs) {\n return mapObject(rs, cls, 1);\n }\n\n };\n }\n\n public static <T1, T2> ResultSetMapper<Tuple2<T1, T2>> tuple(final Class<T1> cls1,\n final Class<T2> cls2) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n return new ResultSetMapper<Tuple2<T1, T2>>() {\n\n @Override\n public Tuple2<T1, T2> apply(ResultSet rs) {\n return new Tuple2<T1, T2>(mapObject(rs, cls1, 1), mapObject(rs, cls2, 2));\n }\n };\n }\n\n public static <T1, T2, T3> ResultSetMapper<Tuple3<T1, T2, T3>> tuple(final Class<T1> cls1,\n final Class<T2> cls2, final Class<T3> cls3) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n return new ResultSetMapper<Tuple3<T1, T2, T3>>() {\n @Override\n public Tuple3<T1, T2, T3> apply(ResultSet rs) {\n return new Tuple3<T1, T2, T3>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3));\n }\n };\n }\n \n public static <T1, T2, T3, T4> ResultSetMapper<Tuple4<T1, T2, T3, T4>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3,\n final Class<T4> cls4) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n return new ResultSetMapper<Tuple4<T1, T2, T3, T4>>() {\n @Override\n public Tuple4<T1, T2, T3, T4> apply(ResultSet rs) {\n return new Tuple4<T1, T2, T3, T4>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4));\n }\n };\n }\n\n public static <T1, T2, T3, T4, T5> ResultSetMapper<Tuple5<T1, T2, T3, T4, T5>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3, final Class<T4> cls4,\n final Class<T5> cls5) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n Preconditions.checkNotNull(cls5, \"cls5 cannot be null\");\n\n return new ResultSetMapper<Tuple5<T1, T2, T3, T4, T5>>() {\n @Override\n public Tuple5<T1, T2, T3, T4, T5> apply(ResultSet rs) {\n return new Tuple5<T1, T2, T3, T4, T5>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4), mapObject(rs, cls5, 5));\n }\n };\n }\n\n public static <T1, T2, T3, T4, T5, T6> ResultSetMapper<Tuple6<T1, T2, T3, T4, T5, T6>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3, final Class<T4> cls4,\n final Class<T5> cls5, final Class<T6> cls6) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n Preconditions.checkNotNull(cls5, \"cls5 cannot be null\");\n Preconditions.checkNotNull(cls6, \"cls6 cannot be null\");\n return new ResultSetMapper<Tuple6<T1, T2, T3, T4, T5, T6>>() {\n @Override\n public Tuple6<T1, T2, T3, T4, T5, T6> apply(ResultSet rs) {\n return new Tuple6<T1, T2, T3, T4, T5, T6>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4), mapObject(rs, cls5, 5),\n mapObject(rs, cls6, 6));\n }\n };\n }\n\n public static <T1, T2, T3, T4, T5, T6, T7> ResultSetMapper<Tuple7<T1, T2, T3, T4, T5, T6, T7>> tuple(\n final Class<T1> cls1, final Class<T2> cls2, final Class<T3> cls3, final Class<T4> cls4,\n final Class<T5> cls5, final Class<T6> cls6, final Class<T7> cls7) {\n Preconditions.checkNotNull(cls1, \"cls1 cannot be null\");\n Preconditions.checkNotNull(cls2, \"cls2 cannot be null\");\n Preconditions.checkNotNull(cls3, \"cls3 cannot be null\");\n Preconditions.checkNotNull(cls4, \"cls4 cannot be null\");\n Preconditions.checkNotNull(cls5, \"cls5 cannot be null\");\n Preconditions.checkNotNull(cls6, \"cls6 cannot be null\");\n Preconditions.checkNotNull(cls7, \"cls7 cannot be null\");\n return new ResultSetMapper<Tuple7<T1, T2, T3, T4, T5, T6, T7>>() {\n @Override\n public Tuple7<T1, T2, T3, T4, T5, T6, T7> apply(ResultSet rs) {\n return new Tuple7<T1, T2, T3, T4, T5, T6, T7>(mapObject(rs, cls1, 1),\n mapObject(rs, cls2, 2), mapObject(rs, cls3, 3),\n mapObject(rs, cls4, 4), mapObject(rs, cls5, 5),\n mapObject(rs, cls6, 6), mapObject(rs, cls7, 7));\n }\n };\n }\n\n public static <T> ResultSetMapper<TupleN<T>> tupleN(final Class<T> cls) {\n Preconditions.checkNotNull(cls, \"cls cannot be null\");\n return new ResultSetMapper<TupleN<T>>() {\n @Override\n public TupleN<T> apply(ResultSet rs) {\n return toTupleN(cls, rs);\n }\n };\n }\n\n private static <T> TupleN<T> toTupleN(final Class<T> cls, ResultSet rs) {\n try {\n int n = rs.getMetaData().getColumnCount();\n List<T> list = new ArrayList<T>();\n for (int i = 1; i <= n; i++) {\n list.add(mapObject(rs, cls, i));\n }\n return new TupleN<T>(list);\n } catch (SQLException e) {\n throw new SQLRuntimeException(e);\n }\n }\n}" ]
import java.sql.ResultSet; import java.util.Optional; import javax.annotation.Nonnull; import org.davidmoten.rx.jdbc.tuple.Tuple2; import org.davidmoten.rx.jdbc.tuple.Tuple3; import org.davidmoten.rx.jdbc.tuple.Tuple4; import org.davidmoten.rx.jdbc.tuple.Tuple5; import org.davidmoten.rx.jdbc.tuple.Tuple6; import org.davidmoten.rx.jdbc.tuple.Tuple7; import org.davidmoten.rx.jdbc.tuple.TupleN; import org.davidmoten.rx.jdbc.tuple.Tuples; import com.github.davidmoten.guavamini.Preconditions; import io.reactivex.Flowable; import io.reactivex.Single;
package org.davidmoten.rx.jdbc; public interface GetterTx { /** * Transforms the results using the given function. * * @param mapper * transforms ResultSet row to an object of type T * @param <T> * the type being mapped to * @return the results of the query as an Observable */ <T> Flowable<Tx<T>> get(@Nonnull ResultSetMapper<? extends T> mapper); default <T> Flowable<Tx<T>> getAs(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(rs -> Util.mapObject(rs, cls, 1)); } default <T> Flowable<Tx<Optional<T>>> getAsOptional(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(rs -> Optional.ofNullable(Util.mapObject(rs, cls, 1))); } /** * <p> * Transforms each row of the {@link ResultSet} into an instance of * <code>T</code> using <i>automapping</i> of the ResultSet columns into * corresponding constructor parameters that are assignable. Beyond normal * assignable criteria (for example Integer 123 is assignable to a Double) other * conversions exist to facilitate the automapping: * </p> * <p> * They are: * <ul> * <li>java.sql.Blob --&gt; byte[]</li> * <li>java.sql.Blob --&gt; java.io.InputStream</li> * <li>java.sql.Clob --&gt; String</li> * <li>java.sql.Clob --&gt; java.io.Reader</li> * <li>java.sql.Date --&gt; java.util.Date</li> * <li>java.sql.Date --&gt; Long</li> * <li>java.sql.Timestamp --&gt; java.util.Date</li> * <li>java.sql.Timestamp --&gt; Long</li> * <li>java.sql.Time --&gt; java.util.Date</li> * <li>java.sql.Time --&gt; Long</li> * <li>java.math.BigInteger --&gt; * Short,Integer,Long,Float,Double,BigDecimal</li> * <li>java.math.BigDecimal --&gt; * Short,Integer,Long,Float,Double,BigInteger</li> * </ul> * * @param cls * class to automap each row of the ResultSet to * @param <T> * generic type of returned stream emissions * @return Flowable of T * */ default <T> Flowable<Tx<T>> autoMap(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(Util.autoMap(cls)); } /** * Automaps all the columns of the {@link ResultSet} into the target class * <code>cls</code>. See {@link #autoMap(Class) autoMap()}. * * @param cls * class of the TupleN elements * @param <T> * generic type of returned stream emissions * @return stream of transaction items */ default <T> Flowable<Tx<TupleN<T>>> getTupleN(@Nonnull Class<T> cls) { Preconditions.checkNotNull(cls, "cls cannot be null"); return get(Tuples.tupleN(cls)); } /** * Automaps all the columns of the {@link ResultSet} into {@link Object} . See * {@link #autoMap(Class) autoMap()}. * * @return stream of transaction items */ default Flowable<Tx<TupleN<Object>>> getTupleN() { return get(Tuples.tupleN(Object.class)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param <T1> * type of first class * @param <T2> * type of second class * @return stream of transaction items */ default <T1, T2> Flowable<Tx<Tuple2<T1, T2>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2) { return get(Tuples.tuple(cls1, cls2)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @return stream of tuples */ default <T1, T2, T3> Flowable<Tx<Tuple3<T1, T2, T3>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3) { return get(Tuples.tuple(cls1, cls2, cls3)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @return stream of tuples */ default <T1, T2, T3, T4> Flowable<Tx<Tuple4<T1, T2, T3, T4>>> getAs(@Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4) { return get(Tuples.tuple(cls1, cls2, cls3, cls4)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param cls5 * fifth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @param <T5> * type of fifth class * @return stream of transaction items */ default <T1, T2, T3, T4, T5> Flowable<Tx<Tuple5<T1, T2, T3, T4, T5>>> getAs( @Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4, @Nonnull Class<T5> cls5) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param cls5 * fifth class * @param cls6 * sixth class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @param <T5> * type of fifth class * @param <T6> * type of sixth class * @return stream of transaction items */ default <T1, T2, T3, T4, T5, T6> Flowable<Tx<Tuple6<T1, T2, T3, T4, T5, T6>>> getAs( @Nonnull Class<T1> cls1, @Nonnull Class<T2> cls2, @Nonnull Class<T3> cls3, @Nonnull Class<T4> cls4, @Nonnull Class<T5> cls5, @Nonnull Class<T6> cls6) { return get(Tuples.tuple(cls1, cls2, cls3, cls4, cls5, cls6)); } /** * Automaps the columns of the {@link ResultSet} into the specified classes. See * {@link #autoMap(Class) autoMap()}. * * @param cls1 * first class * @param cls2 * second class * @param cls3 * third class * @param cls4 * fourth class * @param cls5 * fifth class * @param cls6 * sixth class * @param cls7 * seventh class * @param <T1> * type of first class * @param <T2> * type of second class * @param <T3> * type of third class * @param <T4> * type of fourth class * @param <T5> * type of fifth class * @param <T6> * type of sixth class * @param <T7> * type of seventh class * @return stream of transaction items */
default <T1, T2, T3, T4, T5, T6, T7> Flowable<Tx<Tuple7<T1, T2, T3, T4, T5, T6, T7>>> getAs(
5
axxepta/project-argon
src/main/java/de/axxepta/oxygen/workspace/DitaMapManagerChangeListener.java
[ "public class CheckInAction extends AbstractAction {\n\n private static final Logger logger = LogManager.getLogger(CheckInAction.class);\n\n private final TreeListener treeListener;\n private URL urlString = null;\n\n public CheckInAction(String name, Icon icon, String urlString, TreeListener treeListener) {\n super(name, icon);\n\n try {\n this.urlString = urlString != null ? new URL(urlString) : null;\n } catch (MalformedURLException e) {\n logger.error(e.getMessage());\n throw new IllegalArgumentException(e.getMessage(), e);\n }\n this.treeListener = treeListener;\n }\n\n public CheckInAction(String name, Icon icon, TreeListener treeListener) {\n this(name, icon, null, treeListener);\n }\n\n public CheckInAction(String name, Icon icon, String urlString) {\n this(name, icon, urlString, null);\n }\n\n public CheckInAction(String name, Icon icon) {\n this(name, icon, null, null);\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n if (this.urlString != null) {\n checkIn(this.urlString);\n } else if (treeListener == null) {\n final URL url = PluginWorkspaceProvider.getPluginWorkspace().\n getCurrentEditorAccess(MAIN_EDITING_AREA).getEditorLocation();\n checkIn(url);\n } else if (!treeListener.getNode().getAllowsChildren()) {\n final String urlString = TreeUtils.urlStringFromTreePath(treeListener.getPath());\n try {\n checkIn(new URL(urlString));\n } catch (MalformedURLException ex) {\n throw new IllegalArgumentException(ex);\n }\n }\n }\n\n static void checkIn(URL url) {\n final BaseXSource source = CustomProtocolURLUtils.sourceFromURL(url);\n final String path = CustomProtocolURLUtils.pathFromURL(url);\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n if (connection.lockedByUser(source, path)) {\n ArgonEditorsWatchMap.getInstance().setAskedForCheckIn(url, true);\n if (false) {\n final WSEditor editorAccess = PluginWorkspaceProvider.getPluginWorkspace().\n getEditorAccess(url, MAIN_EDITING_AREA);\n if (editorAccess != null) {\n editorAccess.close(true);\n }\n }\n connection.unlock(source, path);\n }\n } catch (IOException ex) {\n logger.debug(ex);\n }\n }\n\n}", "public class CheckOutAction extends AbstractAction {\n\n private static final Logger logger = LogManager.getLogger(CheckOutAction.class);\n\n private final TreeListener treeListener;\n private String urlString = null;\n\n public CheckOutAction(String name, Icon icon, String urlString, TreeListener treeListener) {\n super(name, icon);\n this.urlString = urlString;\n this.treeListener = treeListener;\n }\n\n public CheckOutAction(String name, Icon icon, TreeListener treeListener) {\n this(name, icon, null, treeListener);\n// super(name, icon);\n// this.treeListener = treeListener;\n }\n\n public CheckOutAction(String name, Icon icon) {\n this(name, icon, null, null);\n// super(name, icon);\n// treeListener = null;\n }\n\n public CheckOutAction(String name, Icon icon, String urlString) {\n this(name, icon, urlString, null);\n// super(name, icon);\n// treeListener = null;\n// this.urlString = urlString;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n if (this.urlString != null) {\n checkOut(this.urlString);\n } else if (treeListener == null) {\n final URL url = PluginWorkspaceProvider.getPluginWorkspace().\n getCurrentEditorAccess(MAIN_EDITING_AREA).getEditorLocation();\n checkOut(url.toString());\n } else if (!treeListener.getNode().getAllowsChildren()) {\n final String urlString = TreeUtils.urlStringFromTreePath(treeListener.getPath());\n checkOut(urlString);\n }\n }\n\n // @SuppressWarnings(\"all\")\n public static void checkOut(String urlString) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n connection.lock(CustomProtocolURLUtils.sourceFromURLString(urlString),\n CustomProtocolURLUtils.pathFromURLString(urlString));\n ArgonEditorsWatchMap.getInstance().addURL(new URL(urlString), true);\n } catch (IOException ex) {\n logger.debug(ex);\n }\n WorkspaceUtils.openURLString(urlString);\n }\n}", "public class ArgonEditorsWatchMap implements ObserverInterface<ListDirEvent> {\r\n\r\n private static final ArgonEditorsWatchMap instance = new ArgonEditorsWatchMap();\r\n\r\n private final Map<URL, EditorInfo> editorMap = new HashMap<>();\r\n /**\r\n * contains all Argon resources with locks, locks owned by current user marked with true value\r\n */\r\n private final Map<URL, Boolean> lockMap = new HashMap<>();\r\n\r\n\r\n private ArgonEditorsWatchMap() {\r\n }\r\n\r\n public static ArgonEditorsWatchMap getInstance() {\r\n return instance;\r\n }\r\n\r\n public void init() {\r\n TopicHolder.newDir.register(this);\r\n update(listDir, \"\");\r\n }\r\n\r\n private boolean isLockInMap(URL url) {\r\n return !(lockMap.get(url) == null);\r\n }\r\n\r\n public boolean hasOwnLock(URL url) {\r\n return isLockInMap(url) && lockMap.get(url);\r\n }\r\n\r\n public boolean hasOtherLock(URL url) {\r\n return isLockInMap(url) && !lockMap.get(url);\r\n }\r\n\r\n public void addURL(URL url) {\r\n if (!isURLInMap(url)) {\r\n editorMap.put(url, new EditorInfo(false));\r\n }\r\n }\r\n\r\n public void addURL(URL url, boolean checkedOut) {\r\n if (isURLInMap(url)) {\r\n editorMap.get(url).setCheckedOut(checkedOut);\r\n } else {\r\n editorMap.put(url, new EditorInfo(checkedOut));\r\n }\r\n if (checkedOut) {\r\n lockMap.put(url, true);\r\n }\r\n }\r\n\r\n public void removeURL(URL url) {\r\n editorMap.remove(url);\r\n if (isLockInMap(url) && lockMap.get(url)) {\r\n lockMap.remove(url);\r\n }\r\n }\r\n\r\n private boolean isURLInMap(URL url) {\r\n return !(editorMap.get(url) == null);\r\n }\r\n\r\n public String getEncoding(URL url) {\r\n if (isURLInMap(url)) {\r\n return \"UTF-8\";\r\n } else {\r\n return \"\";\r\n }\r\n }\r\n\r\n public boolean askedForCheckIn(URL url) {\r\n if (isURLInMap(url)) {\r\n return editorMap.get(url).isAskedForCheckIn();\r\n } else {\r\n return true;\r\n }\r\n }\r\n\r\n public void setAskedForCheckIn(URL url, boolean asked) {\r\n if (isURLInMap(url)) {\r\n editorMap.get(url).setAskedForCheckIn(asked);\r\n }\r\n }\r\n\r\n @Override\r\n public void update(ListDirEvent type, Object... message) {\r\n //\r\n }\r\n\r\n\r\n private static class EditorInfo {\r\n\r\n boolean checkedOut;\r\n boolean askedForCheckIn = false;\r\n\r\n EditorInfo(boolean checkedOut) {\r\n this.checkedOut = checkedOut;\r\n }\r\n\r\n boolean isAskedForCheckIn() {\r\n return askedForCheckIn;\r\n }\r\n\r\n void setAskedForCheckIn(boolean askedForCheckIn) {\r\n this.askedForCheckIn = askedForCheckIn;\r\n }\r\n\r\n void setCheckedOut(boolean checkedOut) {\r\n this.checkedOut = checkedOut;\r\n }\r\n }\r\n\r\n}\r", "public class CustomProtocolURLUtils {\n\n private static final Logger logger = LogManager.getLogger(CustomProtocolURLUtils.class);\n\n public static String pathFromURL(URL url) {\n String urlString = \"\";\n try {\n urlString = java.net.URLDecoder.decode(url.toString(), \"UTF-8\");\n } catch (UnsupportedEncodingException | IllegalArgumentException ex) {\n logger.error(\"URLDecoder error decoding \" + url.toString(), ex.getMessage());\n }\n return pathFromURLString(urlString);\n }\n\n public static String pathFromURLString(String urlString) {\n String[] urlComponents = urlString.split(\":/*\");\n if (urlComponents.length < 2) {\n return \"\";\n // ToDo: exception handling\n } else {\n return urlComponents[1];\n }\n }\n\n public static BaseXSource sourceFromURL(URL url) {\n return sourceFromURLString(url.toString());\n }\n\n public static BaseXSource sourceFromURLString(String urlString) {\n final URI uri = URI.create(urlString);\n if (uri.getScheme() == null) {\n return null;\n }\n switch (uri.getScheme()) {\n// case ArgonConst.ARGON_XQ:\n// return BaseXSource.RESTXQ;\n case ArgonConst.ARGON_REPO:\n return BaseXSource.REPO;\n case ArgonConst.ARGON:\n return BaseXSource.DATABASE;\n default:\n return null;\n }\n }\n}", "public class ImageUtils {\r\n\r\n private static final Logger logger = LogManager.getLogger(ImageUtils.class);\r\n\r\n static private Map<String, Icon> iconMap;\r\n\r\n // CAVE: String constants as Icon keys must be lowercase because the get function makes lowercase of requested keys!\r\n public static final String DB_CONNECTION = \"dbconnection16\";\r\n public static final String DB_CATALOG = \"dbcatalog16\";\r\n public static final String DB_HTTP = \"dbhttp16\";\r\n public static final String DB_FOLDER = \"dbfolder16\";\r\n public static final String FOLDER = \"folderclosed16\";\r\n public static final String URL_OPEN = \"openurl16\";\r\n public static final String FILE_ADD = \"addfile16\";\r\n public static final String DB_ADD = \"addb16\";\r\n public static final String ADD_DIR = \"add_dir16\";\r\n public static final String EXPORT = \"export16\";\r\n public static final String REMOVE = \"remove16\";\r\n public static final String RENAME = \"rename16\";\r\n public static final String INC_VER = \"incversion16\";\r\n public static final String VER_HIST = \"verhistory\";\r\n public static final String REFRESH = \"refresh16\";\r\n public static final String SEARCH_PATH = \"searchinpath16\";\r\n public static final String SEARCH = \"search16\";\r\n public static final String TEAM_LIBRARY = \"teamlibrary\";\r\n public static final String SHARED = \"shared\";\r\n public static final String S_DATABASE = \"s_db\";\r\n public static final String F_DATABASE = \"f_db\";\r\n public static final String T_DATABASE = \"t_db\";\r\n public static final String P_DATABASE = \"p_db\";\r\n public static final String BASEX = \"basex16\";\r\n public static final String BASEX_LOCKED = \"basex16locked\";\r\n public static final String BASEX24 = \"basex24\";\r\n public static final String BASEX24ADD = \"basex24add\";\r\n public static final String UNLOCK = \"unlock\";\r\n public static final String SNIPPET = \"snippet\";\r\n public static final String INSERT_TEMPLATE = \"inserttemplate\";\r\n public static final String SINGLE_UPDATE = \"singleupdate\";\r\n\r\n public static void init() {\r\n iconMap = new HashMap<>();\r\n iconMap.put(\"xml\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"dita\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"ditaval\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"ditacontrol\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"xhtml\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"opf\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"ncx\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"xlf\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"ditamap\", ro.sync.ui.Icons.getIcon(Icons.DITAMAP_TEMPLATE));\r\n iconMap.put(\"epub\", ro.sync.ui.Icons.getIcon(Icons.EPUB_TEMPLATE));\r\n iconMap.put(\"cat\", ro.sync.ui.Icons.getIcon(Icons.XML_TEMPLATE));\r\n iconMap.put(\"wsdl\", ro.sync.ui.Icons.getIcon(Icons.WSDL_TEMPLATE));\r\n iconMap.put(\"xsl\", ro.sync.ui.Icons.getIcon(Icons.XSL_TEMPLATE));\r\n iconMap.put(\"xsd\", ro.sync.ui.Icons.getIcon(Icons.XSD_TEMPLATE));\r\n iconMap.put(\"rng\", ro.sync.ui.Icons.getIcon(Icons.RNG_TEMPLATE));\r\n iconMap.put(\"rnc\", ro.sync.ui.Icons.getIcon(Icons.RNC_TEMPLATE));\r\n iconMap.put(\"nvdl\", ro.sync.ui.Icons.getIcon(Icons.NVDL_TEMPLATE));\r\n iconMap.put(\"dtd\", ro.sync.ui.Icons.getIcon(Icons.DTD_TEMPLATE));\r\n iconMap.put(\"mod\", ro.sync.ui.Icons.getIcon(Icons.DTD_TEMPLATE));\r\n iconMap.put(\"ent\", ro.sync.ui.Icons.getIcon(Icons.DTD_TEMPLATE));\r\n iconMap.put(\"xpl\", ro.sync.ui.Icons.getIcon(Icons.XPROC_TEMPLATE));\r\n iconMap.put(\"xpr\", ro.sync.ui.Icons.getIcon(Icons.XPR_TEMPLATE));\r\n iconMap.put(\"css\", ro.sync.ui.Icons.getIcon(Icons.CSS_TEMPLATE));\r\n iconMap.put(\"xquery\", ro.sync.ui.Icons.getIcon(Icons.XQUERY_TEMPLATE));\r\n iconMap.put(\"xq\", ro.sync.ui.Icons.getIcon(Icons.XQUERY_TEMPLATE));\r\n iconMap.put(\"xql\", ro.sync.ui.Icons.getIcon(Icons.XQUERY_TEMPLATE));\r\n iconMap.put(\"xqm\", ro.sync.ui.Icons.getIcon(Icons.XQUERY_TEMPLATE));\r\n iconMap.put(\"xqy\", ro.sync.ui.Icons.getIcon(Icons.XQUERY_TEMPLATE));\r\n iconMap.put(\"xu\", ro.sync.ui.Icons.getIcon(Icons.XQUERY_TEMPLATE));\r\n iconMap.put(\"html\", ro.sync.ui.Icons.getIcon(Icons.HTML_TEMPLATE));\r\n iconMap.put(\"sch\", ro.sync.ui.Icons.getIcon(Icons.SCH_TEMPLATE));\r\n iconMap.put(\"fo\", ro.sync.ui.Icons.getIcon(Icons.FO_TEMPLATE));\r\n iconMap.put(\"txt\", ro.sync.ui.Icons.getIcon(Icons.TXT_TEMPLATE));\r\n iconMap.put(\"json\", ro.sync.ui.Icons.getIcon(Icons.JSON_TEMPLATE));\r\n iconMap.put(\"js\", ro.sync.ui.Icons.getIcon(Icons.JS_TEMPLATE));\r\n iconMap.put(\"sql\", ro.sync.ui.Icons.getIcon(Icons.SQL_TEMPLATE));\r\n iconMap.put(\"php\", ro.sync.ui.Icons.getIcon(Icons.PHP_TEMPLATE));\r\n iconMap.put(\"xspec\", ro.sync.ui.Icons.getIcon(Icons.XSPEC_TEMPLATE));\r\n// iconMap.put(\"tpl\", ImageUtils.createImageIcon(\"/images/TPL16.png\"));\r\n iconMap.put(\"tpl\", ImageUtils.createImageIcon(\"/images/FolderClosed16.png\"));\r\n iconMap.put(\"file\", ImageUtils.createImageIcon(\"/images/file16.png\"));\r\n iconMap.put(DB_CONNECTION, ImageUtils.createImageIcon(\"/images/DbConnection16.gif\"));\r\n iconMap.put(DB_CATALOG, ImageUtils.createImageIcon(\"/images/DbCatalog16.png\"));\r\n iconMap.put(DB_HTTP, ImageUtils.createImageIcon(\"/images/DBHttp16.png\"));\r\n iconMap.put(DB_FOLDER, ImageUtils.createImageIcon(\"/images/DbFolder16.png\"));\r\n iconMap.put(FOLDER, ImageUtils.createImageIcon(\"/images/FolderClosed16.png\"));\r\n iconMap.put(URL_OPEN, ImageUtils.createImageIcon(\"/images/OpenURL16.gif\"));\r\n iconMap.put(FILE_ADD, ImageUtils.createImageIcon(\"/images/AddFile16.png\"));\r\n iconMap.put(INC_VER, ImageUtils.createImageIcon(\"/images/IncVersion16.png\"));\r\n iconMap.put(VER_HIST, ImageUtils.createImageIcon(\"/images/VerHistory.png\"));\r\n iconMap.put(DB_ADD, ImageUtils.createImageIcon(\"/images/AddDb.png\"));\r\n iconMap.put(ADD_DIR, ImageUtils.createImageIcon(\"/images/AddDir.png\"));\r\n iconMap.put(EXPORT, ImageUtils.createImageIcon(\"/images/Export16.png\"));\r\n iconMap.put(REMOVE, ImageUtils.createImageIcon(\"/images/Remove16.png\"));\r\n iconMap.put(RENAME, ImageUtils.createImageIcon(\"/images/Rename16.png\"));\r\n iconMap.put(REFRESH, ImageUtils.createImageIcon(\"/images/Refresh16.png\"));\r\n iconMap.put(SEARCH_PATH, ImageUtils.createImageIcon(\"/images/SearchInPath16.png\"));\r\n iconMap.put(SEARCH, ImageUtils.createImageIcon(\"/images/SearchInFiles16.png\"));\r\n iconMap.put(SHARED, ImageUtils.createImageIcon(\"/images/DbCatalogShared16.png\"));\r\n iconMap.put(TEAM_LIBRARY, ImageUtils.createImageIcon(\"/images/DbCatalogTeam16.png\"));\r\n iconMap.put(S_DATABASE, ImageUtils.createImageIcon(\"/images/DbCatalogS16.png\"));\r\n iconMap.put(F_DATABASE, ImageUtils.createImageIcon(\"/images/DbCatalogF16.png\"));\r\n iconMap.put(T_DATABASE, ImageUtils.createImageIcon(\"/images/DbCatalogT16.png\"));\r\n iconMap.put(P_DATABASE, ImageUtils.createImageIcon(\"/images/DbCatalogP16.png\"));\r\n iconMap.put(BASEX, ImageUtils.createImageIcon(\"/images/BaseX_16_tr.png\"));\r\n iconMap.put(BASEX_LOCKED, ImageUtils.createImageIcon(\"/images/BaseXlocked.png\"));\r\n iconMap.put(BASEX24, ImageUtils.createImageIcon(\"/images/BaseX24.png\"));\r\n iconMap.put(BASEX24ADD, ImageUtils.createImageIcon(\"/images/BaseX24add.png\"));\r\n iconMap.put(UNLOCK, ImageUtils.createImageIcon(\"/images/unlock.png\"));\r\n iconMap.put(SNIPPET, ImageUtils.createImageIcon(\"/images/snippet.png\"));\r\n iconMap.put(INSERT_TEMPLATE, ImageUtils.createImageIcon(\"/images/InsertTemplate16.png\"));\r\n iconMap.put(SINGLE_UPDATE, ImageUtils.createImageIcon(\"/images/UpdateSingleDocument16.png\"));\r\n }\r\n\r\n public static Icon getIcon(String extension) {\r\n if (iconMap == null) {\r\n init();\r\n }\r\n if (iconMap.get(extension.toLowerCase()) == null) {\r\n return iconMap.get(\"file\");\r\n } else {\r\n return iconMap.get(extension.toLowerCase());\r\n }\r\n }\r\n\r\n public static Image createImage(String path) {\r\n Icon icon = createImageIcon(path);\r\n if (icon instanceof ImageIcon) {\r\n return ((ImageIcon) icon).getImage();\r\n } else {\r\n int w = icon.getIconWidth();\r\n int h = icon.getIconHeight();\r\n GraphicsEnvironment ge =\r\n GraphicsEnvironment.getLocalGraphicsEnvironment();\r\n GraphicsDevice gd = ge.getDefaultScreenDevice();\r\n GraphicsConfiguration gc = gd.getDefaultConfiguration();\r\n BufferedImage image = gc.createCompatibleImage(w, h);\r\n Graphics2D g = image.createGraphics();\r\n icon.paintIcon(null, g, 0, 0);\r\n g.dispose();\r\n return image;\r\n }\r\n }\r\n\r\n public static ImageIcon createImageIcon(String path) {\r\n java.net.URL imgURL = ArgonTree.class.getResource(path);\r\n if (imgURL != null) {\r\n return new ImageIcon(imgURL);\r\n } else {\r\n logger.error(\"Couldn't find file: \" + path);\r\n return null;\r\n }\r\n }\r\n\r\n}\r", "public class Lang {\r\n\r\n private static final Logger logger = LogManager.getLogger(Lang.class);\r\n\r\n private static final String PATH = \"/Argon\";\r\n private static final String MISSING_KEY = \"missing_key:\";\r\n private static final String MISSING_RESOURCE = \"missing_resource:\";\r\n private static PluginResourceBundle bundle = null;\r\n\r\n private static final Map<Locale, Bundle> availableResourceBundles = new HashMap<>();\r\n static {\r\n loadBundle(Locale.GERMANY);\r\n loadBundle(Locale.UK);\r\n }\r\n private static Bundle currentBundle = availableResourceBundles.get(Locale.UK);\r\n\r\n public static void init() {\r\n init(Locale.UK);\r\n }\r\n\r\n public static void init(Locale locale) {\r\n setLocale(locale);\r\n }\r\n\r\n private static void loadBundle(final Locale locale) {\r\n try {\r\n final Bundle bundle = new Bundle(PATH, locale);\r\n availableResourceBundles.put(locale, bundle);\r\n } catch (final IOException ex) {\r\n logger.warn(\"Failed to read resource '\" + PATH + \"' for locale: '\" + locale + \"'\", ex);\r\n } catch (final NullPointerException ex) {\r\n logger.warn(\"Missing resource '\" + PATH + \"' for locale: '\" + locale + \"'\", ex);\r\n }\r\n }\r\n\r\n public static void setLocale(Locale locale) {\r\n if (locale.equals(Locale.GERMANY) || locale.equals(Locale.GERMAN)) {\r\n currentBundle = availableResourceBundles.get(Locale.GERMANY);\r\n } else {\r\n currentBundle = availableResourceBundles.get(Locale.UK);\r\n }\r\n }\r\n \r\n public static void init(StandalonePluginWorkspace wsa) {\r\n bundle = wsa.getResourceBundle();\r\n }\r\n\r\n public static String get(Keys key) {\r\n if (bundle != null) {\r\n return bundle.getMessage(key.name());\r\n }\r\n if (currentBundle != null) {\r\n String val = currentBundle.getString(key.name());\r\n if (val != null) {\r\n return val;\r\n } else {\r\n try {\r\n throw new RuntimeException();\r\n } catch (RuntimeException e) {\r\n logger.error(\"Missing key\", e);\r\n }\r\n return MISSING_KEY + key;\r\n }\r\n } else {\r\n try {\r\n throw new RuntimeException();\r\n } catch (RuntimeException e) {\r\n logger.error(\"Missing bundle\", e);\r\n }\r\n return MISSING_RESOURCE + key;\r\n }\r\n }\r\n\r\n public enum Keys {\r\n tree_root, tree_DB,\r\n tree_repo,\r\n// tree_restxq,\r\n cm_open, cm_checkout, cm_checkin, cm_adddb, cm_add, cm_addsimple,\r\n cm_addfile, cm_delete, cm_rename, cm_newversion, cm_showversion, cm_refresh, cm_search, cm_searchsimple, cm_find,\r\n cm_newdir, cm_save, cm_ok, cm_cancel, cm_tofile, cm_todb, cm_export, cm_checkinselected, cm_exit, cm_saveas,\r\n cm_replycomment,\r\n cm_runquery,\r\n cm_yes, cm_no, cm_all, cm_always, cm_never, cm_compare, cm_reset, cm_overwrite,\r\n cm_nosave,\r\n lbl_filename, lbl_filetype, lbl_filestocheck, lbl_delete, lbl_dir, lbl_searchpath, lbl_elements, lbl_text,\r\n lbl_attributes, lbl_attrbvalues, lbl_scope, lbl_options, lbl_whole, lbl_casesens, lbl_snippet,\r\n lbl_search1, lbl_search2, lbl_search3, lbl_search4, lbl_overwrite, lbl_version, lbl_revision, lbl_date, lbl_closed,\r\n lbl_connection, lbl_host, lbl_user, lbl_pwd, lbl_vcs, lbl_fe, lbl_dboptions, lbl_chop, lbl_ftindex, lbl_textindex,\r\n lbl_attributeindex, lbl_tokenindex, lbl_fixdefault, tt_fe,\r\n title_connection, title_connection2, title_history,\r\n warn_failednewdb, warn_failednewfile, warn_faileddeletedb, warn_faileddelete,\r\n warn_failedexport, warn_failednewversion, warn_norename, warn_resource, warn_storing, warn_locked, warn_nosnippet,\r\n warn_nofile, warn_failedsearch, warn_failedlist, warn_notransfer, warn_transfernoread,\r\n warn_transfernowrite1, warn_transfernowrite2, warn_connectionsettings1, warn_connectionsettings2, warn_settingspath1,\r\n warn_settingspath2, warn_settingspath3,\r\n msg_dbexists1, msg_dbexists2, msg_fileexists1, msg_fileexists2, msg_noquery, msg_noeditor, msg_checkpriordelete,\r\n msg_noupdate1, msg_noupdate2, msg_norename1, msg_norename2, msg_norename3, msg_transferlocked, msg_nameexists,\r\n msg_settingsexists, msg_noscopeselected,\r\n dlg_addfileinto, dlg_externalquery, dlg_checkedout, dlg_delete, dlg_newdir, dlg_replycomment, dlg_saveas, dlg_open,\r\n dlg_snippet, dlg_foundresources, dlg_overwrite, dlg_closed, dlg_overwritesetting, dlg_newsetting\r\n }\r\n\r\n}\r", "public class VersionHistoryUpdater implements ObserverInterface<MsgTopic> {\n\n private final Logger logger = LogManager.getLogger(VersionHistoryUpdater.class);\n\n private List<VersionHistoryEntry> historyList = new ArrayList<>();\n private final JTable versionHistoryTable;\n\n VersionHistoryUpdater(JTable versionHistoryTable) {\n this.versionHistoryTable = versionHistoryTable;\n }\n\n public void update(MsgTopic type, Object... msg) {\n // ToDo: store data permanently in editor watch map to avoid repeated traffic--refresh historyList if editor is saved\n if ((msg[0] instanceof String) && !(msg[0]).equals(\"\")) {\n String urlString = (String) msg[0];\n String resource = CustomProtocolURLUtils.pathFromURLString(urlString);\n\n if (urlString.startsWith(ArgonConst.ARGON + \":\")) {\n try (Connection connection = BaseXConnectionWrapper.getConnection()) {\n historyList = connection.getHistory(resource);\n } catch (IOException ioe) {\n logger.error(\"Argon connection error while getting meta data from resource \" + resource + \": \" + ioe.getMessage(), ioe);\n }\n } else {\n historyList = new ArrayList<>();\n }\n }\n updateVersionHistory();\n }\n\n public static String checkVersionHistory(URL editorLocation) {\n if ((editorLocation != null) && (URLUtils.isArgon(editorLocation)))\n return editorLocation.toString();\n else\n return \"\";\n }\n\n private void updateVersionHistory() {\n ((VersionHistoryTableModel) versionHistoryTable.getModel()).setNewContent(historyList);\n versionHistoryTable.setFillsViewportHeight(true);\n versionHistoryTable.getColumnModel().getColumn(0).setPreferredWidth(20);\n versionHistoryTable.getColumnModel().getColumn(1).setPreferredWidth(20);\n versionHistoryTable.getColumnModel().getColumn(2).setCellRenderer(new DateTableCellRenderer());\n }\n\n}", "public static int booleanDialog(PluginWorkspace pluginWorkspace,\n String title,\n String msg,\n String trueButton, int trueValue, String falseButton,\n int falseValue,\n int initial) {\n return pluginWorkspace.showConfirmDialog(\n title,\n msg,\n new String[]{trueButton, falseButton},\n new int[]{trueValue, falseValue},\n initial);\n}" ]
import de.axxepta.oxygen.actions.CheckInAction; import de.axxepta.oxygen.actions.CheckOutAction; import de.axxepta.oxygen.api.*; import de.axxepta.oxygen.customprotocol.ArgonEditorsWatchMap; import de.axxepta.oxygen.customprotocol.CustomProtocolURLUtils; import de.axxepta.oxygen.utils.ImageUtils; import de.axxepta.oxygen.utils.Lang; import de.axxepta.oxygen.versioncontrol.VersionHistoryUpdater; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ro.sync.ecss.extensions.api.AuthorDocumentController; import ro.sync.ecss.extensions.api.node.AttrValue; import ro.sync.ecss.extensions.api.node.AuthorElement; import ro.sync.ecss.extensions.api.node.AuthorNode; import ro.sync.exml.editor.EditorPageConstants; import ro.sync.exml.workspace.api.editor.WSEditor; import ro.sync.exml.workspace.api.editor.page.ditamap.DITAMapPopupMenuCustomizer; import ro.sync.exml.workspace.api.editor.page.ditamap.WSDITAMapEditorPage; import ro.sync.exml.workspace.api.listeners.WSEditorChangeListener; import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace; import javax.swing.*; import java.io.IOException; import java.net.URL; import static de.axxepta.oxygen.utils.WorkspaceUtils.booleanDialog;
package de.axxepta.oxygen.workspace; /** * @author Markus on 05.11.2016. */ class DitaMapManagerChangeListener extends WSEditorChangeListener { private static final Logger logger = LogManager.getLogger(DitaMapManagerChangeListener.class); private final StandalonePluginWorkspace pluginWorkspaceAccess; DitaMapManagerChangeListener(StandalonePluginWorkspace pluginWorkspace) { super(); this.pluginWorkspaceAccess = pluginWorkspace; } @Override public void editorPageChanged(URL editorLocation) { customizeEditorPopupMenu(); } @Override public void editorSelected(URL editorLocation) { customizeEditorPopupMenu(); TopicHolder.changedEditorStatus.postMessage(VersionHistoryUpdater.checkVersionHistory(editorLocation)); } @Override public void editorActivated(URL editorLocation) { customizeEditorPopupMenu(); TopicHolder.changedEditorStatus.postMessage(VersionHistoryUpdater.checkVersionHistory(editorLocation)); } @Override public void editorClosed(URL editorLocation) { if (editorLocation.toString().startsWith(ArgonConst.ARGON)) { try (Connection connection = BaseXConnectionWrapper.getConnection()) { BaseXSource source = CustomProtocolURLUtils.sourceFromURL(editorLocation); String path = CustomProtocolURLUtils.pathFromURL(editorLocation); if (connection.lockedByUser(source, path) && !ArgonEditorsWatchMap.getInstance().askedForCheckIn(editorLocation)) { int checkInFile = booleanDialog(pluginWorkspaceAccess, "Closed checked out file", "You just closed a checked out file. Do you want to check it in?", "Yes", 0, "No", 1, 0); if (checkInFile == 0) { connection.unlock(source, path); } } } catch (IOException ioe) { logger.debug(ioe.getMessage()); } ArgonEditorsWatchMap.getInstance().removeURL(editorLocation); } } private void customizeEditorPopupMenu() { WSEditor editorAccess = pluginWorkspaceAccess.getCurrentEditorAccess(StandalonePluginWorkspace.DITA_MAPS_EDITING_AREA); if (editorAccess != null) { if (EditorPageConstants.PAGE_DITA_MAP.equals(editorAccess.getCurrentPageID())) { WSDITAMapEditorPage currentCustomizedDitaPageAccess; currentCustomizedDitaPageAccess = (WSDITAMapEditorPage) editorAccess.getCurrentPage(); currentCustomizedDitaPageAccess.setPopUpMenuCustomizer(new ArgonDitaPopupMenuCustomizer(currentCustomizedDitaPageAccess)); } } } private JMenuItem createCheckOutEditorPopUpAddition(String urlString) { return new JMenuItem(new CheckOutAction(Lang.get(Lang.Keys.cm_checkout), ImageUtils.getIcon(ImageUtils.UNLOCK), urlString)); } private JMenuItem createCheckInEditorPopUpAddition(String urlString) {
return new JMenuItem(new CheckInAction(Lang.get(Lang.Keys.cm_checkin), ImageUtils.getIcon(ImageUtils.BASEX_LOCKED), urlString));
0
dragonite-network/dragonite-java
dragonite-proxy/src/main/java/com/vecsight/dragonite/proxy/network/server/ProxyServer.java
[ "public class ProxyServerConfig {\n\n private InetSocketAddress bindAddress;\n\n private String password;\n\n private int mbpsLimit = 0;\n\n private String welcomeMessage = \"Welcome to \" + SystemInfo.getHostname();\n\n private boolean allowLoopback = false;\n\n private final DragoniteSocketParameters dragoniteSocketParameters = new DragoniteSocketParameters();\n\n public ProxyServerConfig(final InetSocketAddress bindAddress, final String password) throws EncryptionException {\n setBindAddress(bindAddress);\n setPassword(password);\n }\n\n public InetSocketAddress getBindAddress() {\n return bindAddress;\n }\n\n public void setBindAddress(final InetSocketAddress bindAddress) {\n checkArgument(bindAddress != null, \"Invalid bind address\");\n this.bindAddress = bindAddress;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(final String password) throws EncryptionException {\n checkArgument(password != null && password.length() >= ProxyGlobalConstants.PASSWORD_MIN_LENGTH, \"Invalid password\");\n dragoniteSocketParameters.setPacketCryptor(new AESCryptor(password));\n this.password = password;\n }\n\n public int getMbpsLimit() {\n return mbpsLimit;\n }\n\n public void setMbpsLimit(final int mbpsLimit) {\n checkArgument(mbpsLimit > 0 && mbpsLimit <= 65535, \"Invalid Mbps\");\n this.mbpsLimit = mbpsLimit;\n }\n\n public String getWelcomeMessage() {\n return welcomeMessage;\n }\n\n public void setWelcomeMessage(final String welcomeMessage) {\n checkArgument(welcomeMessage != null, \"Null welcome message\");\n this.welcomeMessage = welcomeMessage;\n }\n\n public boolean isAllowLoopback() {\n return allowLoopback;\n }\n\n public void setAllowLoopback(final boolean allowLoopback) {\n this.allowLoopback = allowLoopback;\n }\n\n public int getMTU() {\n return dragoniteSocketParameters.getPacketSize();\n }\n\n public void setMTU(final int mtu) {\n dragoniteSocketParameters.setPacketSize(mtu);\n }\n\n public int getWindowMultiplier() {\n return dragoniteSocketParameters.getWindowMultiplier();\n }\n\n public void setWindowMultiplier(final int mult) {\n dragoniteSocketParameters.setWindowMultiplier(mult);\n }\n\n public int getTrafficClass() {\n return dragoniteSocketParameters.getTrafficClass();\n }\n\n public void setTrafficClass(final int tc) {\n dragoniteSocketParameters.setTrafficClass(tc);\n }\n\n public boolean getWebPanelEnabled() {\n return dragoniteSocketParameters.isEnableWebPanel();\n }\n\n public void setWebPanelEnabled(final boolean enabled) {\n dragoniteSocketParameters.setEnableWebPanel(enabled);\n }\n\n public InetSocketAddress getWebPanelBind() {\n return dragoniteSocketParameters.getWebPanelBindAddress();\n }\n\n public void setWebPanelBind(final InetSocketAddress address) {\n dragoniteSocketParameters.setWebPanelBindAddress(address);\n }\n\n public DragoniteSocketParameters getDragoniteSocketParameters() {\n return dragoniteSocketParameters;\n }\n\n}", "public final class ProxyGlobalConstants {\n\n public static final String APP_VERSION = ProxyBuildConfig.VERSION;\n\n public static final byte PROTOCOL_VERSION = 2;\n\n public static final int DEFAULT_SERVER_PORT = 5234;\n\n public static final long INIT_SEND_SPEED = 100 * 1024; //100kb/s\n\n public static final Charset STRING_CHARSET = StandardCharsets.UTF_8;\n\n public static final Charset HEADER_ADDRESS_CHARSET = StandardCharsets.US_ASCII;\n\n public static final short PIPE_BUFFER_SIZE = 10240;\n\n public static final short MAX_FRAME_SIZE = 20480;\n\n public static final int PASSWORD_MIN_LENGTH = 4;\n\n public static final int SOCKS5_PORT = 1080;\n\n public static final int TCP_CONNECT_TIMEOUT_MS = 4000;\n\n public static final String UPDATE_API_URL = \"https://github.com/dragonite-network/dragonite-java/raw/master/VERSIONS\";\n\n public static final String UPDATE_API_PRODUCT_NAME = \"proxy\";\n\n}", "public interface PacketCryptor {\n\n /**\n * Encrypt the message and return the ciphertext.\n * This function may be called by multiple threads at the same time.\n *\n * @param rawData Content to be encrypted\n * @return Encrypted content\n */\n byte[] encrypt(final byte[] rawData);\n\n /**\n * Decrypt the ciphertext and return the message.\n * This function may be called by multiple threads at the same time.\n *\n * @param encryptedData Content to be decrypted\n * @return Decrypted content\n */\n byte[] decrypt(final byte[] encryptedData);\n\n /**\n * Many encryption methods need to add additional bytes to the original message.\n * Please specify the maximum length of additional bytes that the encryption might cause.\n *\n * @return Length of additional bytes\n */\n int getMaxAdditionalBytesLength();\n\n}", "public class DragoniteServer {\n\n //From parameters\n private final int packetSize, maxReceiveWindow;\n private final int windowMultiplier;\n private final int resendMinDelayMS;\n private final int heartbeatIntervalSec, receiveTimeoutSec;\n private final boolean autoSplit;\n private final boolean enableWebPanel;\n private final PacketCryptor packetCryptor;\n private final int cryptorOverhead;\n //end\n\n private volatile long defaultSendSpeed;\n\n private final DatagramSocket datagramSocket;\n\n private final BlockingQueue<DatagramPacket> packetBuffer;\n\n private final Thread receiveThread; //THREAD\n\n private final Thread handleThread; //THREAD\n\n private final Thread aliveDetectThread; //THREAD\n\n private volatile boolean doReceive = true, doHandle = true, doAliveDetect = true;\n\n private final ConcurrentMap<SocketAddress, DragoniteServerSocket> connectionMap = new ConcurrentHashMap<>();\n\n private final BlockingQueue<DragoniteSocket> acceptQueue = new LinkedBlockingQueue<>();\n\n private volatile boolean alive = true;\n\n private final Object closeLock = new Object();\n\n private final DevConsoleWebServer devConsoleWebServer;\n\n private final InetSocketAddress devConsoleBindAddress;\n\n public DragoniteServer(final InetAddress address, final int port, final long defaultSendSpeed, final DragoniteSocketParameters parameters) throws SocketException {\n datagramSocket = new DatagramSocket(port, address);\n\n //set from parameters\n packetSize = parameters.getPacketSize();\n maxReceiveWindow = parameters.getMaxPacketBufferSize();\n windowMultiplier = parameters.getWindowMultiplier();\n resendMinDelayMS = parameters.getResendMinDelayMS();\n heartbeatIntervalSec = parameters.getHeartbeatIntervalSec();\n receiveTimeoutSec = parameters.getReceiveTimeoutSec();\n autoSplit = parameters.isAutoSplit();\n enableWebPanel = parameters.isEnableWebPanel();\n devConsoleBindAddress = parameters.getWebPanelBindAddress();\n packetCryptor = parameters.getPacketCryptor();\n cryptorOverhead = packetCryptor != null ? packetCryptor.getMaxAdditionalBytesLength() : 0;\n\n datagramSocket.setTrafficClass(parameters.getTrafficClass());\n //end\n\n this.defaultSendSpeed = defaultSendSpeed;\n\n if (maxReceiveWindow == 0) {\n packetBuffer = new LinkedBlockingQueue<>();\n } else {\n packetBuffer = new LinkedBlockingQueue<>(maxReceiveWindow);\n }\n\n receiveThread = new Thread(() -> {\n try {\n while (doReceive) {\n final byte[] b = new byte[packetSize + cryptorOverhead];\n final DatagramPacket packet = new DatagramPacket(b, b.length);\n try {\n datagramSocket.receive(packet);\n packetBuffer.put(packet);\n } catch (final IOException ignored) {\n }\n }\n } catch (final InterruptedException ignored) {\n }\n }, \"DS-Receive\");\n receiveThread.start();\n\n handleThread = new Thread(() -> {\n try {\n while (doHandle) {\n final DatagramPacket packet = packetBuffer.take();\n handlePacket(packet);\n }\n } catch (final InterruptedException ignored) {\n //okay\n }\n }, \"DS-PacketHandle\");\n handleThread.start();\n\n aliveDetectThread = new Thread(() -> {\n try {\n while (doAliveDetect) {\n final long current = System.currentTimeMillis();\n final Iterator<Map.Entry<SocketAddress, DragoniteServerSocket>> it = connectionMap.entrySet().iterator();\n while (it.hasNext()) {\n final DragoniteServerSocket socket = it.next().getValue();\n if (socket.isAlive()) {\n if (current - socket.getLastReceiveTime() > receiveTimeoutSec * 1000) {\n //TIMEOUT\n //System.out.println(\"TIMEOUT \" + socket.getRemoteSocketAddress());\n socket.destroy_NoRemove();\n it.remove();\n } else if (current - socket.getLastSendTime() > heartbeatIntervalSec * 1000) {\n try {\n //TODO Fix blocking\n socket.sendHeartbeat();\n } catch (IOException | SenderClosedException ignored) {\n }\n }\n } else {\n it.remove();\n }\n }\n Thread.sleep(1000);\n }\n } catch (final InterruptedException ignored) {\n //okay\n }\n }, \"DS-AliveDetect\");\n aliveDetectThread.start();\n\n DevConsoleWebServer tmpServer = null;\n if (enableWebPanel) {\n try {\n tmpServer = new DevConsoleWebServer(devConsoleBindAddress, () -> {\n final ArrayList<DragoniteSocketStatistics> list = new ArrayList<>();\n for (final DragoniteServerSocket socket : connectionMap.values()) {\n list.add(socket.getStatistics());\n }\n return list;\n });\n } catch (final IOException ignored) {\n }\n }\n devConsoleWebServer = tmpServer;\n }\n\n public DragoniteServer(final int port, final long defaultSendSpeed, final DragoniteSocketParameters parameters) throws SocketException {\n this(null, port, defaultSendSpeed, parameters);\n }\n\n public DragoniteSocket accept() throws InterruptedException {\n return acceptQueue.take();\n }\n\n private void handlePacket(final DatagramPacket packet) throws InterruptedException {\n final SocketAddress remoteAddress = packet.getSocketAddress();\n Message message = null;\n try {\n final byte[] packetData = Arrays.copyOf(packet.getData(), packet.getLength());\n final byte[] data = packetCryptor != null ? packetCryptor.decrypt(packetData) : packetData;\n if (data != null) message = MessageParser.parseMessage(data);\n } catch (final IncorrectMessageException ignored) {\n }\n\n if (message != null) {\n DragoniteServerSocket dragoniteServerSocket = connectionMap.get(remoteAddress);\n if (dragoniteServerSocket == null) {\n //no connection yet\n if (message instanceof ReliableMessage) {\n if (message instanceof CloseMessage) {\n final ACKMessage ackMessage = new ACKMessage(new int[]{((CloseMessage) message).getSequence()}, 0);\n try {\n sendPacket(ackMessage.toBytes(), remoteAddress);\n } catch (final IOException ignored) {\n }\n } else if (((ReliableMessage) message).getSequence() == 0) {\n dragoniteServerSocket = createConnection(remoteAddress, defaultSendSpeed);\n dragoniteServerSocket.onHandleMessage(message, packet.getLength());\n\n acceptQueue.put(dragoniteServerSocket);\n }\n }\n } else {\n dragoniteServerSocket.onHandleMessage(message, packet.getLength());\n }\n }\n }\n\n private DragoniteServerSocket createConnection(final SocketAddress remoteAddress, final long sendSpeed) {\n final DragoniteServerSocket socket = new DragoniteServerSocket(remoteAddress, sendSpeed, this);\n connectionMap.put(remoteAddress, socket);\n return socket;\n }\n\n protected void removeConnectionFromMap(final SocketAddress remoteAddress) {\n connectionMap.remove(remoteAddress);\n }\n\n //SEND ALL PACKETS THROUGH THIS!!\n protected void sendPacket(final byte[] bytes, final SocketAddress socketAddress) throws IOException {\n final byte[] data = packetCryptor != null ? packetCryptor.encrypt(bytes) : bytes;\n if (data != null) {\n final DatagramPacket packet = new DatagramPacket(data, data.length);\n packet.setSocketAddress(socketAddress);\n datagramSocket.send(packet);\n }\n }\n\n public long getDefaultSendSpeed() {\n return defaultSendSpeed;\n }\n\n public void setDefaultSendSpeed(final long defaultSendSpeed) {\n this.defaultSendSpeed = defaultSendSpeed;\n }\n\n public int getPacketSize() {\n return packetSize;\n }\n\n public int getWindowMultiplier() {\n return windowMultiplier;\n }\n\n public int getResendMinDelayMS() {\n return resendMinDelayMS;\n }\n\n public int getHeartbeatIntervalSec() {\n return heartbeatIntervalSec;\n }\n\n public int getReceiveTimeoutSec() {\n return receiveTimeoutSec;\n }\n\n public boolean isAutoSplit() {\n return autoSplit;\n }\n\n public boolean isEnableWebPanel() {\n return enableWebPanel;\n }\n\n public void destroy() {\n synchronized (closeLock) {\n if (alive) {\n\n alive = false;\n\n doReceive = false;\n doHandle = false;\n doAliveDetect = false;\n\n final Iterator<Map.Entry<SocketAddress, DragoniteServerSocket>> it = connectionMap.entrySet().iterator();\n while (it.hasNext()) {\n final DragoniteServerSocket socket = it.next().getValue();\n socket.destroy_NoRemove();\n it.remove();\n }\n\n receiveThread.interrupt();\n handleThread.interrupt();\n aliveDetectThread.interrupt();\n\n packetBuffer.clear();\n\n datagramSocket.close();\n\n }\n }\n }\n\n}", "public abstract class DragoniteSocket {\n\n public abstract byte[] read() throws InterruptedException, ConnectionNotAliveException;\n\n public abstract void send(byte[] bytes) throws InterruptedException, IncorrectSizeException, IOException, SenderClosedException;\n\n public abstract boolean isAlive();\n\n protected abstract void updateLastReceiveTime();\n\n public abstract long getLastReceiveTime();\n\n protected abstract void updateLastSendTime();\n\n public abstract long getLastSendTime();\n\n public abstract SocketAddress getRemoteSocketAddress();\n\n public abstract void setSendSpeed(long sendSpeed);\n\n public abstract long getSendSpeed();\n\n public abstract DragoniteSocketStatistics getStatistics();\n\n public abstract String getDescription();\n\n public abstract void setDescription(String description);\n\n protected abstract void closeSender();\n\n public abstract void closeGracefully() throws InterruptedException, IOException, SenderClosedException;\n\n public abstract void destroy();\n\n}" ]
import com.vecsight.dragonite.proxy.config.ProxyServerConfig; import com.vecsight.dragonite.proxy.misc.ProxyGlobalConstants; import com.vecsight.dragonite.sdk.cryptor.PacketCryptor; import com.vecsight.dragonite.sdk.socket.DragoniteServer; import com.vecsight.dragonite.sdk.socket.DragoniteSocket; import org.pmw.tinylog.Logger; import java.net.InetSocketAddress; import java.net.SocketException;
/* * The Dragonite Project * ------------------------- * See the LICENSE file in the root directory for license information. */ package com.vecsight.dragonite.proxy.network.server; public class ProxyServer { private final InetSocketAddress bindAddress; private final int limitMbps; private final String welcomeMessage; private final boolean allowLoopback;
private final PacketCryptor packetCryptor;
2
hprose/hprose-j2me
cldc/1.0/src/hprose/client/HproseClient.java
[ "public interface HproseCallback {\r\n void handler(Object result, Object[] arguments);\r\n}\r", "public interface HproseInvoker {\r\n void invoke(String functionName, HproseCallback callback);\r\n void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, boolean byRef);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, boolean byRef);\r\n\r\n void invoke(String functionName, HproseCallback callback, Class returnType);\r\n void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, Class returnType);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, Class returnType, boolean byRef);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType, boolean byRef);\r\n\r\n void invoke(String functionName, HproseCallback callback, HproseResultMode resultMode);\r\n void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent, HproseResultMode resultMode);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseResultMode resultMode);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, HproseResultMode resultMode);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, boolean byRef, HproseResultMode resultMode);\r\n void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, boolean byRef, HproseResultMode resultMode);\r\n\r\n Object invoke(String functionName) throws IOException;\r\n Object invoke(String functionName, Object[] arguments) throws IOException;\r\n Object invoke(String functionName, Object[] arguments, boolean byRef) throws IOException;\r\n\r\n Object invoke(String functionName, Class returnType) throws IOException;\r\n Object invoke(String functionName, Object[] arguments, Class returnType) throws IOException;\r\n Object invoke(String functionName, Object[] arguments, Class returnType, boolean byRef) throws IOException;\r\n\r\n Object invoke(String functionName, HproseResultMode resultMode) throws IOException;\r\n Object invoke(String functionName, Object[] arguments, HproseResultMode resultMode) throws IOException;\r\n Object invoke(String functionName, Object[] arguments, boolean byRef, HproseResultMode resultMode) throws IOException;\r\n}", "public class HproseException extends IOException {\r\n\r\n private static final long serialVersionUID = -6146544906159301857L;\r\n\r\n public HproseException() {\r\n super();\r\n }\r\n\r\n public HproseException(String msg) {\r\n super(msg);\r\n }\r\n}\r", "public final class HproseResultMode {\r\n public static final HproseResultMode Normal = new HproseResultMode();\r\n public static final HproseResultMode Serialized = new HproseResultMode();\r\n public static final HproseResultMode Raw = new HproseResultMode();\r\n public static final HproseResultMode RawWithEndTag = new HproseResultMode();\r\n private HproseResultMode() {\r\n }\r\n}", "public interface HproseFilter {\r\n InputStream inputFilter(InputStream istream);\r\n OutputStream outputFilter(OutputStream ostream);\r\n}", "public final class HproseHelper {\r\n\r\n private static final Byte[] byteCache = new Byte[-(-128) + 127 + 1];\r\n private static final Character[] charCache = new Character[127 + 1];\r\n private static final Integer[] intCache = new Integer[-(-128) + 127 + 1];\r\n private static final Short[] shortCache = new Short[-(-128) + 127 + 1];\r\n private static final Long[] longCache = new Long[-(-128) + 127 + 1];\r\n private static final char[] base64EncodeChars = new char[] {\r\n 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\r\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\r\n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\r\n 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\r\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\r\n 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\r\n 'w', 'x', 'y', 'z', '0', '1', '2', '3',\r\n '4', '5', '6', '7', '8', '9', '+', '/' };\r\n private static final byte[] base64DecodeChars = new byte[] {\r\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\r\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\r\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,\r\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,\r\n -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\r\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,\r\n -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,\r\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 };\r\n\r\n static final TimeZone UTC = TimeZone.getTimeZone(\"UTC\");\r\n static final String DefaultTZID = TimeZone.getDefault().getID();\r\n public static final Object Null = new Object();\r\n public static final Boolean TRUE = new Boolean(true);\r\n public static final Boolean FALSE = new Boolean(false);\r\n public static final Class IntegerClass = new Integer(0).getClass();\r\n public static final Class ByteClass = new Byte((byte)0).getClass();\r\n public static final Class ShortClass = new Short((short)0).getClass();\r\n public static final Class LongClass = new Long((long)0).getClass();\r\n public static final Class CharClass = new Character((char)0).getClass();\r\n public static final Class BoolClass = TRUE.getClass();\r\n public static final Class StringClass = \"\".getClass();\r\n public static final Class StringBufferClass = new StringBuffer().getClass();\r\n public static final Class ObjectClass = Null.getClass();\r\n public static final Class DateClass = new Date().getClass();\r\n public static final Class CalendarClass = Calendar.getInstance().getClass();\r\n public static final Class BytesClass = new byte[0].getClass();\r\n public static final Class CharsClass = new char[0].getClass();\r\n public static final Class IntegerArrayClass = new int[0].getClass();\r\n public static final Class ShortArrayClass = new short[0].getClass();\r\n public static final Class LongArrayClass = new long[0].getClass();\r\n public static final Class BoolArrayClass = new boolean[0].getClass();\r\n public static final Class StringArrayClass = new String[0].getClass();\r\n public static final Class StringBufferArrayClass = new StringBuffer[0].getClass();\r\n public static final Class ObjectArrayClass = new Object[0].getClass();\r\n public static final Class DateArrayClass = new Date[0].getClass();\r\n public static final Class CalendarArrayClass = new Calendar[0].getClass();\r\n public static final Class BytesArrayClass = new byte[0][0].getClass();\r\n public static final Class CharsArrayClass = new char[0][0].getClass();\r\n public static final Class VectorClass = new Vector().getClass();\r\n public static final Class StackClass = new Stack().getClass();\r\n public static final Class HashtableClass = new Hashtable().getClass();\r\n public static final Class UUIDClass = new UUID(0, 0).getClass();\r\n public static final Class ClassClass = ObjectClass.getClass();\r\n public static final Class SerializableClass = new Serializable() {\r\n public String[] getPropertyNames() {\r\n return new String[0];\r\n }\r\n public Class getPropertyType(String name) {\r\n return this.getClass();\r\n }\r\n public Object getProperty(String name) {\r\n return Null;\r\n }\r\n public void setProperty(String name, Object value) {\r\n }\r\n }.getClass();\r\n\r\n private HproseHelper() {\r\n }\r\n\r\n static {\r\n for (int i = 0; i < byteCache.length; i++) {\r\n byteCache[i] = new Byte((byte) (i - 128));\r\n }\r\n for (int i = 0; i < charCache.length; i++) {\r\n charCache[i] = new Character((char) i);\r\n }\r\n for (int i = 0; i < intCache.length; i++) {\r\n intCache[i] = new Integer(i - 128);\r\n }\r\n for (int i = 0; i < shortCache.length; i++) {\r\n shortCache[i] = new Short((short) (i - 128));\r\n }\r\n for (int i = 0; i < longCache.length; i++) {\r\n longCache[i] = new Long(i - 128);\r\n }\r\n }\r\n\r\n public static Byte valueOf(byte b) {\r\n final int offset = 128;\r\n return byteCache[(int) b + offset];\r\n }\r\n\r\n public static Boolean valueOf(boolean b) {\r\n return (b ? TRUE : FALSE);\r\n }\r\n\r\n public static Character valueOf(char c) {\r\n if (c <= 127) {\r\n return charCache[(int) c];\r\n }\r\n return new Character(c);\r\n }\r\n\r\n public static Integer valueOf(int i) {\r\n final int offset = 128;\r\n if (i >= -128 && i <= 127) {\r\n return intCache[i + offset];\r\n }\r\n return new Integer(i);\r\n }\r\n\r\n public static Short valueOf(short s) {\r\n final int offset = 128;\r\n int sAsInt = s;\r\n if (sAsInt >= -128 && sAsInt <= 127) {\r\n return shortCache[sAsInt + offset];\r\n }\r\n return new Short(s);\r\n }\r\n\r\n public static Long valueOf(long l) {\r\n final int offset = 128;\r\n if (l >= -128 && l <= 127) {\r\n return longCache[(int) l + offset];\r\n }\r\n return new Long(l);\r\n }\r\n\r\n public static String[] split(String s, char c, int limit) {\r\n if (s == null) return null;\r\n Vector pos = new Vector();\r\n int i = -1;\r\n while ((i = s.indexOf((int) c, i + 1)) > 0) {\r\n pos.addElement(HproseHelper.valueOf(i));\r\n }\r\n int n = pos.size();\r\n int[] p = new int[n];\r\n for (i = 0; i < n; i++) {\r\n p[i] = ((Integer) pos.elementAt(i)).intValue();\r\n }\r\n if ((limit == 0) || (limit > n)) {\r\n limit = n + 1;\r\n }\r\n String[] result = new String[limit];\r\n if (n > 0) {\r\n result[0] = s.substring(0, p[0]);\r\n } else {\r\n result[0] = s;\r\n }\r\n for (i = 1; i < limit - 1; i++) {\r\n result[i] = s.substring(p[i - 1] + 1, p[i]);\r\n }\r\n if (limit > 1) {\r\n result[limit - 1] = s.substring(p[limit - 2] + 1);\r\n }\r\n return result;\r\n }\r\n\r\n public static String getClassName(Class type) {\r\n String className = ClassManager.getClassAlias(type);\r\n if (className == null) {\r\n className = type.getName().replace('.', '_').replace('$', '_');\r\n ClassManager.register(type, className);\r\n }\r\n return className;\r\n }\r\n\r\n private static Class getInnerClass(StringBuffer className, int[] pos, int i, char c) {\r\n if (i < pos.length) {\r\n int p = pos[i];\r\n className.setCharAt(p, c);\r\n Class type = getInnerClass(className, pos, i + 1, '_');\r\n if (i + 1 < pos.length && type == null) {\r\n type = getInnerClass(className, pos, i + 1, '$');\r\n }\r\n return type;\r\n }\r\n else {\r\n try {\r\n return Class.forName(className.toString());\r\n }\r\n catch (Exception e) {\r\n return null;\r\n }\r\n }\r\n }\r\n\r\n private static Class getClass(StringBuffer className, int[] pos, int i, char c) {\r\n if (i < pos.length) {\r\n int p = pos[i];\r\n className.setCharAt(p, c);\r\n Class type = getClass(className, pos, i + 1, '.');\r\n if (i + 1 < pos.length) {\r\n if (type == null) {\r\n type = getClass(className, pos, i + 1, '_');\r\n }\r\n if (type == null) {\r\n type = getInnerClass(className, pos, i + 1, '$');\r\n }\r\n }\r\n return type;\r\n }\r\n else {\r\n try {\r\n return Class.forName(className.toString());\r\n }\r\n catch (Exception e) {\r\n return null;\r\n }\r\n }\r\n }\r\n\r\n public static Class getClass(String className) {\r\n if (ClassManager.containsClass(className)) {\r\n return ClassManager.getClass(className);\r\n }\r\n StringBuffer cn = new StringBuffer(className);\r\n Vector al = new Vector();\r\n int p = className.indexOf(\"_\");\r\n while (p > -1) {\r\n al.addElement(HproseHelper.valueOf(p));\r\n p = className.indexOf(\"_\", p + 1);\r\n }\r\n Class type = null;\r\n if (al.size() > 0) {\r\n try {\r\n int size = al.size();\r\n int[] pos = new int[size];\r\n\r\n for (int i = 0; i < size; i++) {\r\n pos[i] = ((Integer) al.elementAt(i)).intValue();\r\n }\r\n type = getClass(cn, pos, 0, '.');\r\n if (type == null) {\r\n type = getClass(cn, pos, 0, '_');\r\n }\r\n if (type == null) {\r\n type = getInnerClass(cn, pos, 0, '$');\r\n }\r\n }\r\n catch (Exception e) {\r\n }\r\n }\r\n else {\r\n try {\r\n type = Class.forName(className);\r\n }\r\n catch (Exception e) {\r\n }\r\n }\r\n ClassManager.register(type, className);\r\n return type;\r\n }\r\n\r\n public static Serializable newInstance(Class type) {\r\n try {\r\n return (Serializable)type.newInstance();\r\n }\r\n catch (Exception e) {}\r\n return null;\r\n }\r\n\r\n public static String base64Encode(byte[] data) {\r\n StringBuffer sb = new StringBuffer();\r\n int r = data.length % 3;\r\n int len = data.length - r;\r\n int i = 0;\r\n int c;\r\n while (i < len) {\r\n c = (0x000000ff & data[i++]) << 16 |\r\n (0x000000ff & data[i++]) << 8 |\r\n (0x000000ff & data[i++]);\r\n sb.append(base64EncodeChars[c >> 18]);\r\n sb.append(base64EncodeChars[c >> 12 & 0x3f]);\r\n sb.append(base64EncodeChars[c >> 6 & 0x3f]);\r\n sb.append(base64EncodeChars[c & 0x3f]);\r\n }\r\n if (r == 1) {\r\n c = 0x000000ff & data[i++];\r\n sb.append(base64EncodeChars[c >> 2]);\r\n sb.append(base64EncodeChars[(c & 0x03) << 4]);\r\n sb.append(\"==\");\r\n }\r\n else if (r == 2) {\r\n c = (0x000000ff & data[i++]) << 8 |\r\n (0x000000ff & data[i++]);\r\n sb.append(base64EncodeChars[c >> 10]);\r\n sb.append(base64EncodeChars[c >> 4 & 0x3f]);\r\n sb.append(base64EncodeChars[(c & 0x0f) << 2]);\r\n sb.append(\"=\");\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public static byte[] base64Decode(String str) {\r\n byte[] data = str.getBytes();\r\n int len = data.length;\r\n ByteArrayOutputStream buf = new ByteArrayOutputStream(len);\r\n int i = 0;\r\n int b1, b2, b3, b4;\r\n\r\n while (i < len) {\r\n\r\n /* b1 */\r\n do {\r\n b1 = base64DecodeChars[data[i++]];\r\n } while (i < len && b1 == -1);\r\n if (b1 == -1) {\r\n break;\r\n }\r\n\r\n /* b2 */\r\n do {\r\n b2 = base64DecodeChars[data[i++]];\r\n } while (i < len && b2 == -1);\r\n if (b2 == -1) {\r\n break;\r\n }\r\n buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));\r\n\r\n /* b3 */\r\n do {\r\n b3 = data[i++];\r\n if (b3 == 61) {\r\n return buf.toByteArray();\r\n }\r\n b3 = base64DecodeChars[b3];\r\n } while (i < len && b3 == -1);\r\n if (b3 == -1) {\r\n break;\r\n }\r\n buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));\r\n\r\n /* b4 */\r\n do {\r\n b4 = data[i++];\r\n if (b4 == 61) {\r\n return buf.toByteArray();\r\n }\r\n b4 = base64DecodeChars[b4];\r\n } while (i < len && b4 == -1);\r\n if (b4 == -1) {\r\n break;\r\n }\r\n buf.write((int) (((b3 & 0x03) << 6) | b4));\r\n }\r\n return buf.toByteArray();\r\n }\r\n\r\n public static String createGUID() {\r\n return UUID.randomUUID().toString();\r\n }\r\n}", "public final class HproseWriter {\r\n private static final HashMap propertiesCache = new HashMap();\r\n public final OutputStream stream;\r\n private final ObjectIntMap ref = new ObjectIntMap();\r\n private final ObjectIntMap classref = new ObjectIntMap();\r\n private final byte[] buf = new byte[20];\r\n private static final byte[] minIntBuf = new byte[] {'-','2','1','4','7','4','8','3','6','4','8'};\r\n private static final byte[] minLongBuf = new byte[] {'-','9','2','2','3','3','7','2','0','3','6','8','5','4','7','7','5','8','0','8'};\r\n private int lastref = 0;\r\n private int lastclassref = 0;\r\n\r\n public HproseWriter(OutputStream stream) {\r\n this.stream = stream;\r\n }\r\n\r\n public void serialize(Object obj) throws IOException {\r\n if (obj == null) {\r\n writeNull();\r\n }\r\n else if (obj instanceof Integer) {\r\n writeInteger(((Integer) obj).intValue());\r\n }\r\n else if (obj instanceof Byte) {\r\n writeInteger(((Byte) obj).byteValue());\r\n }\r\n else if (obj instanceof Short) {\r\n writeInteger(((Short) obj).shortValue());\r\n }\r\n else if (obj instanceof Character) {\r\n writeUTF8Char(((Character) obj).charValue());\r\n }\r\n else if (obj instanceof Long) {\r\n writeLong(((Long) obj).longValue());\r\n }\r\n else if (obj instanceof BigInteger) {\r\n writeLong((BigInteger) obj);\r\n }\r\n else if (obj instanceof Double) {\r\n writeDouble(((Double) obj).doubleValue());\r\n }\r\n else if (obj instanceof Float) {\r\n writeDouble(((Float) obj).doubleValue());\r\n }\r\n else if (obj instanceof Boolean) {\r\n writeBoolean(((Boolean) obj).booleanValue());\r\n }\r\n else if (obj instanceof Date) {\r\n writeDate((Date) obj, true);\r\n }\r\n else if (obj instanceof Calendar) {\r\n writeDate((Calendar) obj, true);\r\n }\r\n else if (obj instanceof BigDecimal) {\r\n writeString(obj.toString(), true);\r\n }\r\n else if (obj instanceof String ||\r\n obj instanceof StringBuffer) {\r\n String s = obj.toString();\r\n switch (s.length()) {\r\n case 0: writeEmpty(); break;\r\n case 1: writeUTF8Char(s.charAt(0)); break;\r\n default: writeString(s, true); break;\r\n }\r\n }\r\n else if (obj instanceof UUID) {\r\n writeUUID((UUID)obj, true);\r\n }\r\n else if (obj instanceof char[]) {\r\n char[] cs = (char[]) obj;\r\n switch (cs.length) {\r\n case 0: writeEmpty(); break;\r\n case 1: writeUTF8Char(cs[0]); break;\r\n default: writeString(cs, true); break;\r\n }\r\n }\r\n else if (obj instanceof byte[]) {\r\n writeBytes((byte[]) obj, true);\r\n }\r\n else if (obj instanceof short[]) {\r\n writeArray((short[]) obj, true);\r\n }\r\n else if (obj instanceof int[]) {\r\n writeArray((int[]) obj, true);\r\n }\r\n else if (obj instanceof long[]) {\r\n writeArray((long[]) obj, true);\r\n }\r\n else if (obj instanceof float[]) {\r\n writeArray((float[]) obj, true);\r\n }\r\n else if (obj instanceof double[]) {\r\n writeArray((double[]) obj, true);\r\n }\r\n else if (obj instanceof boolean[]) {\r\n writeArray((boolean[]) obj, true);\r\n }\r\n else if (obj instanceof String[]) {\r\n writeArray((String[]) obj, true);\r\n }\r\n else if (obj instanceof StringBuffer[]) {\r\n writeArray((StringBuffer[]) obj, true);\r\n }\r\n else if (obj instanceof char[][]) {\r\n writeArray((char[][]) obj, true);\r\n }\r\n else if (obj instanceof byte[][]) {\r\n writeArray((byte[][]) obj, true);\r\n }\r\n else if (obj instanceof BigInteger[]) {\r\n writeArray((BigInteger[]) obj, true);\r\n }\r\n else if (obj instanceof BigDecimal[]) {\r\n writeArray((BigDecimal[]) obj, true);\r\n }\r\n else if (obj instanceof Object[]) {\r\n writeArray((Object[]) obj, true);\r\n }\r\n else if (obj instanceof Vector) {\r\n writeList((Vector) obj, true);\r\n }\r\n else if (obj instanceof ArrayList) {\r\n writeList((ArrayList) obj, true);\r\n }\r\n else if (obj instanceof Collection) {\r\n writeCollection((Collection) obj, true);\r\n }\r\n else if (obj instanceof Hashtable) {\r\n writeMap((Hashtable) obj, true);\r\n }\r\n else if (obj instanceof Map) {\r\n writeMap((Map) obj, true);\r\n }\r\n else if (obj instanceof Serializable) {\r\n writeObject((Serializable)obj, true);\r\n }\r\n else {\r\n throw new HproseException(obj.getClass().getName() + \" is not a serializable type\");\r\n }\r\n }\r\n\r\n public void writeInteger(int i) throws IOException {\r\n if (i >= 0 && i <= 9) {\r\n stream.write(i + '0');\r\n }\r\n else {\r\n stream.write(HproseTags.TagInteger);\r\n writeInt(i);\r\n stream.write(HproseTags.TagSemicolon);\r\n }\r\n }\r\n\r\n public void writeLong(long l) throws IOException {\r\n if (l >= 0 && l <= 9) {\r\n stream.write((int)l + '0');\r\n }\r\n else {\r\n stream.write(HproseTags.TagLong);\r\n writeInt(l);\r\n stream.write(HproseTags.TagSemicolon);\r\n }\r\n }\r\n\r\n public void writeLong(BigInteger l) throws IOException {\r\n if (l.equals(BigInteger.ZERO)) {\r\n stream.write('0');\r\n }\r\n else if (l.equals(BigInteger.ONE)) {\r\n stream.write('1');\r\n }\r\n else {\r\n stream.write(HproseTags.TagLong);\r\n stream.write(getAscii(l.toString()));\r\n stream.write(HproseTags.TagSemicolon);\r\n }\r\n }\r\n\r\n public void writeDouble(double d) throws IOException {\r\n if (Double.isNaN(d)) {\r\n stream.write(HproseTags.TagNaN);\r\n }\r\n else if (Double.isInfinite(d)) {\r\n stream.write(HproseTags.TagInfinity);\r\n stream.write(d > 0 ? HproseTags.TagPos : HproseTags.TagNeg);\r\n }\r\n else {\r\n stream.write(HproseTags.TagDouble);\r\n stream.write(getAscii(Double.toString(d)));\r\n stream.write(HproseTags.TagSemicolon);\r\n }\r\n }\r\n\r\n public void writeNaN() throws IOException {\r\n stream.write(HproseTags.TagNaN);\r\n }\r\n\r\n public void writeInfinity(boolean positive) throws IOException {\r\n stream.write(HproseTags.TagInfinity);\r\n stream.write(positive ? HproseTags.TagPos : HproseTags.TagNeg);\r\n }\r\n\r\n public void writeNull() throws IOException {\r\n stream.write(HproseTags.TagNull);\r\n }\r\n\r\n public void writeEmpty() throws IOException {\r\n stream.write(HproseTags.TagEmpty);\r\n }\r\n\r\n public void writeBoolean(boolean b) throws IOException {\r\n stream.write(b ? HproseTags.TagTrue : HproseTags.TagFalse);\r\n }\r\n\r\n public void writeDate(Date date) throws IOException {\r\n writeDate(date, true);\r\n }\r\n\r\n public void writeDate(Date date, boolean checkRef) throws IOException {\r\n if (writeRef(date, checkRef)) {\r\n Calendar calendar = Calendar.getInstance(TimeZone.getDefault());\r\n calendar.setTime(date);\r\n writeDateOfCalendar(calendar);\r\n writeTimeOfCalendar(calendar);\r\n stream.write(HproseTags.TagSemicolon);\r\n }\r\n }\r\n\r\n public void writeDate(Calendar calendar) throws IOException {\r\n writeDate(calendar, true);\r\n }\r\n\r\n public void writeDate(Calendar calendar, boolean checkRef) throws IOException {\r\n if (writeRef(calendar, checkRef)) {\r\n String tzID = calendar.getTimeZone().getID();\r\n if (!(tzID.equals(HproseHelper.DefaultTZID) || tzID.equals(\"UTC\"))) {\r\n TimeZone tz = HproseHelper.UTC;\r\n Calendar c = Calendar.getInstance(calendar.getTimeZone());\r\n c.setTime(calendar.getTime());\r\n c.setTimeZone(tz);\r\n calendar = c;\r\n }\r\n writeDateOfCalendar(calendar);\r\n writeTimeOfCalendar(calendar);\r\n stream.write(tzID.equals(\"UTC\") ? HproseTags.TagUTC : HproseTags.TagSemicolon);\r\n }\r\n }\r\n\r\n private void writeDateOfCalendar(Calendar calendar) throws IOException {\r\n int year = calendar.get(Calendar.YEAR);\r\n int month = calendar.get(Calendar.MONTH) + 1;\r\n int day = calendar.get(Calendar.DATE);\r\n stream.write(HproseTags.TagDate);\r\n stream.write((byte) ('0' + (year / 1000 % 10)));\r\n stream.write((byte) ('0' + (year / 100 % 10)));\r\n stream.write((byte) ('0' + (year / 10 % 10)));\r\n stream.write((byte) ('0' + (year % 10)));\r\n stream.write((byte) ('0' + (month / 10 % 10)));\r\n stream.write((byte) ('0' + (month % 10)));\r\n stream.write((byte) ('0' + (day / 10 % 10)));\r\n stream.write((byte) ('0' + (day % 10)));\r\n }\r\n\r\n private void writeTimeOfCalendar(Calendar calendar) throws IOException {\r\n int hour = calendar.get(Calendar.HOUR_OF_DAY);\r\n int minute = calendar.get(Calendar.MINUTE);\r\n int second = calendar.get(Calendar.SECOND);\r\n int millisecond = calendar.get(Calendar.MILLISECOND);\r\n if (hour == 0 && minute == 0 && second == 0 && millisecond == 0) return;\r\n stream.write(HproseTags.TagTime);\r\n stream.write((byte) ('0' + (hour / 10 % 10)));\r\n stream.write((byte) ('0' + (hour % 10)));\r\n stream.write((byte) ('0' + (minute / 10 % 10)));\r\n stream.write((byte) ('0' + (minute % 10)));\r\n stream.write((byte) ('0' + (second / 10 % 10)));\r\n stream.write((byte) ('0' + (second % 10)));\r\n if (millisecond > 0) {\r\n stream.write(HproseTags.TagPoint);\r\n stream.write((byte) ('0' + (millisecond / 100 % 10)));\r\n stream.write((byte) ('0' + (millisecond / 10 % 10)));\r\n stream.write((byte) ('0' + (millisecond % 10)));\r\n }\r\n }\r\n\r\n public void writeBytes(byte[] bytes) throws IOException {\r\n writeBytes(bytes, true);\r\n }\r\n\r\n public void writeBytes(byte[] bytes, boolean checkRef) throws IOException {\r\n if (writeRef(bytes, checkRef)) {\r\n stream.write(HproseTags.TagBytes);\r\n if (bytes.length > 0) writeInt(bytes.length);\r\n stream.write(HproseTags.TagQuote);\r\n stream.write(bytes);\r\n stream.write(HproseTags.TagQuote);\r\n }\r\n }\r\n\r\n public void writeUTF8Char(int c) throws IOException {\r\n stream.write(HproseTags.TagUTF8Char);\r\n if (c < 0x80) {\r\n stream.write(c);\r\n }\r\n else if (c < 0x800) {\r\n stream.write(0xc0 | (c >>> 6));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n else {\r\n stream.write(0xe0 | (c >>> 12));\r\n stream.write(0x80 | ((c >>> 6) & 0x3f));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n }\r\n\r\n public void writeString(String s) throws IOException {\r\n writeString(s, true);\r\n }\r\n\r\n public void writeString(String s, boolean checkRef) throws IOException {\r\n if (writeRef(s, checkRef)) {\r\n stream.write(HproseTags.TagString);\r\n writeUTF8String(s, stream);\r\n }\r\n }\r\n\r\n private void writeUTF8String(String s, OutputStream stream) throws IOException {\r\n int length = s.length();\r\n if (length > 0) writeInt(length, stream);\r\n stream.write(HproseTags.TagQuote);\r\n for (int i = 0; i < length; i++) {\r\n int c = 0xffff & s.charAt(i);\r\n if (c < 0x80) {\r\n stream.write(c);\r\n }\r\n else if (c < 0x800) {\r\n stream.write(0xc0 | (c >>> 6));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n else if (c < 0xd800 || c > 0xdfff) {\r\n stream.write(0xe0 | (c >>> 12));\r\n stream.write(0x80 | ((c >>> 6) & 0x3f));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n else {\r\n if (++i < length) {\r\n int c2 = 0xffff & s.charAt(i);\r\n if (c < 0xdc00 && 0xdc00 <= c2 && c2 <= 0xdfff) {\r\n c = ((c & 0x03ff) << 10 | (c2 & 0x03ff)) + 0x010000;\r\n stream.write(0xf0 | (c >>> 18));\r\n stream.write(0x80 | ((c >>> 12) & 0x3f));\r\n stream.write(0x80 | ((c >>> 6) & 0x3f));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n else {\r\n throw new HproseException(\"wrong unicode string\");\r\n }\r\n }\r\n else {\r\n throw new HproseException(\"wrong unicode string\");\r\n }\r\n }\r\n }\r\n stream.write(HproseTags.TagQuote);\r\n }\r\n\r\n public void writeString(char[] s) throws IOException {\r\n writeString(s, true);\r\n }\r\n\r\n public void writeString(char[] s, boolean checkRef) throws IOException {\r\n if (writeRef(s, checkRef)) {\r\n stream.write(HproseTags.TagString);\r\n writeUTF8String(s);\r\n }\r\n }\r\n\r\n private void writeUTF8String(char[] s) throws IOException {\r\n int length = s.length;\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagQuote);\r\n for (int i = 0; i < length; i++) {\r\n int c = 0xffff & s[i];\r\n if (c < 0x80) {\r\n stream.write(c);\r\n }\r\n else if (c < 0x800) {\r\n stream.write(0xc0 | (c >>> 6));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n else if (c < 0xd800 || c > 0xdfff) {\r\n stream.write(0xe0 | (c >>> 12));\r\n stream.write(0x80 | ((c >>> 6) & 0x3f));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n else {\r\n if (++i < length) {\r\n int c2 = 0xffff & s[i];\r\n if (c < 0xdc00 && 0xdc00 <= c2 && c2 <= 0xdfff) {\r\n c = ((c & 0x03ff) << 10 | (c2 & 0x03ff)) + 0x010000;\r\n stream.write(0xf0 | ((c >>> 18) & 0x3f));\r\n stream.write(0x80 | ((c >>> 12) & 0x3f));\r\n stream.write(0x80 | ((c >>> 6) & 0x3f));\r\n stream.write(0x80 | (c & 0x3f));\r\n }\r\n else {\r\n throw new HproseException(\"wrong unicode string\");\r\n }\r\n }\r\n else {\r\n throw new HproseException(\"wrong unicode string\");\r\n }\r\n }\r\n }\r\n stream.write(HproseTags.TagQuote);\r\n }\r\n\r\n public void writeUUID(UUID uuid) throws IOException {\r\n writeUUID(uuid, true);\r\n }\r\n\r\n public void writeUUID(UUID uuid, boolean checkRef) throws IOException {\r\n if (writeRef(uuid, checkRef)) {\r\n stream.write(HproseTags.TagGuid);\r\n stream.write(HproseTags.TagOpenbrace);\r\n stream.write(getAscii(uuid.toString()));\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(short[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(short[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeInteger(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(int[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(int[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeInteger(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(long[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(long[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeLong(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(float[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(float[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeDouble(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(double[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(double[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeDouble(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(boolean[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(boolean[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeBoolean(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(String[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(String[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeString(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(StringBuffer[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(StringBuffer[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeString(array[i].toString());\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(char[][] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(char[][] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeString(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(byte[][] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(byte[][] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeBytes(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(BigInteger[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(BigInteger[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeLong(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(BigDecimal[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(BigDecimal[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n writeString(array[i].toString());\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeArray(Object[] array) throws IOException {\r\n writeArray(array, true);\r\n }\r\n\r\n public void writeArray(Object[] array, boolean checkRef) throws IOException {\r\n if (writeRef(array, checkRef)) {\r\n int length = array.length;\r\n stream.write(HproseTags.TagList);\r\n if (length > 0) writeInt(length);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < length; i++) {\r\n serialize(array[i]);\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeCollection(Collection collection) throws IOException {\r\n writeCollection(collection, true);\r\n }\r\n\r\n public void writeCollection(Collection collection, boolean checkRef) throws IOException {\r\n if (writeRef(collection, checkRef)) {\r\n int count = collection.size();\r\n stream.write(HproseTags.TagList);\r\n if (count > 0) writeInt(count);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (Iterator iter = collection.iterator(); iter.hasNext();) {\r\n serialize(iter.next());\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeList(Vector list) throws IOException {\r\n writeList(list, true);\r\n }\r\n\r\n public void writeList(Vector list, boolean checkRef) throws IOException {\r\n if (writeRef(list, checkRef)) {\r\n int count = list.size();\r\n stream.write(HproseTags.TagList);\r\n if (count > 0) writeInt(count);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < count; i++) {\r\n serialize(list.elementAt(i));\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeList(List list) throws IOException {\r\n writeList(list, true);\r\n }\r\n\r\n public void writeList(List list, boolean checkRef) throws IOException {\r\n if (writeRef(list, checkRef)) {\r\n int count = list.size();\r\n stream.write(HproseTags.TagList);\r\n if (count > 0) writeInt(count);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < count; i++) {\r\n serialize(list.get(i));\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeMap(Hashtable map) throws IOException {\r\n writeMap(map, true);\r\n }\r\n\r\n public void writeMap(Hashtable map, boolean checkRef) throws IOException {\r\n if (writeRef(map, checkRef)) {\r\n int count = map.size();\r\n stream.write(HproseTags.TagMap);\r\n if (count > 0) writeInt(count);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (Enumeration e = map.keys(); e.hasMoreElements();) {\r\n Object key = (Object) e.nextElement();\r\n serialize(key);\r\n serialize(map.get(key));\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeMap(Map map) throws IOException {\r\n writeMap(map, true);\r\n }\r\n\r\n public void writeMap(Map map, boolean checkRef) throws IOException {\r\n if (writeRef(map, checkRef)) {\r\n int count = map.size();\r\n stream.write(HproseTags.TagMap);\r\n if (count > 0) writeInt(count);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (Iterator entrys = map.entrySet().iterator(); entrys.hasNext();) {\r\n Entry entry = (Entry) entrys.next();\r\n serialize(entry.getKey());\r\n serialize(entry.getValue());\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n public void writeObject(Serializable object) throws IOException {\r\n writeObject(object, true);\r\n }\r\n\r\n public void writeObject(Serializable object, boolean checkRef) throws IOException {\r\n if (checkRef && ref.containsKey(object)) {\r\n writeRef(object);\r\n }\r\n else {\r\n Class type = object.getClass();\r\n int cr;\r\n if (classref.containsKey(type)) {\r\n cr = classref.get(type);\r\n }\r\n else {\r\n cr = writeClass(object);\r\n }\r\n ref.put(object, lastref++);\r\n String[] names = object.getPropertyNames();\r\n stream.write(HproseTags.TagObject);\r\n writeInt(cr);\r\n stream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < names.length; i++) {\r\n serialize(object.getProperty(names[i]));\r\n }\r\n stream.write(HproseTags.TagClosebrace);\r\n }\r\n }\r\n\r\n private int writeClass(Serializable object) throws IOException {\r\n Class type = object.getClass();\r\n SerializeCache cache = null;\r\n synchronized (propertiesCache) {\r\n if (propertiesCache.containsKey(type)) {\r\n cache = (SerializeCache) propertiesCache.get(type);\r\n }\r\n }\r\n if (cache == null) {\r\n cache = new SerializeCache();\r\n ByteArrayOutputStream cachestream = new ByteArrayOutputStream();\r\n String[] names = object.getPropertyNames();\r\n int count = names.length;\r\n cachestream.write(HproseTags.TagClass);\r\n writeUTF8String(HproseHelper.getClassName(type), cachestream);\r\n if (count > 0) writeInt(count, cachestream);\r\n cachestream.write(HproseTags.TagOpenbrace);\r\n for (int i = 0; i < count; i++) {\r\n cachestream.write(HproseTags.TagString);\r\n writeUTF8String(names[i], cachestream);\r\n cache.refcount++;\r\n }\r\n cachestream.write(HproseTags.TagClosebrace);\r\n cache.data = cachestream.toByteArray();\r\n synchronized (propertiesCache) {\r\n propertiesCache.put(type, cache);\r\n }\r\n }\r\n stream.write(cache.data);\r\n lastref += cache.refcount;\r\n int cr = lastclassref++;\r\n classref.put(type, cr);\r\n return cr;\r\n }\r\n\r\n private boolean writeRef(Object obj, boolean checkRef) throws IOException {\r\n if (checkRef && ref.containsKey(obj)) {\r\n stream.write(HproseTags.TagRef);\r\n writeInt(ref.get(obj));\r\n stream.write(HproseTags.TagSemicolon);\r\n return false;\r\n }\r\n else {\r\n ref.put(obj, lastref++);\r\n return true;\r\n }\r\n }\r\n\r\n private void writeRef(Object obj) throws IOException {\r\n stream.write(HproseTags.TagRef);\r\n writeInt(ref.get(obj));\r\n stream.write(HproseTags.TagSemicolon);\r\n }\r\n\r\n private byte[] getAscii(String s) {\r\n int size = s.length();\r\n byte[] b = new byte[size--];\r\n for (; size >= 0; size--) {\r\n b[size] = (byte) s.charAt(size);\r\n }\r\n return b;\r\n }\r\n\r\n private void writeInt(int i) throws IOException {\r\n writeInt(i, stream);\r\n }\r\n\r\n private void writeInt(int i, OutputStream stream) throws IOException {\r\n if ((i >= 0) && (i <= 9)) {\r\n stream.write((byte)('0' + i));\r\n }\r\n else if (i == Integer.MIN_VALUE) {\r\n stream.write(minIntBuf);\r\n }\r\n else {\r\n int off = 20;\r\n int len = 0;\r\n boolean neg = false;\r\n if (i < 0) {\r\n neg = true;\r\n i = -i;\r\n }\r\n while (i != 0) {\r\n buf[--off] = (byte) (i % 10 + '0');\r\n ++len;\r\n i /= 10;\r\n }\r\n if (neg) {\r\n buf[--off] = '-';\r\n ++len;\r\n }\r\n stream.write(buf, off, len);\r\n }\r\n }\r\n\r\n private void writeInt(long i) throws IOException {\r\n if ((i >= 0) && (i <= 9)) {\r\n stream.write((byte)('0' + i));\r\n }\r\n else if (i == Long.MIN_VALUE) {\r\n stream.write(minLongBuf);\r\n }\r\n else {\r\n int off = 20;\r\n int len = 0;\r\n boolean neg = false;\r\n if (i < 0) {\r\n neg = true;\r\n i = -i;\r\n }\r\n while (i != 0) {\r\n buf[--off] = (byte) (i % 10 + '0');\r\n ++len;\r\n i /= 10;\r\n }\r\n if (neg) {\r\n buf[--off] = '-';\r\n ++len;\r\n }\r\n stream.write(buf, off, len);\r\n }\r\n }\r\n\r\n public void reset() {\r\n ref.clear();\r\n classref.clear();\r\n lastref = 0;\r\n lastclassref = 0;\r\n }\r\n\r\n class SerializeCache {\r\n byte[] data;\r\n int refcount;\r\n }\r\n}", "public final class HproseReader {\r\n\r\n public final InputStream stream;\r\n private final List ref = new ArrayList();\r\n private final List classref = new ArrayList();\r\n private final HashMap propertyref = new HashMap();\r\n\r\n public HproseReader(InputStream stream) {\r\n this.stream = stream;\r\n }\r\n\r\n public Object unserialize() throws IOException {\r\n return unserialize(stream.read(), null);\r\n }\r\n\r\n public Object unserialize(Class type) throws IOException {\r\n return unserialize(stream.read(), type);\r\n }\r\n\r\n private Object unserialize(int tag, Class type) throws IOException {\r\n switch (tag) {\r\n case '0':\r\n case '1':\r\n case '2':\r\n case '3':\r\n case '4':\r\n case '5':\r\n case '6':\r\n case '7':\r\n case '8':\r\n case '9':\r\n return readDigit(tag, type);\r\n case HproseTags.TagInteger:\r\n return readInteger(type);\r\n case HproseTags.TagLong:\r\n return readLong(type);\r\n case HproseTags.TagDouble:\r\n return readDouble(type);\r\n case HproseTags.TagNull:\r\n return null;\r\n case HproseTags.TagEmpty:\r\n return readEmpty(type);\r\n case HproseTags.TagTrue:\r\n return readTrue(type);\r\n case HproseTags.TagFalse:\r\n return readFalse(type);\r\n case HproseTags.TagNaN:\r\n return readNaN(type);\r\n case HproseTags.TagInfinity:\r\n return readInfinity(type);\r\n case HproseTags.TagDate:\r\n return readDate(false, type);\r\n case HproseTags.TagTime:\r\n return readTime(false, type);\r\n case HproseTags.TagBytes:\r\n return readBytes(type);\r\n case HproseTags.TagUTF8Char:\r\n return readUTF8Char(type);\r\n case HproseTags.TagString:\r\n return readString(false, type);\r\n case HproseTags.TagGuid:\r\n return readUUID(false, type);\r\n case HproseTags.TagList:\r\n return readList(false, type);\r\n case HproseTags.TagMap:\r\n return readMap(false, type);\r\n case HproseTags.TagClass:\r\n readClass();\r\n return unserialize(stream.read(), type);\r\n case HproseTags.TagObject:\r\n return readObject(false, type);\r\n case HproseTags.TagRef:\r\n return readRef(type);\r\n case HproseTags.TagError:\r\n throw new HproseException((String)readString());\r\n case -1:\r\n throw new HproseException(\"No byte found in stream\");\r\n }\r\n throw new HproseException(\"Unexpected serialize tag '\" +\r\n (char) tag + \"' in stream\");\r\n }\r\n\r\n private Object readDigit(int tag, Class type) throws IOException {\r\n if ((type == null) ||\r\n Integer.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return HproseHelper.valueOf((int)(tag - '0'));\r\n }\r\n if (Byte.class.equals(type)) {\r\n return HproseHelper.valueOf((byte)(tag - '0'));\r\n }\r\n if (Long.class.equals(type)) {\r\n return HproseHelper.valueOf((long)(tag - '0'));\r\n }\r\n if (Short.class.equals(type)) {\r\n return HproseHelper.valueOf((short)(tag - '0'));\r\n }\r\n if (Float.class.equals(type)) {\r\n return HproseHelper.valueOf((float)(tag - '0'));\r\n }\r\n if (Double.class.equals(type)) {\r\n return HproseHelper.valueOf((double)(tag - '0'));\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return BigInteger.valueOf((long)(tag - '0'));\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return BigDecimal.valueOf((long)(tag - '0'));\r\n }\r\n if (String.class.equals(type)) {\r\n return String.valueOf((char)tag);\r\n }\r\n if (Character.class.equals(type)) {\r\n return HproseHelper.valueOf((char)tag);\r\n }\r\n if (Boolean.class.equals(type)) {\r\n return HproseHelper.valueOf(tag != '0');\r\n }\r\n if (Calendar.class.equals(type)) {\r\n Calendar calendar = Calendar.getInstance(TimeZone.getDefault());\r\n calendar.setTime(new Date((long)(tag - '0')));\r\n return calendar;\r\n }\r\n if (Date.class.equals(type)) {\r\n return new Date((long)(tag - '0'));\r\n }\r\n return castError(\"Integer\", type);\r\n }\r\n\r\n private Object readInteger(Class type) throws IOException {\r\n if ((type == null) ||\r\n Integer.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return new Integer(readInt(HproseTags.TagSemicolon));\r\n }\r\n if (Byte.class.equals(type)) {\r\n return new Byte(readByte(HproseTags.TagSemicolon));\r\n }\r\n if (Long.class.equals(type)) {\r\n return new Long(readLong(HproseTags.TagSemicolon));\r\n }\r\n if (Short.class.equals(type)) {\r\n return new Short(readShort(HproseTags.TagSemicolon));\r\n }\r\n if (Float.class.equals(type)) {\r\n return Float.valueOf(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (Double.class.equals(type)) {\r\n return Double.valueOf(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return new BigInteger(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return new BigDecimal(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (String.class.equals(type)) {\r\n return readUntil(HproseTags.TagSemicolon);\r\n }\r\n if (Character.class.equals(type)) {\r\n return HproseHelper.valueOf((char) readInteger(false));\r\n }\r\n if (Boolean.class.equals(type)) {\r\n return HproseHelper.valueOf(readInteger(false) != 0);\r\n }\r\n if (Calendar.class.equals(type)) {\r\n Calendar calendar = Calendar.getInstance(TimeZone.getDefault());\r\n calendar.setTime(new Date(readLong(false)));\r\n return calendar;\r\n }\r\n if (Date.class.equals(type)) {\r\n return new Date(readLong(false));\r\n }\r\n return castError(\"Integer\", type);\r\n }\r\n\r\n private Object readLong(Class type) throws IOException {\r\n if ((type == null) ||\r\n BigInteger.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return new BigInteger(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (Long.class.equals(type)) {\r\n return new Long(readLong(HproseTags.TagSemicolon));\r\n }\r\n if (Integer.class.equals(type)) {\r\n return new Integer(readInt(HproseTags.TagSemicolon));\r\n }\r\n if (Float.class.equals(type)) {\r\n return Float.valueOf(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (Double.class.equals(type)) {\r\n return Double.valueOf(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return new BigDecimal(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (Byte.class.equals(type)) {\r\n return new Byte(readByte(HproseTags.TagSemicolon));\r\n }\r\n if (Short.class.equals(type)) {\r\n return new Short(readShort(HproseTags.TagSemicolon));\r\n }\r\n if (String.class.equals(type)) {\r\n return readUntil(HproseTags.TagSemicolon);\r\n }\r\n if (Boolean.class.equals(type)) {\r\n return HproseHelper.valueOf(readLong(false) != 0);\r\n }\r\n if (Character.class.equals(type)) {\r\n return HproseHelper.valueOf((char) readLong(false));\r\n }\r\n if (Calendar.class.equals(type)) {\r\n Calendar calendar = Calendar.getInstance(TimeZone.getDefault());\r\n calendar.setTime(new Date(readLong(false)));\r\n return calendar;\r\n }\r\n if (Date.class.equals(type)) {\r\n return new Date(readLong(false));\r\n }\r\n return castError(\"Long\", type);\r\n }\r\n\r\n private Object readDouble(Class type) throws IOException {\r\n if ((type == null) ||\r\n Double.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return Double.valueOf(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (Float.class.equals(type)) {\r\n return Float.valueOf(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return new BigDecimal(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (String.class.equals(type)) {\r\n return readUntil(HproseTags.TagSemicolon);\r\n }\r\n if (Integer.class.equals(type)) {\r\n return HproseHelper.valueOf(Double.valueOf(readUntil(HproseTags.TagSemicolon)).intValue());\r\n }\r\n if (Long.class.equals(type)) {\r\n return HproseHelper.valueOf(Double.valueOf(readUntil(HproseTags.TagSemicolon)).longValue());\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return new BigInteger(readUntil(HproseTags.TagSemicolon));\r\n }\r\n if (Byte.class.equals(type)) {\r\n return HproseHelper.valueOf(Double.valueOf(readUntil(HproseTags.TagSemicolon)).byteValue());\r\n }\r\n if (Short.class.equals(type)) {\r\n return HproseHelper.valueOf(Double.valueOf(readUntil(HproseTags.TagSemicolon)).shortValue());\r\n }\r\n if (Boolean.class.equals(type)) {\r\n return HproseHelper.valueOf(readDouble(false) != 0.0);\r\n }\r\n if (Character.class.equals(type)) {\r\n return HproseHelper.valueOf((char) Double.valueOf(readUntil(HproseTags.TagSemicolon)).intValue());\r\n }\r\n if (Calendar.class.equals(type)) {\r\n Calendar calendar = Calendar.getInstance(TimeZone.getDefault());\r\n calendar.setTime(new Date(Double.valueOf(readUntil(HproseTags.TagSemicolon)).longValue()));\r\n return calendar;\r\n }\r\n if (Date.class.equals(type)) {\r\n return new Date(Double.valueOf(readUntil(HproseTags.TagSemicolon)).longValue());\r\n }\r\n return castError(\"Double\", type);\r\n }\r\n\r\n private Object readEmpty(Class type) throws IOException {\r\n if (type == null ||\r\n String.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return \"\";\r\n }\r\n if (StringBuffer.class.equals(type)) {\r\n return new StringBuffer();\r\n }\r\n if (char[].class.equals(type)) {\r\n return new char[0];\r\n }\r\n if (byte[].class.equals(type)) {\r\n return new byte[0];\r\n }\r\n if (Boolean.class.equals(type)) {\r\n return Boolean.FALSE;\r\n }\r\n if (Integer.class.equals(type)) {\r\n return HproseHelper.valueOf(0);\r\n }\r\n if (Long.class.equals(type)) {\r\n return HproseHelper.valueOf((long) 0);\r\n }\r\n if (Byte.class.equals(type)) {\r\n return HproseHelper.valueOf((byte) 0);\r\n }\r\n if (Short.class.equals(type)) {\r\n return HproseHelper.valueOf((short) 0);\r\n }\r\n if (Character.class.equals(type)) {\r\n return HproseHelper.valueOf((char) 0);\r\n }\r\n if (Float.class.equals(type)) {\r\n return new Float(0);\r\n }\r\n if (Double.class.equals(type)) {\r\n return new Double(0);\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return BigInteger.ZERO;\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return BigDecimal.valueOf(0);\r\n }\r\n return castError(\"Empty String\", type);\r\n }\r\n\r\n private Object readTrue(Class type) throws IOException {\r\n if (type == null ||\r\n Boolean.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return Boolean.TRUE;\r\n }\r\n if (String.class.equals(type)) {\r\n return \"true\";\r\n }\r\n if (Integer.class.equals(type)) {\r\n return HproseHelper.valueOf(1);\r\n }\r\n if (Long.class.equals(type)) {\r\n return HproseHelper.valueOf((long) 1);\r\n }\r\n if (Byte.class.equals(type)) {\r\n return HproseHelper.valueOf((byte) 1);\r\n }\r\n if (Short.class.equals(type)) {\r\n return HproseHelper.valueOf((short) 1);\r\n }\r\n if (Character.class.equals(type)) {\r\n return HproseHelper.valueOf('T');\r\n }\r\n if (Float.class.equals(type)) {\r\n return new Float(1);\r\n }\r\n if (Double.class.equals(type)) {\r\n return new Double(1);\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return BigInteger.ONE;\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return BigDecimal.valueOf(1);\r\n }\r\n return castError(\"Boolean\", type);\r\n }\r\n\r\n private Object readFalse(Class type) throws IOException {\r\n if (type == null ||\r\n Boolean.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return Boolean.FALSE;\r\n }\r\n if (String.class.equals(type)) {\r\n return \"false\";\r\n }\r\n if (Integer.class.equals(type)) {\r\n return HproseHelper.valueOf(0);\r\n }\r\n if (Long.class.equals(type)) {\r\n return HproseHelper.valueOf((long) 0);\r\n }\r\n if (Byte.class.equals(type)) {\r\n return HproseHelper.valueOf((byte) 0);\r\n }\r\n if (Short.class.equals(type)) {\r\n return HproseHelper.valueOf((short) 0);\r\n }\r\n if (Character.class.equals(type)) {\r\n return HproseHelper.valueOf('F');\r\n }\r\n if (Float.class.equals(type)) {\r\n return new Float(0);\r\n }\r\n if (Double.class.equals(type)) {\r\n return new Double(0);\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return BigInteger.ZERO;\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return BigDecimal.valueOf(0);\r\n }\r\n return castError(\"Boolean\", type);\r\n }\r\n\r\n private Object readNaN(Class type) throws IOException {\r\n if ((type == null) ||\r\n Double.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return HproseHelper.valueOf(Double.NaN);\r\n }\r\n if (Float.class.equals(type)) {\r\n return HproseHelper.valueOf(Float.NaN);\r\n }\r\n if (String.class.equals(type)) {\r\n return \"NaN\";\r\n }\r\n return castError(\"NaN\", type);\r\n }\r\n\r\n private Object readInfinity(Class type) throws IOException {\r\n if ((type == null) ||\r\n Double.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return HproseHelper.valueOf(readInfinity(false));\r\n }\r\n if (Float.class.equals(type)) {\r\n return HproseHelper.valueOf((float) readInfinity(false));\r\n }\r\n if (String.class.equals(type)) {\r\n return String.valueOf(readInfinity(false));\r\n }\r\n return castError(\"Infinity\", type);\r\n }\r\n\r\n private Object readBytes(Class type) throws IOException {\r\n if ((type == null) ||\r\n byte[].class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return readBytes(false);\r\n }\r\n if (String.class.equals(type)) {\r\n return new String(readBytes(false));\r\n }\r\n return castError(\"byte[]\", type);\r\n }\r\n\r\n private Object readUTF8Char(Class type) throws IOException {\r\n char u = readUTF8Char(false);\r\n if ((type == null) ||\r\n Character.class.equals(type)) {\r\n return HproseHelper.valueOf(u);\r\n }\r\n if (String.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return String.valueOf((char)u);\r\n }\r\n if (Integer.class.equals(type)) {\r\n return HproseHelper.valueOf((int)u);\r\n }\r\n if (Byte.class.equals(type)) {\r\n return HproseHelper.valueOf((byte)u);\r\n }\r\n if (Long.class.equals(type)) {\r\n return HproseHelper.valueOf((long)u);\r\n }\r\n if (Short.class.equals(type)) {\r\n return HproseHelper.valueOf((short)u);\r\n }\r\n if (Float.class.equals(type)) {\r\n return HproseHelper.valueOf((float)u);\r\n }\r\n if (Double.class.equals(type)) {\r\n return HproseHelper.valueOf((double)u);\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return BigInteger.valueOf((long)u);\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return BigDecimal.valueOf((long)u);\r\n }\r\n if (char[].class.equals(type)) {\r\n return new char[] { u };\r\n }\r\n if (Boolean.class.equals(type)) {\r\n return HproseHelper.valueOf(u != 0 && u != '0' && u != 'F' && u != 'f');\r\n }\r\n if (Calendar.class.equals(type)) {\r\n Calendar calendar = Calendar.getInstance(TimeZone.getDefault());\r\n calendar.setTime(new Date((long)u));\r\n return calendar;\r\n }\r\n if (Date.class.equals(type)) {\r\n return new Date((long)u);\r\n }\r\n return castError(\"Character\", type);\r\n }\r\n\r\n public void checkTag(int expectTag, int tag) throws IOException {\r\n if (tag != expectTag) {\r\n throw new HproseException(\"Tag '\" + (char) expectTag +\r\n \"' expected, but '\" + (char) tag +\r\n \"' found in stream\");\r\n }\r\n }\r\n\r\n public void checkTag(int expectTag) throws IOException {\r\n checkTag(expectTag, stream.read());\r\n }\r\n\r\n public int checkTags(String expectTags, int tag) throws IOException {\r\n if (expectTags.indexOf(tag) == -1) {\r\n throw new HproseException(\"Tag '\" + expectTags +\r\n \"' expected, but '\" + (char) tag +\r\n \"' found in stream\");\r\n }\r\n return tag;\r\n }\r\n\r\n public int checkTags(String expectTags) throws IOException {\r\n return checkTags(expectTags, stream.read());\r\n }\r\n\r\n public String readUntil(int tag) throws IOException {\r\n StringBuffer sb = new StringBuffer();\r\n int i = stream.read();\r\n while ((i != tag) && (i != -1)) {\r\n sb.append((char) i);\r\n i = stream.read();\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public byte readByte(int tag) throws IOException {\r\n byte result = 0;\r\n int i = stream.read();\r\n if (i == tag) return result;\r\n byte sign = 1;\r\n if (i == '+') {\r\n i = stream.read();\r\n }\r\n else if (i == '-') {\r\n sign = -1;\r\n i = stream.read();\r\n }\r\n while ((i != tag) && (i != -1)) {\r\n result *= 10;\r\n result += (i - '0') * sign;\r\n i = stream.read();\r\n }\r\n return result;\r\n }\r\n\r\n public short readShort(int tag) throws IOException {\r\n short result = 0;\r\n int i = stream.read();\r\n if (i == tag) return result;\r\n short sign = 1;\r\n if (i == '+') {\r\n i = stream.read();\r\n }\r\n else if (i == '-') {\r\n sign = -1;\r\n i = stream.read();\r\n }\r\n while ((i != tag) && (i != -1)) {\r\n result *= 10;\r\n result += (i - '0') * sign;\r\n i = stream.read();\r\n }\r\n return result;\r\n }\r\n\r\n public int readInt(int tag) throws IOException {\r\n int result = 0;\r\n int i = stream.read();\r\n if (i == tag) return result;\r\n int sign = 1;\r\n if (i == '+') {\r\n i = stream.read();\r\n }\r\n else if (i == '-') {\r\n sign = -1;\r\n i = stream.read();\r\n }\r\n while ((i != tag) && (i != -1)) {\r\n result *= 10;\r\n result += (i - '0') * sign;\r\n i = stream.read();\r\n }\r\n return result;\r\n }\r\n\r\n public long readLong(int tag) throws IOException {\r\n long result = 0;\r\n int i = stream.read();\r\n if (i == tag) return result;\r\n long sign = 1;\r\n if (i == '+') {\r\n i = stream.read();\r\n }\r\n else if (i == '-') {\r\n sign = -1;\r\n i = stream.read();\r\n }\r\n while ((i != tag) && (i != -1)) {\r\n result *= 10;\r\n result += (i - '0') * sign;\r\n i = stream.read();\r\n }\r\n return result;\r\n }\r\n\r\n public int readInteger() throws IOException {\r\n return readInteger(true);\r\n }\r\n\r\n public int readInteger(boolean includeTag) throws IOException {\r\n if (includeTag) {\r\n int tag = stream.read();\r\n if ((tag >= '0') && (tag <= '9')) {\r\n return tag - '0';\r\n }\r\n checkTag(HproseTags.TagInteger, tag);\r\n }\r\n return readInt(HproseTags.TagSemicolon);\r\n }\r\n\r\n public BigInteger readBigInteger() throws IOException {\r\n return readBigInteger(true);\r\n }\r\n\r\n public BigInteger readBigInteger(boolean includeTag) throws IOException {\r\n if (includeTag) {\r\n int tag = stream.read();\r\n if ((tag >= '0') && (tag <= '9')) {\r\n return BigInteger.valueOf((long)(tag - '0'));\r\n }\r\n checkTags((char) HproseTags.TagInteger + \"\" +\r\n (char) HproseTags.TagLong, tag);\r\n }\r\n return new BigInteger(readUntil(HproseTags.TagSemicolon));\r\n }\r\n\r\n public long readLong() throws IOException {\r\n return readLong(true);\r\n }\r\n\r\n public long readLong(boolean includeTag) throws IOException {\r\n if (includeTag) {\r\n int tag = stream.read();\r\n if ((tag >= '0') && (tag <= '9')) {\r\n return (long)(tag - '0');\r\n }\r\n checkTags((char) HproseTags.TagInteger + \"\" +\r\n (char) HproseTags.TagLong, tag);\r\n }\r\n return readLong(HproseTags.TagSemicolon);\r\n }\r\n\r\n public double readDouble() throws IOException {\r\n return readDouble(true);\r\n }\r\n\r\n public double readDouble(boolean includeTag) throws IOException {\r\n if (includeTag) {\r\n int tag = stream.read();\r\n if ((tag >= '0') && (tag <= '9')) {\r\n return (double)(tag - '0');\r\n }\r\n checkTags((char) HproseTags.TagInteger + \"\" +\r\n (char) HproseTags.TagLong + \"\" +\r\n (char) HproseTags.TagDouble + \"\" +\r\n (char) HproseTags.TagNaN + \"\" +\r\n (char) HproseTags.TagInfinity, tag);\r\n if (tag == HproseTags.TagNaN) {\r\n return Double.NaN;\r\n }\r\n if (tag == HproseTags.TagInfinity) {\r\n return readInfinity(false);\r\n }\r\n }\r\n return Double.parseDouble(readUntil(HproseTags.TagSemicolon));\r\n }\r\n\r\n public double readNaN() throws IOException {\r\n checkTag(HproseTags.TagNaN);\r\n return Double.NaN;\r\n }\r\n\r\n public double readInfinity() throws IOException {\r\n return readInfinity(true);\r\n }\r\n\r\n public double readInfinity(boolean includeTag) throws IOException {\r\n if (includeTag) {\r\n checkTag(HproseTags.TagInfinity);\r\n }\r\n return ((stream.read() == HproseTags.TagNeg) ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY);\r\n }\r\n\r\n public Object readNull() throws IOException {\r\n checkTag(HproseTags.TagNull);\r\n return null;\r\n }\r\n\r\n public Object readEmpty() throws IOException {\r\n checkTag(HproseTags.TagEmpty);\r\n return \"\";\r\n }\r\n\r\n public boolean readBoolean() throws IOException {\r\n int tag = checkTags((char) HproseTags.TagTrue + \"\" + (char) HproseTags.TagFalse);\r\n return (tag == HproseTags.TagTrue);\r\n }\r\n\r\n public Object readDate() throws IOException {\r\n return readDate(true, null);\r\n }\r\n\r\n public Object readDate(boolean includeTag) throws IOException {\r\n return readDate(includeTag, null);\r\n }\r\n\r\n public Object readDate(Class type) throws IOException {\r\n return readDate(true, type);\r\n }\r\n\r\n public Object readDate(boolean includeTag, Class type) throws IOException {\r\n int tag;\r\n if (includeTag) {\r\n tag = checkTags((char) HproseTags.TagDate + \"\" + (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n }\r\n Calendar calendar;\r\n int year = stream.read() - '0';\r\n year = year * 10 + stream.read() - '0';\r\n year = year * 10 + stream.read() - '0';\r\n year = year * 10 + stream.read() - '0';\r\n int month = stream.read() - '0';\r\n month = month * 10 + stream.read() - '0';\r\n int day = stream.read() - '0';\r\n day = day * 10 + stream.read() - '0';\r\n tag = stream.read();\r\n if (tag == HproseTags.TagTime) {\r\n int hour = stream.read() - '0';\r\n hour = hour * 10 + stream.read() - '0';\r\n int minute = stream.read() - '0';\r\n minute = minute * 10 + stream.read() - '0';\r\n int second = stream.read() - '0';\r\n second = second * 10 + stream.read() - '0';\r\n int millisecond = 0;\r\n tag = stream.read();\r\n if (tag == HproseTags.TagPoint) {\r\n millisecond = stream.read() - '0';\r\n millisecond = millisecond * 10 + stream.read() - '0';\r\n millisecond = millisecond * 10 + stream.read() - '0';\r\n tag = stream.read();\r\n if (tag >= '0' && tag <= '9') {\r\n stream.read();\r\n stream.read();\r\n tag = stream.read();\r\n if (tag >= '0' && tag <= '9') {\r\n stream.read();\r\n stream.read();\r\n tag = stream.read();\r\n }\r\n }\r\n }\r\n calendar = Calendar.getInstance(tag == HproseTags.TagUTC ? HproseHelper.UTC : TimeZone.getDefault());\r\n calendar.set(Calendar.YEAR, year);\r\n calendar.set(Calendar.MONTH, month - 1);\r\n calendar.set(Calendar.DATE, day);\r\n calendar.set(Calendar.HOUR_OF_DAY, hour);\r\n calendar.set(Calendar.MINUTE, minute);\r\n calendar.set(Calendar.SECOND, second);\r\n calendar.set(Calendar.MILLISECOND, millisecond);\r\n }\r\n else {\r\n calendar = Calendar.getInstance(tag == HproseTags.TagUTC ? HproseHelper.UTC : TimeZone.getDefault());\r\n calendar.set(Calendar.YEAR, year);\r\n calendar.set(Calendar.MONTH, month - 1);\r\n calendar.set(Calendar.DATE, day);\r\n }\r\n Object o = changeCalendarType(calendar, type);\r\n ref.add(o);\r\n return o;\r\n }\r\n\r\n public Object readTime() throws IOException {\r\n return readTime(true, null);\r\n }\r\n\r\n public Object readTime(boolean includeTag) throws IOException {\r\n return readTime(includeTag, null);\r\n }\r\n\r\n public Object readTime(Class type) throws IOException {\r\n return readTime(true, type);\r\n }\r\n\r\n public Object readTime(boolean includeTag, Class type) throws IOException {\r\n int tag;\r\n if (includeTag) {\r\n tag = checkTags((char) HproseTags.TagTime + \"\" + (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n }\r\n Calendar calendar;\r\n int hour = stream.read() - '0';\r\n hour = hour * 10 + stream.read() - '0';\r\n int minute = stream.read() - '0';\r\n minute = minute * 10 + stream.read() - '0';\r\n int second = stream.read() - '0';\r\n second = second * 10 + stream.read() - '0';\r\n int millisecond = 0;\r\n tag = stream.read();\r\n if (tag == HproseTags.TagPoint) {\r\n millisecond = stream.read() - '0';\r\n millisecond = millisecond * 10 + stream.read() - '0';\r\n millisecond = millisecond * 10 + stream.read() - '0';\r\n tag = stream.read();\r\n if (tag >= '0' && tag <= '9') {\r\n stream.read();\r\n stream.read();\r\n tag = stream.read();\r\n if (tag >= '0' && tag <= '9') {\r\n stream.read();\r\n stream.read();\r\n tag = stream.read();\r\n }\r\n }\r\n }\r\n calendar = Calendar.getInstance(tag == HproseTags.TagUTC ? HproseHelper.UTC : TimeZone.getDefault());\r\n calendar.set(Calendar.YEAR, 1970);\r\n calendar.set(Calendar.MONTH, 0);\r\n calendar.set(Calendar.DATE, 1);\r\n calendar.set(Calendar.HOUR_OF_DAY, hour);\r\n calendar.set(Calendar.MINUTE, minute);\r\n calendar.set(Calendar.SECOND, second);\r\n calendar.set(Calendar.MILLISECOND, millisecond);\r\n Object o = changeCalendarType(calendar, type);\r\n ref.add(o);\r\n return o;\r\n }\r\n\r\n public Object readDateTime() throws IOException {\r\n return readDateTime(null);\r\n }\r\n\r\n public Object readDateTime(Class type) throws IOException {\r\n int tag = checkTags((char) HproseTags.TagDate + \"\" +\r\n (char) HproseTags.TagTime + \"\" +\r\n (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n if (tag == HproseTags.TagDate) {\r\n return readDate(false, type);\r\n }\r\n return readTime(false, type);\r\n }\r\n\r\n private Object changeCalendarType(Calendar calendar, Class type) throws IOException {\r\n if (type == null ||\r\n Calendar.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return calendar;\r\n }\r\n if (Date.class.equals(type)) {\r\n return calendar.getTime();\r\n }\r\n if (Long.class.equals(type)) {\r\n return new Long(calendar.getTime().getTime());\r\n }\r\n if (String.class.equals(type)) {\r\n return calendar.getTime().toString();\r\n }\r\n return castError(calendar, type);\r\n }\r\n\r\n public byte[] readBytes() throws IOException {\r\n return readBytes(true);\r\n }\r\n\r\n public byte[] readBytes(boolean includeTag) throws IOException {\r\n if (includeTag) {\r\n int tag = checkTags((char) HproseTags.TagBytes + \"\" + (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return (byte[]) readRef(byte[].class);\r\n }\r\n }\r\n int len = readInt(HproseTags.TagQuote);\r\n int off = 0;\r\n byte[] b = new byte[len];\r\n while (len > 0) {\r\n int size = stream.read(b, off, len);\r\n off += size;\r\n len -= size;\r\n }\r\n checkTag(HproseTags.TagQuote);\r\n ref.add(b);\r\n return b;\r\n }\r\n\r\n public char readUTF8Char(boolean includeTag) throws IOException {\r\n if (includeTag) {\r\n checkTag(HproseTags.TagUTF8Char);\r\n }\r\n char u;\r\n int c = stream.read();\r\n switch (c >>> 4) {\r\n case 0:\r\n case 1:\r\n case 2:\r\n case 3:\r\n case 4:\r\n case 5:\r\n case 6:\r\n case 7: {\r\n // 0xxx xxxx\r\n u = (char) c;\r\n break;\r\n }\r\n case 12:\r\n case 13: {\r\n // 110x xxxx 10xx xxxx\r\n int c2 = stream.read();\r\n u = (char) (((c & 0x1f) << 6) |\r\n (c2 & 0x3f));\r\n break;\r\n }\r\n case 14: {\r\n // 1110 xxxx 10xx xxxx 10xx xxxx\r\n int c2 = stream.read();\r\n int c3 = stream.read();\r\n u = (char) (((c & 0x0f) << 12) |\r\n ((c2 & 0x3f) << 6) |\r\n (c3 & 0x3f));\r\n break;\r\n }\r\n default:\r\n throw new HproseException(\"bad utf-8 encoding at \" +\r\n ((c < 0) ? \"end of stream\" : \"0x\" + Integer.toHexString(c & 0xff)));\r\n }\r\n return u;\r\n }\r\n\r\n public Object readString() throws IOException {\r\n return readString(true, null, true);\r\n }\r\n\r\n public Object readString(boolean includeTag) throws IOException {\r\n return readString(includeTag, null, true);\r\n }\r\n\r\n public Object readString(Class type) throws IOException {\r\n return readString(true, type, true);\r\n }\r\n\r\n public Object readString(boolean includeTag, Class type) throws IOException {\r\n return readString(includeTag, type, true);\r\n }\r\n\r\n private Object readString(boolean includeTag, Class type, boolean includeRef) throws IOException {\r\n if (includeTag) {\r\n int tag = checkTags((char) HproseTags.TagString + \"\" +\r\n (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n }\r\n int count = readInt(HproseTags.TagQuote);\r\n char[] buf = new char[count];\r\n for (int i = 0; i < count; i++) {\r\n int c = stream.read();\r\n switch (c >>> 4) {\r\n case 0:\r\n case 1:\r\n case 2:\r\n case 3:\r\n case 4:\r\n case 5:\r\n case 6:\r\n case 7: {\r\n // 0xxx xxxx\r\n buf[i] = (char) c;\r\n break;\r\n }\r\n case 12:\r\n case 13: {\r\n // 110x xxxx 10xx xxxx\r\n int c2 = stream.read();\r\n buf[i] = (char) (((c & 0x1f) << 6) |\r\n (c2 & 0x3f));\r\n break;\r\n }\r\n case 14: {\r\n // 1110 xxxx 10xx xxxx 10xx xxxx\r\n int c2 = stream.read();\r\n int c3 = stream.read();\r\n buf[i] = (char) (((c & 0x0f) << 12) |\r\n ((c2 & 0x3f) << 6) |\r\n (c3 & 0x3f));\r\n break;\r\n }\r\n case 15: {\r\n // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx\r\n if ((c & 0xf) <= 4) {\r\n int c2 = stream.read();\r\n int c3 = stream.read();\r\n int c4 = stream.read();\r\n int s = ((c & 0x07) << 18) |\r\n ((c2 & 0x3f) << 12) |\r\n ((c3 & 0x3f) << 6) |\r\n (c4 & 0x3f) - 0x10000;\r\n if (0 <= s && s <= 0xfffff) {\r\n buf[i++] = (char) (((s >>> 10) & 0x03ff) | 0xd800);\r\n buf[i] = (char) ((s & 0x03ff) | 0xdc00);\r\n break;\r\n }\r\n }\r\n // no break here!! here need throw exception.\r\n }\r\n default:\r\n throw new HproseException(\"bad utf-8 encoding at \" +\r\n ((c < 0) ? \"end of stream\" : \"0x\" + Integer.toHexString(c & 0xff)));\r\n }\r\n }\r\n checkTag(HproseTags.TagQuote);\r\n Object o = changeStringType(buf, type);\r\n if (includeRef) {\r\n ref.add(o);\r\n }\r\n return o;\r\n }\r\n\r\n private Object changeStringType(char[] str, Class type) throws IOException {\r\n if (char[].class.equals(type)) {\r\n return str;\r\n }\r\n if (StringBuffer.class.equals(type)) {\r\n return new StringBuffer(str.length).append(str);\r\n }\r\n String s = new String(str);\r\n if ((type == null) ||\r\n String.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return s;\r\n }\r\n if (BigDecimal.class.equals(type)) {\r\n return new BigDecimal(s);\r\n }\r\n if (BigInteger.class.equals(type)) {\r\n return new BigInteger(s);\r\n }\r\n if (Byte.class.equals(type)) {\r\n return new Byte(Byte.parseByte(s));\r\n }\r\n if (Short.class.equals(type)) {\r\n return new Short(Short.parseShort(s));\r\n }\r\n if (Integer.class.equals(type)) {\r\n return new Integer(Integer.parseInt(s));\r\n }\r\n if (Long.class.equals(type)) {\r\n return new Long(Long.parseLong(s));\r\n }\r\n if (Float.class.equals(type)) {\r\n return new Float(Float.parseFloat(s));\r\n }\r\n if (Double.class.equals(type)) {\r\n return new Double(Double.parseDouble(s));\r\n }\r\n if (Character.class.equals(type)) {\r\n if (str.length == 1) {\r\n return new Character(str[0]);\r\n }\r\n else {\r\n return new Character((char) Integer.parseInt(s));\r\n }\r\n }\r\n if (Boolean.class.equals(type)) {\r\n if (str.length == 0) {\r\n return Boolean.FALSE;\r\n }\r\n else if (str.length == 1) {\r\n return HproseHelper.valueOf(str[0] != 0);\r\n }\r\n else {\r\n return HproseHelper.valueOf(s.equalsIgnoreCase(\"true\"));\r\n }\r\n }\r\n if (byte[].class.equals(type)) {\r\n try {\r\n return s.getBytes(\"UTF-8\");\r\n }\r\n catch (Exception e) {\r\n return s.getBytes();\r\n }\r\n }\r\n if (UUID.class.equals(type)) {\r\n return UUID.fromString(s);\r\n }\r\n return castError(str, type);\r\n }\r\n\r\n public Object readUUID() throws IOException {\r\n return readUUID(true, null);\r\n }\r\n\r\n public Object readUUID(boolean includeTag) throws IOException {\r\n return readUUID(includeTag, null);\r\n }\r\n\r\n public Object readUUID(Class type) throws IOException {\r\n return readUUID(true, type);\r\n }\r\n\r\n public Object readUUID(boolean includeTag, Class type) throws IOException {\r\n if (includeTag) {\r\n int tag = checkTags((char)HproseTags.TagGuid + \"\" +\r\n (char)HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n }\r\n checkTag(HproseTags.TagOpenbrace);\r\n char[] buf = new char[36];\r\n for (int i = 0; i < 36; i++) {\r\n buf[i] = (char) stream.read();\r\n }\r\n checkTag(HproseTags.TagClosebrace);\r\n Object o = changeUUIDType(buf, type);\r\n ref.add(o);\r\n return o;\r\n }\r\n\r\n private Object changeUUIDType(char[] buf, Class type) throws IOException {\r\n if (char[].class.equals(type)) {\r\n return buf;\r\n }\r\n String s = new String(buf);\r\n if (String.class.equals(type)) {\r\n return s;\r\n }\r\n if (type == null ||\r\n UUID.class.equals(type) ||\r\n Object.class.equals(type)) {\r\n return UUID.fromString(s);\r\n }\r\n if (StringBuffer.class.equals(type)) {\r\n return new StringBuffer(s);\r\n }\r\n return castError(buf, type);\r\n }\r\n\r\n private short[] readShortArray(int count) throws IOException {\r\n short[] a = new short[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = ((Short)unserialize(Short.class)).shortValue();\r\n }\r\n return a;\r\n }\r\n\r\n private int[] readIntegerArray(int count) throws IOException {\r\n int[] a = new int[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = ((Integer)unserialize(Integer.class)).intValue();\r\n }\r\n return a;\r\n }\r\n\r\n private long[] readLongArray(int count) throws IOException {\r\n long[] a = new long[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = ((Long)unserialize(Long.class)).longValue();\r\n }\r\n return a;\r\n }\r\n\r\n private boolean[] readBooleanArray(int count) throws IOException {\r\n boolean[] a = new boolean[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = ((Boolean)unserialize(Boolean.class)).booleanValue();\r\n }\r\n return a;\r\n }\r\n\r\n private float[] readFloatArray(int count) throws IOException {\r\n float[] a = new float[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = ((Float)unserialize(Float.class)).floatValue();\r\n }\r\n return a;\r\n }\r\n\r\n private double[] readDoubleArray(int count) throws IOException {\r\n double[] a = new double[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = ((Double)unserialize(Double.class)).doubleValue();\r\n }\r\n return a;\r\n }\r\n\r\n private BigInteger[] readBigIntegerArray(int count) throws IOException {\r\n BigInteger[] a = new BigInteger[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (BigInteger)unserialize(BigInteger.class);\r\n }\r\n return a;\r\n }\r\n\r\n private String[] readStringArray(int count) throws IOException {\r\n String[] a = new String[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (String) unserialize(String.class);\r\n }\r\n return a;\r\n }\r\n\r\n private StringBuffer[] readStringBufferArray(int count) throws IOException {\r\n StringBuffer[] a = new StringBuffer[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (StringBuffer) unserialize(StringBuffer.class);\r\n }\r\n return a;\r\n }\r\n\r\n private BigDecimal[] readBigDecimalArray(int count) throws IOException {\r\n BigDecimal[] a = new BigDecimal[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (BigDecimal) unserialize(BigDecimal.class);\r\n }\r\n return a;\r\n }\r\n\r\n private byte[][] readBytesArray(int count) throws IOException {\r\n byte[][] a = new byte[count][];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (byte[]) unserialize(byte[].class);\r\n }\r\n return a;\r\n }\r\n\r\n private char[][] readCharsArray(int count) throws IOException {\r\n char[][] a = new char[count][];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (char[]) unserialize(char[].class);\r\n }\r\n return a;\r\n }\r\n\r\n private Calendar[] readCalendarArray(int count) throws IOException {\r\n Calendar[] a = new Calendar[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (Calendar) unserialize(Calendar.class);\r\n }\r\n return a;\r\n }\r\n\r\n private Date[] readDateArray(int count) throws IOException {\r\n Date[] a = new Date[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = (Date) unserialize(Date.class);\r\n }\r\n return a;\r\n }\r\n\r\n public void readArray(Class[] types, Object[] a, int count) throws IOException {\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = unserialize(types[i]);\r\n }\r\n }\r\n\r\n public Object[] readArray(int count) throws IOException {\r\n Object[] a = new Object[count];\r\n ref.add(a);\r\n for (int i = 0; i < count; i++) {\r\n a[i] = unserialize(Object.class);\r\n }\r\n return a;\r\n }\r\n\r\n private ArrayList readArrayList(int count) throws IOException {\r\n ArrayList list = new ArrayList(count);\r\n ref.add(list);\r\n for (int i = 0; i < count; i++) {\r\n list.add(unserialize(Object.class));\r\n }\r\n return list;\r\n }\r\n\r\n private LinkedList readLinkedList(int count) throws IOException {\r\n LinkedList list = new LinkedList();\r\n ref.add(list);\r\n for (int i = 0; i < count; i++) {\r\n list.add(unserialize(Object.class));\r\n }\r\n return list;\r\n }\r\n\r\n private Vector readVector(int count) throws IOException {\r\n Vector list = new Vector(count);\r\n ref.add(list);\r\n for (int i = 0; i < count; i++) {\r\n list.addElement(unserialize(Object.class));\r\n }\r\n return list;\r\n }\r\n\r\n private Stack readStack(int count) throws IOException {\r\n Stack list = new Stack();\r\n ref.add(list);\r\n for (int i = 0; i < count; i++) {\r\n list.addElement(unserialize(Object.class));\r\n }\r\n return list;\r\n }\r\n\r\n private HashSet readHashSet(int count) throws IOException {\r\n HashSet set = new HashSet();\r\n ref.add(set);\r\n for (int i = 0; i < count; i++) {\r\n set.add(unserialize(Object.class));\r\n }\r\n return set;\r\n }\r\n\r\n private TreeSet readTreeSet(int count) throws IOException {\r\n TreeSet set = new TreeSet();\r\n ref.add(set);\r\n for (int i = 0; i < count; i++) {\r\n set.add(unserialize(Object.class));\r\n }\r\n return set;\r\n }\r\n\r\n private Collection readCollection(int count, Class type) throws IOException {\r\n Collection collection = (Collection) HproseHelper.newInstance(type);\r\n ref.add(collection);\r\n for (int i = 0; i < count; i++) {\r\n collection.add(unserialize(Object.class));\r\n }\r\n return collection;\r\n }\r\n\r\n private Hashtable readListAsHashtable(int count) throws IOException {\r\n Hashtable map = new Hashtable(count);\r\n ref.add(map);\r\n for (int i = 0; i < count; i++) {\r\n Object key = HproseHelper.valueOf(i);\r\n Object value = unserialize(Object.class);\r\n map.put(key, value);\r\n }\r\n return map;\r\n }\r\n\r\n private Map readListAsMap(int count, Class type) throws IOException {\r\n Map map = (Map) HproseHelper.newInstance(type);\r\n ref.add(map);\r\n for (int i = 0; i < count; i++) {\r\n Object key = HproseHelper.valueOf(i);\r\n Object value = unserialize(Object.class);\r\n map.put(key, value);\r\n }\r\n return map;\r\n }\r\n\r\n public Object readList() throws IOException {\r\n return readList(true, null);\r\n }\r\n\r\n public Object readList(boolean includeTag) throws IOException {\r\n return readList(includeTag, null);\r\n }\r\n\r\n public Object readList(Class type) throws IOException {\r\n return readList(true, type);\r\n }\r\n\r\n public Object readList(boolean includeTag, Class type) throws IOException {\r\n if (includeTag) {\r\n int tag = checkTags((char) HproseTags.TagList + \"\" +\r\n (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n }\r\n int count = readInt(HproseTags.TagOpenbrace);\r\n Object list = null;\r\n if ((type == null) ||\r\n Object.class.equals(type) ||\r\n Collection.class.equals(type) ||\r\n AbstractCollection.class.equals(type) ||\r\n List.class.equals(type) ||\r\n AbstractList.class.equals(type) ||\r\n ArrayList.class.equals(type)) {\r\n list = readArrayList(count);\r\n }\r\n else if (AbstractSequentialList.class.equals(type) ||\r\n LinkedList.class.equals(type)) {\r\n list = readLinkedList(count);\r\n }\r\n else if (int[].class.equals(type)) {\r\n list = readIntegerArray(count);\r\n }\r\n else if (short[].class.equals(type)) {\r\n list = readShortArray(count);\r\n }\r\n else if (long[].class.equals(type)) {\r\n list = readLongArray(count);\r\n }\r\n else if (String[].class.equals(type)) {\r\n list = readStringArray(count);\r\n }\r\n else if (boolean[].class.equals(type)) {\r\n list = readBooleanArray(count);\r\n }\r\n else if (double[].class.equals(type)) {\r\n list = readDoubleArray(count);\r\n }\r\n else if (float[].class.equals(type)) {\r\n list = readFloatArray(count);\r\n }\r\n else if (BigInteger[].class.equals(type)) {\r\n list = readBigIntegerArray(count);\r\n }\r\n else if (BigDecimal[].class.equals(type)) {\r\n list = readBigDecimalArray(count);\r\n }\r\n else if (StringBuffer[].class.equals(type)) {\r\n list = readStringBufferArray(count);\r\n }\r\n else if (byte[][].class.equals(type)) {\r\n list = readBytesArray(count);\r\n }\r\n else if (char[][].class.equals(type)) {\r\n list = readCharsArray(count);\r\n }\r\n else if (Calendar[].class.equals(type)) {\r\n list = readCalendarArray(count);\r\n }\r\n else if (Date[].class.equals(type)) {\r\n list = readDateArray(count);\r\n }\r\n else if (Object[].class.equals(type)) {\r\n list = readArray(count);\r\n }\r\n else if (Vector.class.equals(type)) {\r\n list = readVector(count);\r\n }\r\n else if (Stack.class.equals(type)) {\r\n list = readStack(count);\r\n }\r\n else if (Set.class.equals(type) ||\r\n AbstractSet.class.equals(type) ||\r\n HashSet.class.equals(type)) {\r\n list = readHashSet(count);\r\n }\r\n else if (SortedSet.class.equals(type) ||\r\n TreeSet.class.equals(type)) {\r\n list = readTreeSet(count);\r\n }\r\n else if (Collection.class.isAssignableFrom(type)) {\r\n list = readCollection(count, type);\r\n }\r\n else if (Hashtable.class.equals(type)) {\r\n list = readListAsHashtable(count);\r\n }\r\n else if (Map.class.isAssignableFrom(type)) {\r\n list = readListAsMap(count, type);\r\n }\r\n else {\r\n castError(\"List\", type);\r\n }\r\n checkTag(HproseTags.TagClosebrace);\r\n return list;\r\n }\r\n\r\n private HashMap readHashMap(int count) throws IOException {\r\n HashMap map = new HashMap(count);\r\n ref.add(map);\r\n for (int i = 0; i < count; i++) {\r\n Object key = unserialize(Object.class);\r\n Object value = unserialize(Object.class);\r\n map.put(key, value);\r\n }\r\n return map;\r\n }\r\n\r\n private TreeMap readTreeMap(int count) throws IOException {\r\n TreeMap map = new TreeMap();\r\n ref.add(map);\r\n for (int i = 0; i < count; i++) {\r\n Object key = unserialize(Object.class);\r\n Object value = unserialize(Object.class);\r\n map.put(key, value);\r\n }\r\n return map;\r\n }\r\n\r\n private Hashtable readHashtable(int count) throws IOException {\r\n Hashtable map = new Hashtable(count);\r\n ref.add(map);\r\n for (int i = 0; i < count; i++) {\r\n Object key = unserialize(Object.class);\r\n Object value = unserialize(Object.class);\r\n map.put(key, value);\r\n }\r\n return map;\r\n }\r\n\r\n private Map readMap(int count, Class type) throws IOException {\r\n Map map = (Map) HproseHelper.newInstance(type);\r\n ref.add(map);\r\n for (int i = 0; i < count; i++) {\r\n Object key = unserialize(Object.class);\r\n Object value = unserialize(Object.class);\r\n map.put(key, value);\r\n }\r\n return map;\r\n }\r\n\r\n private Serializable readObject(int count, Class type) throws IOException {\r\n Serializable obj = (Serializable)HproseHelper.newInstance(type);\r\n ref.add(obj);\r\n for (int i = 0; i < count; i++) {\r\n String name = (String)(readString(String.class));\r\n Object value = unserialize(obj.getPropertyType(name));\r\n obj.setProperty(name, value);\r\n }\r\n return obj;\r\n }\r\n\r\n public Object readMap() throws IOException {\r\n return readMap(true, null);\r\n }\r\n\r\n public Object readMap(boolean includeTag) throws IOException {\r\n return readMap(includeTag, null);\r\n }\r\n\r\n public Object readMap(Class type) throws IOException {\r\n return readMap(true, type);\r\n }\r\n\r\n public Object readMap(boolean includeTag, Class type) throws IOException {\r\n if (includeTag) {\r\n int tag = checkTags((char) HproseTags.TagMap + \"\" +\r\n (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n }\r\n int count = readInt(HproseTags.TagOpenbrace);\r\n Object map = null;\r\n if ((type == null) ||\r\n Object.class.equals(type) ||\r\n Map.class.equals(type) ||\r\n AbstractMap.class.equals(type) ||\r\n HashMap.class.equals(type)) {\r\n map = readHashMap(count);\r\n }\r\n else if (SortedMap.class.equals(type) ||\r\n TreeMap.class.equals(type)) {\r\n map = readTreeMap(count);\r\n }\r\n else if (Hashtable.class.equals(type)) {\r\n map = readHashtable(count);\r\n }\r\n else {\r\n if (Map.class.isAssignableFrom(type)) {\r\n map = readMap(count, type);\r\n }\r\n else {\r\n map = readObject(count, type);\r\n }\r\n }\r\n checkTag(HproseTags.TagClosebrace);\r\n return map;\r\n }\r\n\r\n public Object readObject() throws IOException {\r\n return readObject(true, null);\r\n }\r\n\r\n public Object readObject(boolean includeTag) throws IOException {\r\n return readObject(includeTag, null);\r\n }\r\n\r\n public Object readObject(Class type) throws IOException {\r\n return readObject(true, type);\r\n }\r\n\r\n public Object readObject(boolean includeTag, Class type) throws IOException {\r\n if (includeTag) {\r\n int tag = checkTags((char) HproseTags.TagObject + \"\" +\r\n (char) HproseTags.TagClass + \"\" +\r\n (char) HproseTags.TagRef);\r\n if (tag == HproseTags.TagRef) {\r\n return readRef(type);\r\n }\r\n if (tag == HproseTags.TagClass) {\r\n readClass();\r\n return readObject(type);\r\n }\r\n }\r\n Object c = classref.get(readInt(HproseTags.TagOpenbrace));\r\n String[] propertyNames = (String[]) propertyref.get(c);\r\n int count = propertyNames.length;\r\n Serializable obj = null;\r\n if (Class.class.equals(c.getClass())) {\r\n Class cls = (Class) c;\r\n if ((type == null) || type.isAssignableFrom(cls)) {\r\n obj = HproseHelper.newInstance(cls);\r\n }\r\n else {\r\n obj = HproseHelper.newInstance(type);\r\n }\r\n }\r\n else if (type != null) {\r\n obj = HproseHelper.newInstance(type);\r\n }\r\n if (obj == null) {\r\n HashMap map = new HashMap(count);\r\n ref.add(map);\r\n for (int i = 0; i < count; i++) {\r\n map.put(propertyNames[i], unserialize(Object.class));\r\n }\r\n checkTag(HproseTags.TagClosebrace);\r\n return map;\r\n }\r\n else {\r\n ref.add(obj);\r\n for (int i = 0; i < count; i++) {\r\n Object value = unserialize(obj.getPropertyType(propertyNames[i]));\r\n obj.setProperty(propertyNames[i], value);\r\n }\r\n checkTag(HproseTags.TagClosebrace);\r\n return obj;\r\n }\r\n }\r\n\r\n private void readClass() throws IOException {\r\n String className = (String) readString(false, null, false);\r\n int count = readInt(HproseTags.TagOpenbrace);\r\n String[] propertyNames = new String[count];\r\n for (int i = 0; i < count; i++) {\r\n propertyNames[i] = (String) readString(true);\r\n }\r\n checkTag(HproseTags.TagClosebrace);\r\n Class type = HproseHelper.getClass(className);\r\n if (type == null) {\r\n Object key = new Object();\r\n classref.add(key);\r\n propertyref.put(key, propertyNames);\r\n }\r\n else {\r\n classref.add(type);\r\n propertyref.put(type, propertyNames);\r\n }\r\n }\r\n\r\n private Object readRef(Class type) throws IOException {\r\n Object o = ref.get(readInt(HproseTags.TagSemicolon));\r\n if (type == null || type.isInstance(o)) {\r\n return o;\r\n }\r\n return castError(o, type);\r\n }\r\n\r\n private Object castError(String srctype, Class desttype) throws IOException {\r\n throw new HproseException(srctype + \" can't change to \" + desttype.getName());\r\n }\r\n\r\n private Object castError(Object obj, Class type) throws IOException {\r\n throw new HproseException(obj.getClass().getName() + \" can't change to \" + type.getName());\r\n }\r\n\r\n public ByteArrayOutputStream readRaw() throws IOException {\r\n \tByteArrayOutputStream ostream = new ByteArrayOutputStream();\r\n \treadRaw(ostream);\r\n \treturn ostream;\r\n }\r\n\r\n public void readRaw(OutputStream ostream) throws IOException {\r\n readRaw(ostream, stream.read());\r\n }\r\n\r\n private void readRaw(OutputStream ostream, int tag) throws IOException {\r\n ostream.write(tag);\r\n switch (tag) {\r\n case '0':\r\n case '1':\r\n case '2':\r\n case '3':\r\n case '4':\r\n case '5':\r\n case '6':\r\n case '7':\r\n case '8':\r\n case '9':\r\n case HproseTags.TagNull:\r\n case HproseTags.TagEmpty:\r\n case HproseTags.TagTrue:\r\n case HproseTags.TagFalse:\r\n case HproseTags.TagNaN:\r\n break;\r\n case HproseTags.TagInfinity:\r\n ostream.write(stream.read());\r\n break;\r\n case HproseTags.TagInteger:\r\n case HproseTags.TagLong:\r\n case HproseTags.TagDouble:\r\n case HproseTags.TagRef:\r\n readNumberRaw(ostream);\r\n break;\r\n case HproseTags.TagDate:\r\n case HproseTags.TagTime:\r\n readDateTimeRaw(ostream);\r\n break;\r\n case HproseTags.TagUTF8Char:\r\n readUTF8CharRaw(ostream);\r\n break;\r\n case HproseTags.TagBytes:\r\n readBytesRaw(ostream);\r\n break;\r\n case HproseTags.TagString:\r\n readStringRaw(ostream);\r\n break;\r\n case HproseTags.TagGuid:\r\n readGuidRaw(ostream);\r\n break;\r\n case HproseTags.TagList:\r\n case HproseTags.TagMap:\r\n case HproseTags.TagObject:\r\n readComplexRaw(ostream);\r\n break;\r\n case HproseTags.TagClass:\r\n readComplexRaw(ostream);\r\n readRaw(ostream);\r\n break;\r\n case HproseTags.TagError:\r\n readRaw(ostream);\r\n break;\r\n case -1:\r\n throw new HproseException(\"No byte found in stream\");\r\n default:\r\n throw new HproseException(\"Unexpected serialize tag '\" +\r\n (char) tag + \"' in stream\");\r\n }\r\n }\r\n\r\n private void readNumberRaw(OutputStream ostream) throws IOException {\r\n int tag;\r\n do {\r\n tag = stream.read();\r\n ostream.write(tag);\r\n } while (tag != HproseTags.TagSemicolon);\r\n }\r\n\r\n private void readDateTimeRaw(OutputStream ostream) throws IOException {\r\n int tag;\r\n do {\r\n tag = stream.read();\r\n ostream.write(tag);\r\n } while (tag != HproseTags.TagSemicolon &&\r\n tag != HproseTags.TagUTC);\r\n }\r\n\r\n private void readUTF8CharRaw(OutputStream ostream) throws IOException {\r\n int tag = stream.read();\r\n switch (tag >>> 4) {\r\n case 0:\r\n case 1:\r\n case 2:\r\n case 3:\r\n case 4:\r\n case 5:\r\n case 6:\r\n case 7: {\r\n // 0xxx xxxx\r\n ostream.write(tag);\r\n break;\r\n }\r\n case 12:\r\n case 13: {\r\n // 110x xxxx 10xx xxxx\r\n ostream.write(tag);\r\n ostream.write(stream.read());\r\n break;\r\n }\r\n case 14: {\r\n // 1110 xxxx 10xx xxxx 10xx xxxx\r\n ostream.write(tag);\r\n ostream.write(stream.read());\r\n ostream.write(stream.read());\r\n break;\r\n }\r\n default:\r\n throw new HproseException(\"bad utf-8 encoding at \" +\r\n ((tag < 0) ? \"end of stream\" :\r\n \"0x\" + Integer.toHexString(tag & 0xff)));\r\n }\r\n }\r\n\r\n private void readBytesRaw(OutputStream ostream) throws IOException {\r\n int len = 0;\r\n int tag = '0';\r\n do {\r\n len *= 10;\r\n len += tag - '0';\r\n tag = stream.read();\r\n ostream.write(tag);\r\n } while (tag != HproseTags.TagQuote);\r\n int off = 0;\r\n byte[] b = new byte[len];\r\n while (len > 0) {\r\n int size = stream.read(b, off, len);\r\n off += size;\r\n len -= size;\r\n }\r\n ostream.write(b);\r\n ostream.write(stream.read());\r\n }\r\n\r\n private void readStringRaw(OutputStream ostream) throws IOException {\r\n int count = 0;\r\n int tag = '0';\r\n do {\r\n count *= 10;\r\n count += tag - '0';\r\n tag = stream.read();\r\n ostream.write(tag);\r\n } while (tag != HproseTags.TagQuote);\r\n for (int i = 0; i < count; i++) {\r\n tag = stream.read();\r\n switch (tag >>> 4) {\r\n case 0:\r\n case 1:\r\n case 2:\r\n case 3:\r\n case 4:\r\n case 5:\r\n case 6:\r\n case 7: {\r\n // 0xxx xxxx\r\n ostream.write(tag);\r\n break;\r\n }\r\n case 12:\r\n case 13: {\r\n // 110x xxxx 10xx xxxx\r\n ostream.write(tag);\r\n ostream.write(stream.read());\r\n break;\r\n }\r\n case 14: {\r\n // 1110 xxxx 10xx xxxx 10xx xxxx\r\n ostream.write(tag);\r\n ostream.write(stream.read());\r\n ostream.write(stream.read());\r\n break;\r\n }\r\n case 15: {\r\n // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx\r\n if ((tag & 0xf) <= 4) {\r\n ostream.write(tag);\r\n ostream.write(stream.read());\r\n ostream.write(stream.read());\r\n ostream.write(stream.read());\r\n break;\r\n }\r\n // no break here!! here need throw exception.\r\n }\r\n default:\r\n throw new HproseException(\"bad utf-8 encoding at \" +\r\n ((tag < 0) ? \"end of stream\" :\r\n \"0x\" + Integer.toHexString(tag & 0xff)));\r\n }\r\n }\r\n ostream.write(stream.read());\r\n }\r\n\r\n private void readGuidRaw(OutputStream ostream) throws IOException {\r\n int len = 38;\r\n int off = 0;\r\n byte[] b = new byte[len];\r\n while (len > 0) {\r\n int size = stream.read(b, off, len);\r\n off += size;\r\n len -= size;\r\n }\r\n ostream.write(b);\r\n }\r\n\r\n private void readComplexRaw(OutputStream ostream) throws IOException {\r\n int tag;\r\n do {\r\n tag = stream.read();\r\n ostream.write(tag);\r\n } while (tag != HproseTags.TagOpenbrace);\r\n while ((tag = stream.read()) != HproseTags.TagClosebrace) {\r\n readRaw(ostream, tag);\r\n }\r\n ostream.write(tag);\r\n }\r\n\r\n public void reset() {\r\n ref.clear();\r\n classref.clear();\r\n propertyref.clear();\r\n }\r\n}", "public final class HproseTags {\r\n /* Serialize Tags */\r\n public static final int TagInteger = 'i';\r\n public static final int TagLong = 'l';\r\n public static final int TagDouble = 'd';\r\n public static final int TagNull = 'n';\r\n public static final int TagEmpty = 'e';\r\n public static final int TagTrue = 't';\r\n public static final int TagFalse = 'f';\r\n public static final int TagNaN = 'N';\r\n public static final int TagInfinity = 'I';\r\n public static final int TagDate = 'D';\r\n public static final int TagTime = 'T';\r\n public static final int TagUTC = 'Z';\r\n public static final int TagBytes = 'b';\r\n public static final int TagUTF8Char = 'u';\r\n public static final int TagString = 's';\r\n public static final int TagGuid = 'g';\r\n public static final int TagList = 'a';\r\n public static final int TagMap = 'm';\r\n public static final int TagClass = 'c';\r\n public static final int TagObject = 'o';\r\n public static final int TagRef = 'r';\r\n /* Serialize Marks */\r\n public static final int TagPos = '+';\r\n public static final int TagNeg = '-';\r\n public static final int TagSemicolon = ';';\r\n public static final int TagOpenbrace = '{';\r\n public static final int TagClosebrace = '}';\r\n public static final int TagQuote = '\"';\r\n public static final int TagPoint = '.';\r\n /* Protocol Tags */\r\n public static final int TagFunctions = 'F';\r\n public static final int TagCall = 'C';\r\n public static final int TagResult = 'R';\r\n public static final int TagArgument = 'A';\r\n public static final int TagError = 'E';\r\n public static final int TagEnd = 'z';\r\n}" ]
import java.io.InputStream; import java.io.OutputStream; import hprose.common.HproseErrorEvent; import hprose.common.HproseCallback; import hprose.common.HproseInvoker; import hprose.common.HproseException; import hprose.common.HproseResultMode; import hprose.common.HproseFilter; import hprose.io.HproseHelper; import hprose.io.HproseWriter; import hprose.io.HproseReader; import hprose.io.HproseTags; import java.io.ByteArrayOutputStream; import java.io.IOException;
invoke(functionName, arguments, callback, null, null, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent) { invoke(functionName, arguments, callback, errorEvent, null, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, boolean byRef) { invoke(functionName, arguments, callback, null, null, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, boolean byRef) { invoke(functionName, arguments, callback, errorEvent, null, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, HproseCallback callback, Class returnType) { invoke(functionName, nullArgs, callback, null, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType) { invoke(functionName, nullArgs, callback, errorEvent, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, Class returnType) { invoke(functionName, arguments, callback, null, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType) { invoke(functionName, arguments, callback, errorEvent, returnType, false, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, Class returnType, boolean byRef) { invoke(functionName, arguments, callback, null, returnType, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, Class returnType, boolean byRef) { invoke(functionName, arguments, callback, errorEvent, returnType, byRef, HproseResultMode.Normal); } public final void invoke(String functionName, HproseCallback callback, HproseResultMode resultMode) { invoke(functionName, nullArgs, callback, null, null, false, resultMode); } public final void invoke(String functionName, HproseCallback callback, HproseErrorEvent errorEvent, HproseResultMode resultMode) { invoke(functionName, nullArgs, callback, errorEvent, null, false, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseResultMode resultMode) { invoke(functionName, arguments, callback, null, null, false, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, HproseResultMode resultMode) { invoke(functionName, arguments, callback, errorEvent, null, false, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, boolean byRef, HproseResultMode resultMode) { invoke(functionName, arguments, callback, null, null, byRef, resultMode); } public final void invoke(String functionName, Object[] arguments, HproseCallback callback, HproseErrorEvent errorEvent, boolean byRef, HproseResultMode resultMode) { invoke(functionName, arguments, callback, errorEvent, null, byRef, resultMode); } private void invoke(final String functionName, final Object[] arguments, final HproseCallback callback, final HproseErrorEvent errorEvent, final Class returnType, final boolean byRef, final HproseResultMode resultMode) { new Thread() { public void run() { try { Object result = invoke(functionName, arguments, returnType, byRef, resultMode); callback.handler(result, arguments); } catch (Throwable ex) { if (errorEvent != null) { errorEvent.handler(functionName, ex); } else if (onError != null) { onError.handler(functionName, ex); } } } }.start(); } public final Object invoke(String functionName) throws IOException { return invoke(functionName, nullArgs, (Class)null, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments) throws IOException { return invoke(functionName, arguments, (Class)null, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments, boolean byRef) throws IOException { return invoke(functionName, arguments, (Class)null, byRef, HproseResultMode.Normal); } public final Object invoke(String functionName, Class returnType) throws IOException { return invoke(functionName, nullArgs, returnType, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments, Class returnType) throws IOException { return invoke(functionName, arguments, returnType, false, HproseResultMode.Normal); } public final Object invoke(String functionName, Object[] arguments, Class returnType, boolean byRef) throws IOException { return invoke(functionName, arguments, returnType, byRef, HproseResultMode.Normal); } public final Object invoke(String functionName, HproseResultMode resultMode) throws IOException { return invoke(functionName, nullArgs, (Class)null, false, resultMode); } public final Object invoke(String functionName, Object[] arguments, HproseResultMode resultMode) throws IOException { return invoke(functionName, arguments, (Class)null, false, resultMode); } public final Object invoke(String functionName, Object[] arguments, boolean byRef, HproseResultMode resultMode) throws IOException { return invoke(functionName, arguments, (Class)null, byRef, resultMode); } private Object invoke(String functionName, Object[] arguments, Class returnType, boolean byRef, HproseResultMode resultMode) throws IOException { Object context = getInvokeContext(); OutputStream ostream = getOutputStream(context); boolean success = false; try { doOutput(functionName, arguments, byRef, ostream); success = true; } finally { sendData(ostream, context, success); } Object result = null; InputStream istream = getInputStream(context); success = false; try { result = doInput(arguments, returnType, resultMode, istream); success = true; } finally { endInvoke(istream, context, success); }
if (result instanceof HproseException) {
2
kihira/Tails
src/main/java/uk/kihira/tails/client/ClientEventHandler.java
[ "public class GuiEditor extends GuiBase\n{\n static final int TEXT_COLOUR = 0xFFFFFF;\n static final int HOZ_LINE_COLOUR = 0xFF000000;\n static final int SOFT_BLACK = 0xEA000000;\n static final int DARK_GREY = 0xFF1A1A1A;\n static final int GREY = 0xFF666666;\n\n private static final int TINT_PANEL_HEIGHT = 145;\n\n @Nullable\n private Outfit originalOutfit; // The outfit from before the GUI was opened. Is updated when player saves new outfit\n private Outfit outfit;\n @Nullable\n private OutfitPart currentOutfitPart;\n private UUID playerUUID;\n\n TintPanel tintPanel;\n PartsPanel partsPanel;\n private TransformPanel transformPanel;\n private PreviewPanel previewPanel;\n private ControlsPanel controlsPanel;\n public LibraryPanel libraryPanel;\n public LibraryInfoPanel libraryInfoPanel;\n\n public GuiEditor()\n {\n super(new TranslationTextComponent(\"tails.editor.title\"), 4);\n\n this.playerUUID = PlayerEntity.getUUID(getMinecraft().getSession().getProfile());\n\n // Load outfit or create empty one\n this.originalOutfit = Config.localOutfit.get() == null ? new Outfit() : Config.localOutfit.get();\n\n // Copy outfit for modifying and set as our current outfit\n // todo should a new UUID be generated?\n // if one isn't generated, won't be able to properly cache data on clients.\n // but then again, we would probably be sent the entire json blob when trying to get the player outfit anyway\n this.outfit = Tails.GSON.fromJson(Tails.GSON.toJson(this.originalOutfit), Outfit.class);\n if (this.outfit == null)\n {\n this.outfit = new Outfit();\n }\n setOutfit(this.outfit);\n }\n\n @Override\n public void init()\n {\n final int previewWindowEdgeOffset = 150;\n final int previewWindowRight = this.width - previewWindowEdgeOffset;\n final int previewWindowBottom = this.height - 30;\n final int texSelectHeight = 35;\n\n //Not an ideal solution but keeps everything from resetting on resize\n if (this.tintPanel == null)\n {\n final ArrayList<Panel<?>> layer0 = getLayer(0);\n final ArrayList<Panel<?>> layer1 = getLayer(1);\n\n layer0.add(this.previewPanel = new PreviewPanel(\n this,\n previewWindowEdgeOffset,\n 0,\n previewWindowRight - previewWindowEdgeOffset,\n previewWindowBottom)\n );\n layer1.add(this.partsPanel = new PartsPanel(\n this,\n 0,\n 0,\n previewWindowEdgeOffset,\n this.height - texSelectHeight)\n );\n layer1.add(this.libraryPanel = new LibraryPanel(\n this,\n 0,\n 0,\n previewWindowEdgeOffset,\n this.height)\n );\n layer1.add(this.tintPanel = new TintPanel(\n this,\n previewWindowRight,\n 0,\n this.width - previewWindowRight,\n TINT_PANEL_HEIGHT)\n );\n layer1.add(this.transformPanel = new TransformPanel(\n this,\n previewWindowRight,\n TINT_PANEL_HEIGHT,\n this.width - previewWindowRight,\n this.height - TINT_PANEL_HEIGHT)\n );\n layer1.add(this.libraryInfoPanel =\n new LibraryInfoPanel(\n this,\n previewWindowRight,\n 0,\n this.width - previewWindowRight,\n this.height - 60)\n );\n layer1.add(this.controlsPanel = new ControlsPanel(\n this,\n previewWindowEdgeOffset,\n previewWindowBottom,\n previewWindowRight - previewWindowEdgeOffset,\n this.height - previewWindowBottom)\n );\n\n this.libraryInfoPanel.enabled = false;\n this.libraryPanel.enabled = false;\n }\n else\n {\n this.tintPanel.resize(previewWindowRight, 0, this.width - previewWindowRight, TINT_PANEL_HEIGHT);\n this.transformPanel.resize(previewWindowRight, TINT_PANEL_HEIGHT,this.width - previewWindowRight, this.height - TINT_PANEL_HEIGHT);\n this.libraryInfoPanel.resize(previewWindowRight, 0, this.width - previewWindowRight, this.height - 60);\n this.partsPanel.resize(0, 0, previewWindowEdgeOffset, this.height - texSelectHeight);\n this.libraryPanel.resize(0, 0, previewWindowEdgeOffset, this.height);\n this.previewPanel.resize(previewWindowEdgeOffset, 0, previewWindowRight - previewWindowEdgeOffset, previewWindowBottom);\n this.controlsPanel.resize(previewWindowEdgeOffset, previewWindowBottom, previewWindowRight - previewWindowEdgeOffset, this.height - previewWindowBottom);\n }\n\n super.init();\n }\n\n @Override\n public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks)\n {\n super.render(matrixStack, mouseX, mouseY, partialTicks);\n\n // Render any parts that have been queued up whilst in GUI as RenderWorldLast is called before GUIs\n ((ClientProxy) Tails.proxy).partRenderer.doRender(matrixStack);\n }\n\n @Override\n public void onClose()\n {\n Tails.proxy.setActiveOutfit(playerUUID, Config.localOutfit.get());\n super.onClose();\n }\n\n void refreshTintPane()\n {\n tintPanel.updateTints(true);\n }\n\n /**\n * Sets the current OutfitPart that is being edited to the one supplied\n * @param outfitPart The outfit part\n */\n void setActiveOutfitPart(@Nullable OutfitPart outfitPart)\n {\n // todo should maintain a list of IOutfitPartSelected instead\n getAllPanels().forEach((final Panel panel) -> {\n if (panel instanceof IOutfitPartSelected)\n {\n ((IOutfitPartSelected) panel).OnOutfitPartSelected(outfitPart);\n }\n });\n\n currentOutfitPart = outfitPart;\n }\n\n /**\n * Adds a new OutfitPart to the Outfit and sets it to the current edited one\n * @param outfitPart The part to be added\n */\n void addOutfitPart(OutfitPart outfitPart)\n {\n outfit.parts.add(outfitPart);\n setActiveOutfitPart(outfitPart);\n }\n\n /**\n * Gets the current part on the outfit that is selected\n * @return The selected part on the outfit. May be null if there is no part or outfit\n */\n @Nullable\n OutfitPart getCurrentOutfitPart()\n {\n if (outfit == null)\n {\n return null;\n }\n return currentOutfitPart;\n }\n\n public void setOutfit(Outfit newOutfit)\n {\n outfit = newOutfit;\n Tails.proxy.setActiveOutfit(playerUUID, outfit);\n }\n\n public Outfit getOutfit()\n {\n return outfit;\n }\n}", "public final class Config \n{\n public static BooleanValue forceLegacyRendering;\n public static BooleanValue libraryEnabled;\n public static ConfigValue<Outfit> localOutfit;\n\n public static ForgeConfigSpec configuration;\n\n public static void loadConfig() \n {\n ForgeConfigSpec.Builder builder = new ForgeConfigSpec.Builder();\n\n forceLegacyRendering = builder\n .comment(\"Forces the legacy renderer which may have better compatibility with other mods\")\n .define(\"forceLegacyRenderer\", false);\n\n libraryEnabled = builder\n .comment(\"Whether to enable the library system for sharing tails. This mostly matters on servers.\")\n .define(\"enableLibrary\", true);\n\n localOutfit = builder\n .comment(\"Local Players outfit. Delete to remove all customisation data. Do not try to edit manually\")\n .define(\"localPlayerOutfit\", new Outfit());\n \n //Load default if none exists\n if (localOutfit == null) \n {\n Tails.setLocalOutfit(new Outfit());\n }\n // todo\n/* try\n {\n localOutfit = Gson.fromJson(Tails.configuration.getString(\"Local Player Outfit\",\n Configuration.CATEGORY_GENERAL, \"{}\", \"Local Players outfit. Delete to remove all customisation data. Do not try to edit manually\"), Outfit.class);\n\n } catch (JsonSyntaxException e) {\n Tails.configuration.getCategory(Configuration.CATEGORY_GENERAL).remove(\"Local Player Data\");\n Tails.LOGGER.error(\"Failed to load local player data: Invalid JSON syntax! Invalid data being removed\");\n }*/\n\n configuration = builder.build();\n //configuration.save();\n }\n}", "@Mod(Tails.MOD_ID)\npublic class Tails \n{\n public static final String MOD_ID = \"tails\";\n public static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n public static final Gson GSON = new GsonBuilder().create();\n public static final boolean DEBUG = true;\n\n public static boolean hasRemote;\n\n public static CommonProxy proxy = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new);\n\n public Tails()\n {\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigChange);\n MinecraftForge.EVENT_BUS.addListener(this::addReloadListener);\n }\n\n private void setup(final FMLCommonSetupEvent event)\n {\n proxy.preInit();\n Config.loadConfig();\n\n PartRegistry.loadAllPartsFromResources();\n }\n\n private void addReloadListener(final AddReloadListenerEvent event)\n {\n event.addListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) ->\n CompletableFuture.runAsync(() -> proxy.onResourceManagerReload()));\n }\n\n public void onConfigChange(final ModConfigEvent event)\n {\n if (event.getConfig().getModId().equals(Tails.MOD_ID)) \n {\n Config.loadConfig();\n }\n }\n\n public static void setLocalOutfit(final Outfit outfit)\n {\n Config.localOutfit.set(outfit);\n Config.configuration.save();\n }\n}", "public final class PlayerDataMessage \n{\n private UUID uuid;\n private Outfit outfit;\n private boolean shouldRemove;\n\n public PlayerDataMessage() {}\n public PlayerDataMessage(UUID uuid, Outfit outfit, boolean shouldRemove)\n {\n this.uuid = uuid;\n this.outfit = outfit;\n this.shouldRemove = shouldRemove;\n }\n\n public PlayerDataMessage(PacketBuffer buf) \n {\n this.uuid = buf.readUniqueId();\n String tailInfoJson = buf.readString();\n if (!Strings.isNullOrEmpty(tailInfoJson)) \n {\n try \n {\n this.outfit = Tails.GSON.fromJson(tailInfoJson, Outfit.class);\n } catch (JsonSyntaxException e) \n {\n Tails.LOGGER.catching(e);\n }\n }\n else \n {\n this.outfit = null;\n }\n }\n\n public void encode(PacketBuffer buf) \n {\n buf.writeUniqueId(this.uuid);\n buf.writeString(outfit == null ? \"\" : Tails.GSON.toJson(this.outfit));\n }\n\n public void handle(Supplier<Context> ctx) \n {\n ctx.get().enqueueWork(() ->\n {\n if (this.shouldRemove)\n {\n Tails.proxy.removeActiveOutfit(this.uuid);\n } \n else if (this.outfit != null) \n {\n Tails.proxy.setActiveOutfit(this.uuid, this.outfit);\n //Tell other clients about the change\n if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) \n {\n TailsPacketHandler.networkWrapper.send(PacketDistributor.ALL.noArg(), new PlayerDataMessage(this.uuid, this.outfit, false));\n }\n }\n });\n ctx.get().setPacketHandled(true);\n }\n}", "public final class TailsPacketHandler \n{\n private static final String PROTOCOL_VERSION = \"1\";\n\n public static final SimpleChannel networkWrapper = NetworkRegistry.newSimpleChannel(\n new ResourceLocation(Tails.MOD_ID, \"main\"),\n () -> PROTOCOL_VERSION,\n PROTOCOL_VERSION::equals,\n TailsPacketHandler::versionCheck);\n\n private static boolean versionCheck(String serverVersion) \n {\n if (serverVersion.equals(NetworkRegistry.ABSENT) || serverVersion.equals(NetworkRegistry.ACCEPTVANILLA))\n {\n Tails.LOGGER.info(\"Connecting to vanilla server, or mod is missing from server\");\n Tails.hasRemote = false; // TODO better pattern\n }\n else if (serverVersion.equals(PROTOCOL_VERSION))\n {\n Tails.LOGGER.info(\"Connecting to server that has Tails mod installed and acceptable version\");\n Tails.hasRemote = true;\n }\n else\n {\n Tails.LOGGER.warn(\"Unknown server version %s!\", serverVersion);\n }\n\n return true;\n }\n}", "public class ClientProxy extends CommonProxy \n{\n public PartRenderer partRenderer;\n\n @Override\n public void preInit() \n {\n registerMessages();\n registerHandlers();\n this.libraryManager = new LibraryManager.ClientLibraryManager();\n }\n\n @Override\n protected void registerHandlers()\n {\n ClientEventHandler eventHandler = new ClientEventHandler();\n MinecraftForge.EVENT_BUS.register(eventHandler);\n\n //super.registerHandlers();\n }\n\n @Override\n public void onResourceManagerReload()\n {\n setupRenderers();\n }\n /**\n * Sets up the various part renders on the player model.\n * Renderers used depends upon legacy setting\n */\n private void setupRenderers()\n {\n/* boolean legacyRenderer = Config.forceLegacyRendering.get();\n if (legacyRenderer)\n {\n Tails.LOGGER.info(\"Legacy Renderer has been forced enabled\");\n }*/\n // todo Fix smart moving compat\n// else if (Loader.isModLoaded(\"SmartMoving\"))\n// {\n// Tails.LOGGER.info(\"Legacy Renderer enabled automatically for mod compatibility\");\n// legacyRenderer = true;\n// }\n partRenderer = new PartRenderer();\n\n Map<String, PlayerRenderer> skinMap = Minecraft.getInstance().getRenderManager().getSkinMap();\n\n/* if (legacyRenderer)\n {\n MinecraftForge.EVENT_BUS.register(new FallbackRenderHandler());\n\n // Default\n PlayerModel<AbstractClientPlayerEntity> model = skinMap.get(\"default\").getEntityModel();\n model.bipedHead.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.HEAD));\n model.bipedBody.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.CHEST));\n model.bipedLeftArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_ARM));\n model.bipedRightArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_ARM));\n model.bipedLeftLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_LEG));\n model.bipedRightLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_LEG));\n // Slim\n model = skinMap.get(\"slim\").getEntityModel();\n model.bipedHead.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.HEAD));\n model.bipedBody.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.CHEST));\n model.bipedLeftArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_ARM));\n model.bipedRightArm.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_ARM));\n model.bipedLeftLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.LEFT_LEG));\n model.bipedRightLeg.addChild(new FallbackRenderHandler.ModelRendererWrapper(model, MountPoint.RIGHT_LEG));\n } else */\n {\n // Default\n PlayerRenderer renderPlayer = skinMap.get(\"default\");\n renderPlayer.addLayer(new LayerPart(renderPlayer, renderPlayer.getEntityModel().bipedHead, partRenderer, MountPoint.HEAD));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedBody, partRenderer, MountPoint.CHEST));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedLeftArm, partRenderer, MountPoint.LEFT_ARM));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedRightArm, partRenderer, MountPoint.RIGHT_ARM));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedLeftLeg, partRenderer, MountPoint.LEFT_LEG));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedRightLeg, partRenderer, MountPoint.RIGHT_LEG));\n\n // Slim\n renderPlayer = skinMap.get(\"slim\");\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedHead, partRenderer, MountPoint.HEAD));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedBody, partRenderer, MountPoint.CHEST));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedLeftArm, partRenderer, MountPoint.LEFT_ARM));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedRightArm, partRenderer, MountPoint.RIGHT_ARM));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedLeftLeg, partRenderer, MountPoint.LEFT_LEG));\n renderPlayer.addLayer(new LayerPart(renderPlayer,renderPlayer.getEntityModel().bipedRightLeg, partRenderer, MountPoint.RIGHT_LEG));\n }\n }\n}" ]
import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.IngameMenuScreen; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.resources.I18n; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import uk.kihira.tails.client.gui.GuiEditor; import uk.kihira.tails.common.Config; import uk.kihira.tails.common.Tails; import uk.kihira.tails.common.network.PlayerDataMessage; import uk.kihira.tails.common.network.TailsPacketHandler; import uk.kihira.tails.proxy.ClientProxy;
package uk.kihira.tails.client; public class ClientEventHandler { private boolean sentPartInfoToServer = false; private boolean clearAllPartInfo = false; /* *** Tails Editor Button *** */ @SubscribeEvent public void onScreenInitPost(GuiScreenEvent.InitGuiEvent.Post event) { if (event.getGui() instanceof IngameMenuScreen) { Button tailsButton = new Button((event.getGui().width / 2) - 35, event.getGui().height - 25, 70, 20, new TranslationTextComponent("tails.gui.button.editor"), (button) -> { event.getGui().getMinecraft().displayGuiScreen(new GuiEditor()); event.setCanceled(true); }); event.addWidget(tailsButton); } } /* *** Tails syncing *** */ @SubscribeEvent public void onConnectToServer(ClientPlayerNetworkEvent.LoggedInEvent event) { //Add local player texture to map if (Config.localOutfit != null) { Tails.proxy.setActiveOutfit(Minecraft.getInstance().getSession().getProfile().getId(), Config.localOutfit.get()); } } @SubscribeEvent public void onDisconnect(ClientPlayerNetworkEvent.LoggedOutEvent e) { Tails.hasRemote = false; sentPartInfoToServer = false; clearAllPartInfo = true; Config.loadConfig(); } @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent e) { if (e.phase == TickEvent.Phase.START) { if (clearAllPartInfo) { Tails.proxy.clearAllPartsData(); clearAllPartInfo = false; } //World can't be null if we want to send a packet it seems else if (!sentPartInfoToServer && Minecraft.getInstance().world != null) {
TailsPacketHandler.networkWrapper.sendToServer(new PlayerDataMessage(Minecraft.getInstance().getSession().getProfile().getId(), Config.localOutfit.get(), false));
3
tupilabs/tap4j
src/test/java/org/tap4j/consumer/TestTap13YamlConsumer2.java
[ "public class BaseTapTest {\n\n /**\n * Get a test set for a given file name.\n * @param name File name.\n * @return Test Set.\n */\n protected TestSet getTestSet(String name) {\n return this.getTestSet(new Tap13Parser(), name);\n }\n\n /**\n * Get a test set for given parser and file name.\n * @param parser Parser.\n * @param name File name.\n * @return Test Set.\n */\n protected TestSet getTestSet(Parser parser, String name) {\n TapConsumer consumer = getConsumer(parser);\n return consumer\n .load(new File(getClass()\n .getResource(name)\n .getFile()));\n }\n\n /**\n * Get a tap consumer.\n * @return TAP Consumer.\n */\n protected TapConsumer getConsumer() {\n return getConsumer(new Tap13Parser());\n }\n\n /**\n * Get a consumer for with a given parser.\n * @param parser TAP parser.\n * @return TAP Consumer.\n */\n protected TapConsumer getConsumer(Parser parser) {\n return new TapConsumerImpl(parser);\n }\n\n}", "public class Directive implements Serializable {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = 8183935213177175225L;\n\n /**\n * Directive Value (TO DO, SKIP).\n */\n private final DirectiveValues directiveValue;\n\n /**\n * Reason for the directive.\n */\n private final String reason;\n\n /**\n * Constructor with parameters.\n *\n * @param directiveValue Directive Value.\n * @param reason Reason for the directive.\n */\n public Directive(DirectiveValues directiveValue, String reason) {\n super();\n this.directiveValue = directiveValue;\n this.reason = reason;\n }\n\n /**\n * @return Directive Value.\n */\n public DirectiveValues getDirectiveValue() {\n return this.directiveValue;\n }\n\n /**\n * @return Reason for the directive.\n */\n public String getReason() {\n return this.reason;\n }\n\n}", "public class Plan extends TapElement {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = 8517740981464132024L;\n\n /**\n * Default initial test step.\n */\n private static final Integer INITIAL_TEST_STEP = 1;\n\n /**\n * TAP Plan initial test number.\n */\n private final Integer initialTestNumber;\n\n /**\n * TAP Plan last test number.\n */\n\n private final Integer lastTestNumber;\n\n /**\n * TAP Plan skip. If present the tests should not be executed.\n */\n private SkipPlan skip;\n\n /**\n * Child subtest.\n */\n private TestSet subtest;\n\n /**\n * Constructor with parameters.\n *\n * @param initialTestNumber Initial test number (usually is 1).\n * @param lastTestNumber Last test number (may be 0 if to skip all tests).\n */\n public Plan(Integer initialTestNumber, Integer lastTestNumber) {\n super();\n this.initialTestNumber = initialTestNumber;\n this.lastTestNumber = lastTestNumber;\n this.subtest = null;\n }\n\n /**\n * Constructor with parameters.\n *\n * @param amountOfTests How many tests we have in the plan.\n */\n public Plan(Integer amountOfTests) {\n super();\n this.initialTestNumber = INITIAL_TEST_STEP;\n this.lastTestNumber = amountOfTests;\n }\n\n /**\n * Constructor with parameters.\n *\n * @param amountOfTests How many tests we have in the plan.\n * @param skip Plan skip with a reason.\n */\n public Plan(Integer amountOfTests, SkipPlan skip) {\n super();\n this.initialTestNumber = INITIAL_TEST_STEP;\n this.lastTestNumber = amountOfTests;\n this.skip = skip;\n }\n\n /**\n * Constructor with parameters.\n *\n * @param initialTestNumber Initial test number (usually is 1).\n * @param lastTestNumber Last test number (may be 0 if to skip all tests).\n * @param skip Plan skip with a reason.\n */\n public Plan(Integer initialTestNumber, Integer lastTestNumber, SkipPlan skip) {\n super();\n this.initialTestNumber = initialTestNumber;\n this.lastTestNumber = lastTestNumber;\n this.skip = skip;\n }\n\n /**\n * @return Initial test number.\n */\n public Integer getInitialTestNumber() {\n return this.initialTestNumber;\n }\n\n /**\n * @return Last test number.\n */\n public Integer getLastTestNumber() {\n return this.lastTestNumber;\n }\n\n /**\n * @return Flag used to indicate whether skip all tests or not.\n */\n public Boolean isSkip() {\n return this.skip != null;\n }\n\n /**\n * @return Plan Skip with reason.\n */\n public SkipPlan getSkip() {\n return this.skip;\n }\n\n /**\n * Defines whether we should skip all tests or not.\n *\n * @param skip Plan Skip.\n */\n public void setSkip(SkipPlan skip) {\n this.skip = skip;\n }\n\n /**\n * @return the subtest\n */\n public TestSet getSubtest() {\n return subtest;\n }\n\n /**\n * @param subtest the subtest to set\n */\n public void setSubtest(TestSet subtest) {\n this.subtest = subtest;\n }\n}", "public class TestResult extends TapResult {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = -2735372334488828166L;\n\n /**\n * Test Status (OK, NOT OK).\n */\n private StatusValues status;\n\n /**\n * Test Number.\n */\n private Integer testNumber;\n\n /**\n * Description of the test.\n */\n private String description;\n\n /**\n * Directive of the test (TO DO, SKIP).\n */\n private Directive directive;\n\n /**\n * Child subtest.\n */\n private TestSet subtest;\n\n /**\n * Comment.\n */\n private List<Comment> comments;\n\n /**\n * Default constructor.\n */\n public TestResult() {\n super();\n this.status = StatusValues.NOT_OK;\n this.testNumber = -1;\n this.subtest = null;\n this.comments = new LinkedList<>();\n }\n\n /**\n * Constructor with parameter.\n *\n * @param testStatus Status of the test.\n * @param testNumber Number of the test.\n */\n public TestResult(StatusValues testStatus, Integer testNumber) {\n super();\n this.status = testStatus;\n this.testNumber = testNumber;\n this.comments = new LinkedList<>();\n }\n\n /**\n * @return Status of the test.\n */\n public StatusValues getStatus() {\n return this.status;\n }\n\n /**\n * @param status Status of the test.\n */\n public void setStatus(StatusValues status) {\n this.status = status;\n }\n\n /**\n * @return Test Number.\n */\n public Integer getTestNumber() {\n return this.testNumber;\n }\n\n /**\n * @param testNumber Test Number.\n */\n public void setTestNumber(Integer testNumber) {\n this.testNumber = testNumber;\n }\n\n /**\n * @return Test description.\n */\n public String getDescription() {\n return this.description;\n }\n\n /**\n * @param description Test description.\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return Optional Directive.\n */\n public Directive getDirective() {\n return this.directive;\n }\n\n /**\n * @param directive Optional Directive.\n */\n public void setDirective(Directive directive) {\n this.directive = directive;\n }\n\n /**\n * @return the subtest\n */\n public TestSet getSubtest() {\n return subtest;\n }\n\n /**\n * @param subtest the subtest to set\n */\n public void setSubtest(TestSet subtest) {\n this.subtest = subtest;\n }\n\n /**\n * @return The comments for this Test Result.\n */\n public List<Comment> getComments() {\n return this.comments;\n }\n\n /**\n * @param comments list of comments for this Test Result.\n */\n public void setComments(List<Comment> comments) {\n this.comments = comments;\n }\n\n /**\n * Adds a new comment to this Test Result.\n *\n * @param comment comment for this Test Result.\n */\n public void addComment(Comment comment) {\n this.comments.add(comment);\n }\n\n}", "public class TestSet implements Serializable {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = 114777557084672201L;\n\n /**\n * TAP Header.\n */\n private Header header;\n\n /**\n * TAP Plan.\n */\n private Plan plan;\n\n /**\n * List of TAP Lines.\n */\n private final List<TapElement> tapLines = new LinkedList<>();\n\n /**\n * List of Test Results.\n */\n private final List<TestResult> testResults = new LinkedList<>();\n\n /**\n * List of Bail Outs.\n */\n private final List<BailOut> bailOuts = new LinkedList<>();\n\n /**\n * List of comments.\n */\n private final List<Comment> comments = new LinkedList<>();\n\n /**\n * TAP Footer.\n */\n private Footer footer;\n\n /**\n * Default constructor.\n */\n public TestSet() {\n super();\n }\n\n /**\n * @return TAP Header.\n */\n public Header getHeader() {\n return this.header;\n }\n\n /**\n * @param header TAP Header.\n */\n public void setHeader(Header header) {\n this.header = header;\n }\n\n /**\n * @return TAP Plan.\n */\n public Plan getPlan() {\n return this.plan;\n }\n\n /**\n * @param plan TAP Plan.\n */\n public void setPlan(Plan plan) {\n this.plan = plan;\n }\n\n /**\n * @return List of TAP Lines. These lines may be either a TestResult or a\n * BailOut.\n */\n public List<TapElement> getTapLines() {\n return tapLines;\n }\n\n /**\n * @return List of Test Results.\n */\n public List<TestResult> getTestResults() {\n return this.testResults;\n }\n\n /**\n * @return Next test number.\n */\n public int getNextTestNumber() {\n return this.testResults.size() + 1;\n }\n\n /**\n * @return List of Bail Outs.\n */\n public List<BailOut> getBailOuts() {\n return this.bailOuts;\n }\n\n /**\n * @return List of Comments.\n */\n public List<Comment> getComments() {\n return this.comments;\n }\n\n /**\n * Adds a new TAP Line.\n *\n * @param tapLine TAP Line.\n * @return True if the TAP Line could be added into the list successfully.\n */\n public boolean addTapLine(TapResult tapLine) {\n return this.tapLines.add(tapLine);\n }\n\n /**\n * Adds a TestResult into the list of TestResults. If the TestResult Test\n * Number is null or less than or equals to zero it is changed to the next\n * Test Number in the sequence.\n *\n * @param testResult TAP TestResult.\n * @return Whether could add to TestResult list or not.\n */\n public boolean addTestResult(TestResult testResult) {\n if (testResult.getTestNumber() == null\n || testResult.getTestNumber() <= 0) {\n testResult.setTestNumber(this.testResults.size() + 1);\n }\n this.testResults.add(testResult);\n return this.tapLines.add(testResult);\n }\n\n /**\n * @param bailOut Bail Out.\n * @return Whether could add to BailOut list or not.\n */\n public boolean addBailOut(BailOut bailOut) {\n this.bailOuts.add(bailOut);\n return this.tapLines.add(bailOut);\n }\n\n /**\n * @param comment Comment. Whether could add to Comment list or not.\n * @return True if could successfully add the comment.\n */\n public boolean addComment(Comment comment) {\n comments.add(comment);\n return tapLines.add(comment);\n }\n\n /**\n * Removes a TAP Line from the list.\n *\n * @param tapLine TAP Line object.\n * @return True if could successfully remove the TAP Line from the list.\n */\n protected boolean removeTapLine(TapResult tapLine) {\n return this.tapLines.remove(tapLine);\n }\n\n /**\n * Removes a Test Result from the list.\n *\n * @param testResult Test Result.\n * @return True if could successfully remove the Test Result from the list.\n */\n public boolean removeTestResult(TestResult testResult) {\n boolean flag = false;\n if (this.tapLines.remove(testResult)) {\n this.testResults.remove(testResult);\n flag = true;\n }\n return flag;\n }\n\n /**\n * Removes a Bail Out from the list.\n *\n * @param bailOut Bail Out object.\n * @return True if could successfully remove the Bail Out from the list.\n */\n public boolean removeBailOut(BailOut bailOut) {\n boolean flag = false;\n if (this.tapLines.remove(bailOut)) {\n this.bailOuts.remove(bailOut);\n flag = true;\n }\n return flag;\n }\n\n /**\n * Removes a Comment from the list.\n *\n * @param comment Comment.\n * @return True if could successfully remove the Comment from the list.\n */\n public boolean removeComment(Comment comment) {\n boolean flag = false;\n if (this.tapLines.remove(comment)) {\n this.comments.remove(comment);\n flag = true;\n }\n return flag;\n }\n\n /**\n * @return Number of TAP Lines. It includes Test Results, Bail Outs and\n * Comments (the footer is not included).\n */\n public int getNumberOfTapLines() {\n return this.tapLines.size();\n }\n\n /**\n * @return Number of Test Results.\n */\n public int getNumberOfTestResults() {\n return this.testResults.size();\n }\n\n /**\n * @return Number of Bail Outs.\n */\n public int getNumberOfBailOuts() {\n return this.bailOuts.size();\n }\n\n /**\n * @return Number of Comments.\n */\n public int getNumberOfComments() {\n return this.comments.size();\n }\n\n /**\n * @return Footer\n */\n public Footer getFooter() {\n return this.footer;\n }\n\n /**\n * @param footer Footer\n */\n public void setFooter(Footer footer) {\n this.footer = footer;\n }\n\n /**\n * @return <code>true</code> if it has any Bail Out statement,\n * <code>false</code> otherwise.\n */\n public boolean hasBailOut() {\n boolean isBailOut = false;\n\n for (TapElement tapLine : tapLines) {\n if (tapLine instanceof BailOut) {\n isBailOut = true;\n break;\n }\n }\n\n return isBailOut;\n }\n\n /**\n * @return <code>true</code> if it contains OK status, <code>false</code>\n * otherwise.\n */\n public Boolean containsOk() {\n boolean containsOk = false;\n\n for (TestResult testResult : this.testResults) {\n if (testResult.getStatus().equals(StatusValues.OK)) {\n containsOk = true;\n break;\n }\n }\n\n return containsOk;\n }\n\n /**\n * @return <code>true</code> if it contains NOT OK status,\n * <code>false</code> otherwise.\n */\n public Boolean containsNotOk() {\n boolean containsNotOk = false;\n\n for (TestResult testResult : this.testResults) {\n if (testResult.getStatus().equals(StatusValues.NOT_OK)) {\n containsNotOk = true;\n break;\n }\n }\n\n return containsNotOk;\n }\n\n /**\n * @return <code>true</code> if it contains BAIL OUT!, <code>false</code>\n * otherwise.\n */\n public Boolean containsBailOut() {\n return this.bailOuts.size() > 0;\n }\n\n /**\n * @param testNumber test result number.\n * @return Test Result with given number.\n */\n public TestResult getTestResult(Integer testNumber) {\n TestResult foundTestResult = null;\n for (TestResult testResult : this.testResults) {\n if (testResult.getTestNumber().equals(testNumber)) {\n foundTestResult = testResult;\n break;\n }\n }\n return foundTestResult;\n }\n\n}", "public enum DirectiveValues {\n\n /**\n * Valid values.\n */\n SKIP(\"SKIP\"), TODO(\"TODO\");\n\n /**\n * The text of the directive.\n */\n private final String textValue;\n\n /**\n * Constructor with parameter.\n *\n * @param textValue Directive text value.\n */\n DirectiveValues(String textValue) {\n this.textValue = textValue;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n return this.textValue;\n }\n\n /**\n * Get a directive value for a given string.\n * @param textValue String\n * @return Directive value\n */\n public static DirectiveValues get(String textValue) {\n if (\"skip\".equalsIgnoreCase(textValue)) {\n return DirectiveValues.SKIP;\n } else if (\"todo\".equalsIgnoreCase(textValue)) {\n return DirectiveValues.TODO;\n }\n return null;\n }\n\n}" ]
import org.tap4j.model.Directive; import org.tap4j.model.Plan; import org.tap4j.model.TestResult; import org.tap4j.model.TestSet; import org.tap4j.util.DirectiveValues; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.tap4j.BaseTapTest;
/* * The MIT License * * Copyright (c) 2010 tap4j team (see AUTHORS) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.tap4j.consumer; /** * @since 1.0 */ public class TestTap13YamlConsumer2 extends BaseTapTest { @Test public void testTapConsumerYaml() { final TestSet testSet = getTestSet("/org/tap4j/consumer/tap_with_yaml_comments_bailout_directives.tap"); assertNotNull(testSet); final Plan plan = testSet.getPlan(); assertEquals(1, (int) plan.getInitialTestNumber()); assertEquals(3, (int) plan.getLastTestNumber()); assertEquals(3, testSet.getNumberOfTestResults()); assertTrue(testSet.containsBailOut()); final TestResult testNumber2WithSkipDirective = testSet.getTestResult(2); assertNotNull(testNumber2WithSkipDirective); final Directive skipDirective = testNumber2WithSkipDirective.getDirective();
assertSame(skipDirective.getDirectiveValue(), DirectiveValues.SKIP);
5
twothe/DaVincing
src/main/java/two/davincing/renderer/PieceRenderer.java
[ "@Mod(modid = DaVincing.MOD_ID, name = DaVincing.MOD_NAME, version = DaVincing.MOD_VERSION)\npublic class DaVincing {\n\n /* Global logger that uses string format type logging */\n public static final Logger log = LogManager.getLogger(DaVincing.class.getSimpleName(), new StringFormatterMessageFactory());\n /* Task scheduler for background task. Will run at lowest thread priority to not interfere with FPS/ticks */\n public static final ScheduledExecutorService backgroundTasks = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory(DaVincing.class.getSimpleName() + \" Worker\", Thread.MIN_PRIORITY, true));\n public static final ConcurrentLinkedQueue<Runnable> glTasks = new ConcurrentLinkedQueue<Runnable>();\n \n public static final String MOD_NAME = \"DaVincing\";\n public static final String MOD_ID = \"davincing\";\n public static final String MOD_VERSION = \"1710.1.8\"; // Make sure to keep this version in sync with the build.gradle file!\n\n @Mod.Instance(MOD_ID)\n public static DaVincing instance; // this will point to the actual instance of this class once running\n\n @SidedProxy(clientSide = \"two.davincing.ProxyClient\", serverSide = \"two.davincing.ProxyServer\")\n public static ProxyBase proxy; // will load the appropriate proxy class depending whether this is running on a client or on a server\n\n public static final Config config = new Config();\n public static final CreativeTabs tabDaVincing = new DaVincingCreativeTab();\n public static final SimpleNetworkWrapper network = NetworkRegistry.INSTANCE.newSimpleChannel(\"minepainter\");\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n config.initialize(event.getSuggestedConfigurationFile());\n proxy.onPreInit();\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent e) {\n config.load();\n proxy.onInit();\n\n Crafting.instance.registerRecipes();\n\n network.registerMessage(SculptureOperationMessage.SculptureOperationHandler.class, SculptureOperationMessage.class, 0, Side.SERVER);\n network.registerMessage(PaintingOperationHandler.class, PaintingOperationMessage.class, 1, Side.SERVER);\n config.save();\n }\n\n @Mod.EventHandler\n public void postInit(final FMLPostInitializationEvent event) {\n proxy.onPostInit();\n }\n\n @Mod.EventHandler\n public void serverLoad(final FMLServerStartingEvent event) {\n event.registerServerCommand(new CommandImportPainting());\n }\n\n @Mod.EventHandler\n public void serverStopped(final FMLServerStoppedEvent event) {\n }\n}", "public class ProxyBase {\n\n public static final BlockLoader<SculptureBlock> blockSculpture = new BlockLoader(new SculptureBlock(), SculptureEntity.class);\n public static final BlockLoader<PaintingBlock> blockPainting = new BlockLoader(new PaintingBlock(), PaintingEntity.class);\n\n public static ItemHandle itemHandle;\n public static ChiselItem itemChisel;\n public static ChiselItem itemBarcutter;\n public static ChiselItem itemSaw;\n public static PaintTool itemEraser;\n public static PaintTool itemBucket;\n public static PaintTool itemMixerbrush;\n public static PaintTool itemMinibrush;\n public static CopygunItem itemCopygun;\n public static Palette itemPalette;\n /* Items with special renderer */\n public static PieceItem itemBar;\n public static DroppedSculptureItem itemDroppedSculpture;\n public static PieceItem itemCover;\n public static CanvasItem itemCanvas;\n public static PieceItem itemPiece;\n /* Initialization list for content that needs post-initialization. */\n protected LinkedList<InitializableModContent> pendingInitialization = new LinkedList<InitializableModContent>();\n /* Global Config vars */\n public boolean doAmbientOcclusion; // whether or not to do ambient occlusion during rendering\n public final ArrayList<Block> blockBlacklist = new ArrayList<Block>();\n\n public ProxyBase() {\n }\n\n protected void loadGlobalConfigValues() {\n doAmbientOcclusion = DaVincing.config.getMiscBoolean(\"Render with Ambient Occlusion\", false);\n final List<Block> defaultBlackList = Arrays.asList(new Block[]{\n Blocks.bedrock, Blocks.cactus, Blocks.glass, Blocks.grass, Blocks.leaves, Blocks.stained_glass\n });\n\n blockBlacklist.clear();\n blockBlacklist.addAll(DaVincing.config.getMiscBlocks(\"Chisel blacklist\", defaultBlackList, \"A list of blocks that cannot be chiseled. Note that all blocks with a tile entity or blocks that are not full blocks cannot be chiseled in general.\"));\n }\n\n protected void registerBlocks() {\n blockSculpture.load();\n blockPainting.load();\n }\n\n protected void registerItems() {\n itemHandle = new ItemHandle();\n pendingInitialization.add(itemHandle);\n itemChisel = new ChiselItem();\n pendingInitialization.add(itemChisel);\n itemBarcutter = new ChiselItem.Barcutter();\n pendingInitialization.add(itemBarcutter);\n itemSaw = new ChiselItem.Saw();\n pendingInitialization.add(itemSaw);\n itemCopygun = new CopygunItem();\n pendingInitialization.add(itemCopygun);\n itemMinibrush = new PaintTool.Mini();\n pendingInitialization.add(itemMinibrush);\n itemMixerbrush = new PaintTool.Mixer();\n pendingInitialization.add(itemMixerbrush);\n itemBucket = new PaintTool.Bucket();\n pendingInitialization.add(itemBucket);\n itemEraser = new PaintTool.Eraser();\n pendingInitialization.add(itemEraser);\n itemPalette = new Palette();\n pendingInitialization.add(itemPalette);\n\n itemCanvas = new CanvasItem();\n pendingInitialization.add(itemCanvas);\n itemPiece = new PieceItem();\n pendingInitialization.add(itemPiece);\n itemBar = new PieceItem.Bar();\n pendingInitialization.add(itemBar);\n itemCover = new PieceItem.Cover();\n pendingInitialization.add(itemCover);\n itemDroppedSculpture = new DroppedSculptureItem();\n pendingInitialization.add(itemDroppedSculpture);\n }\n\n protected void registerRenderers() {\n }\n\n public void onPreInit() {\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n public void onInit() {\n loadGlobalConfigValues();\n registerBlocks();\n registerItems();\n registerRenderers();\n\n InitializableModContent content;\n while ((content = pendingInitialization.poll()) != null) {\n content.initialize();\n }\n }\n\n public void onPostInit() {\n }\n}", "public class PieceItem extends ChiselItem {\n\n public PieceItem() {\n this.setCreativeTab(null);\n this.setUnlocalizedName(\"sculpture_piece\");\n this.setTextureName(\"\");\n this.setHasSubtypes(true);\n this.setMaxStackSize(64);\n this.setMaxDamage(0);\n this.setContainerItem(null);\n }\n\n @Override\n public void registerIcons(IIconRegister r) {\n }\n\n @Override\n public Block getEditBlock(ItemStack is) {\n return Block.getBlockById((is.getItemDamage() >> 4) & 0xfff);\n }\n\n @Override\n public int getEditMeta(ItemStack is) {\n return is.getItemDamage() & 0xf;\n }\n\n @Override\n public int getChiselFlags(EntityPlayer ep) {\n return Operations.PLACE | Operations.CONSUME;\n }\n\n public int getWorthPiece() {\n return 1;\n }\n\n public static class Bar extends PieceItem {\n\n @Override\n public int getChiselFlags(EntityPlayer ep) {\n int axis = Operations.getLookingAxis(ep);\n switch (axis) {\n case 0:\n return Operations.PLACE | Operations.ALLX | Operations.CONSUME;\n case 1:\n return Operations.PLACE | Operations.ALLY | Operations.CONSUME;\n case 2:\n return Operations.PLACE | Operations.ALLZ | Operations.CONSUME;\n }\n return Operations.PLACE;\n }\n\n public int getWorthPiece() {\n return 8;\n }\n }\n\n public static class Cover extends PieceItem {\n\n @Override\n public int getChiselFlags(EntityPlayer ep) {\n int axis = Operations.getLookingAxis(ep);\n switch (axis) {\n case 0:\n return Operations.PLACE | Operations.ALLY | Operations.ALLZ | Operations.CONSUME;\n case 1:\n return Operations.PLACE | Operations.ALLX | Operations.ALLZ | Operations.CONSUME;\n case 2:\n return Operations.PLACE | Operations.ALLX | Operations.ALLY | Operations.CONSUME;\n }\n return Operations.PLACE;\n }\n\n public int getWorthPiece() {\n return 64;\n }\n }\n}", "public class SculptureBlock extends BlockContainer {\n\n protected Block currentBlock;\n protected int meta;\n protected int renderID;\n\n public SculptureBlock() {\n super(Blocks.stone.getMaterial());\n this.setHardness(1.0f);\n this.setBlockName(\"sculpture\");\n\n this.meta = 0;\n this.renderID = -1;\n this.currentBlock = Blocks.stone;\n }\n\n public void setCurrentBlock(final Block that, final int meta) {\n if (that == null) {\n this.meta = 0;\n this.renderID = -1;\n this.currentBlock = Blocks.stone;\n } else {\n this.currentBlock = that;\n this.meta = meta;\n this.renderID = that.getRenderType();\n if (!SculptureRenderCuller.isMergeable(that)) {\n this.renderID = 0;\n }\n }\n }\n\n public void useStandardRendering() {\n this.renderID = 0;\n }\n\n public void dropScrap(World w, int x, int y, int z, ItemStack is) {\n this.dropBlockAsItem(w, x, y, z, is);\n }\n\n @Override\n public MovingObjectPosition collisionRayTrace(final World world, int x, int y, int z, final Vec3 start, final Vec3 end) {\n final TileEntity tileEntity = world.getTileEntity(x, y, z);\n if (tileEntity instanceof SculptureEntity) {\n SculptureEntity tile = (SculptureEntity) tileEntity;\n Sculpture sculpture = tile.sculpture();\n\n final int[] pos = Operations.raytrace(sculpture, start.addVector(-x, -y, -z), end.addVector(-x, -y, -z));\n if (pos[0] == -1) {\n return null;\n }\n\n final ForgeDirection dir = ForgeDirection.getOrientation(pos[3]);\n Vec3 hit = null;\n if (dir.offsetX != 0) {\n hit = start.getIntermediateWithXValue(end, x + pos[0] / 8f + (dir.offsetX + 1) / 16f);\n } else if (dir.offsetY != 0) {\n hit = start.getIntermediateWithYValue(end, y + pos[1] / 8f + (dir.offsetY + 1) / 16f);\n } else if (dir.offsetZ != 0) {\n hit = start.getIntermediateWithZValue(end, z + pos[2] / 8f + (dir.offsetZ + 1) / 16f);\n }\n if (hit == null) {\n if (sculpture.isEmpty()) {\n return super.collisionRayTrace(world, x, y, z, start, end);\n }\n return null;\n }\n\n return new MovingObjectPosition(x, y, z, pos[3], hit);\n } else {\n DaVincing.log.warn(\"[SculptureBlock.collisionRayTrace] failed: expected SculptureEntity, but got %s\", Utils.getClassName(tileEntity));\n return null;\n }\n }\n\n @Override\n public void addCollisionBoxesToList(final World world, int x, int y, int z, final AxisAlignedBB par5AxisAlignedBB, final List list, Entity par7Entity) {\n final TileEntity tileEntity = world.getTileEntity(x, y, z);\n if (tileEntity instanceof SculptureEntity) {\n final SculptureEntity tile = (SculptureEntity) tileEntity;\n final Sculpture sculpture = tile.sculpture();\n\n for (int xPos = 0; xPos < 8; xPos++) {\n for (int yPos = 0; yPos < 8; yPos++) {\n for (int zPos = 0; zPos < 8; zPos++) {\n if (sculpture.getBlockAt(xPos, yPos, zPos, null) == Blocks.air) {\n continue;\n }\n this.setBlockBounds(xPos / 8f, yPos / 8f, zPos / 8f, (xPos + 1) / 8f, (yPos + 1) / 8f, (zPos + 1) / 8f);\n super.addCollisionBoxesToList(world, x, y, z, par5AxisAlignedBB, list, par7Entity);\n }\n }\n }\n this.setBlockBounds(0, 0, 0, 1, 1, 1);\n } else {\n DaVincing.log.warn(\"[SculptureBlock.addCollisionBoxesToList] failed: expected SculptureEntity, but got %s\", Utils.getClassName(tileEntity));\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public boolean shouldSideBeRendered(IBlockAccess iba, int x, int y, int z, int side) {\n//\t\tif(x>=0 && y>=0 && z>=0 && x<8 && y<8 && z<8)\n//\t\t\treturn iba.isAirBlock(x, y, z);\n if (iba.getBlock(x, y, z) == this.currentBlock) {\n return false;\n }\n return iba.isAirBlock(x, y, z) || !iba.getBlock(x, y, z).isOpaqueCube();\n }\n\n @Override\n public TileEntity createNewTileEntity(World var1, int var2) {\n return new SculptureEntity();\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister p_149651_1_) {\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return currentBlock.getIcon(side, this.meta);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public int getRenderType() {\n if (renderID == -1) {\n return ProxyBase.blockSculpture.getRenderID();\n }\n return renderID;\n }\n\n @Override\n public boolean isOpaqueCube() {\n return false;\n }\n\n @Override\n public boolean renderAsNormalBlock() {\n return false;\n }\n\n @Override\n public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player) {\n final TileEntity tileEntity = world.getTileEntity(x, y, z);\n if (tileEntity instanceof SculptureEntity) {\n final SculptureEntity sculptureEntity = (SculptureEntity) tileEntity;\n final NBTTagCompound nbt = new NBTTagCompound();\n final ItemStack itemStack = new ItemStack(ProxyBase.itemDroppedSculpture);\n\n sculptureEntity.sculpture.write(nbt);\n itemStack.setTagCompound(nbt);\n return itemStack;\n } else {\n DaVincing.log.warn(\"[SculptureBlock.getPickBlock] failed: expected SculptureEntity, but got %s\", Utils.getClassName(tileEntity));\n return null;\n }\n }\n\n @Override\n public int getLightValue(IBlockAccess world, int x, int y, int z) {\n TileEntity te = world.getTileEntity(x, y, z);\n if (te == null || !(te instanceof SculptureEntity)) {\n return super.getLightValue(world, x, y, z);\n }\n SculptureEntity se = (SculptureEntity) te;\n return se.sculpture.getLight();\n }\n\n @Override\n protected ItemStack createStackedBlock(int p_149644_1_) {\n return null;\n }\n\n public boolean dropSculptureToPlayer(World w, EntityPlayer ep, int x, int y, int z) {\n final TileEntity tileEntity = w.getTileEntity(x, y, z);\n if (tileEntity instanceof SculptureEntity) {\n final SculptureEntity se = (SculptureEntity) tileEntity;\n if (se.sculpture().isEmpty() == false) {\n final NBTTagCompound nbt = new NBTTagCompound();\n final ItemStack is = new ItemStack(ProxyBase.itemDroppedSculpture);\n\n applyPlayerRotation(se.sculpture.r, ep, true);\n se.sculpture.write(nbt);\n applyPlayerRotation(se.sculpture.r, ep, false);\n is.setTagCompound(nbt);\n this.dropBlockAsItem(w, x, y, z, is);\n\n return true;\n } else {\n DaVincing.log.warn(\"[SculptureBlock.dropSculptureToPlayer] failed: sculpture was empty\");\n }\n } else {\n DaVincing.log.warn(\"[SculptureBlock.dropSculptureToPlayer] failed: expected SculptureEntity, but got %s\", Utils.getClassName(tileEntity));\n }\n return false;\n }\n\n @Override\n public boolean removedByPlayer(World w, EntityPlayer ep, int x, int y, int z, boolean willHarvest) {\n dropSculptureToPlayer(w, ep, x, y, z);\n return super.removedByPlayer(w, ep, x, y, z, willHarvest);\n }\n\n public static void applyPlayerRotation(Rotation r, EntityPlayer ep, boolean reverse) {\n Vec3 look = ep.getLookVec();\n double dx = Math.abs(look.xCoord);\n double dz = Math.abs(look.zCoord);\n\n int rotation;\n if (dx > dz) {\n rotation = look.xCoord > 0 ? 3 : 1;\n } else {\n rotation = look.zCoord > 0 ? 2 : 0;\n }\n\n if (reverse) {\n rotation = (4 - rotation) % 4;\n }\n\n for (int i = 0; i < rotation; i++) {\n r.rotate(1);\n }\n }\n\n @Override\n public Item getItemDropped(int p_149650_1_, Random p_149650_2_, int p_149650_3_) {\n return null;\n }\n\n}", "public class Utils {\n\n public static void forEachInv(IInventory inv, IInvTraversal traversal) {\n int size = inv.getSizeInventory();\n for (int i = 0; i < size; i++) {\n ItemStack is = inv.getStackInSlot(i);\n if (traversal.visit(i, is)) {\n return;\n }\n }\n }\n\n public static interface IInvTraversal {\n\n public boolean visit(int i, ItemStack is);\n }\n\n public static String getClassName(final Object o) {\n return o == null ? \"null\" : o.getClass().getName();\n }\n\n public static String getSimpleClassName(final Object o) {\n return o == null ? \"null\" : o.getClass().getSimpleName();\n }\n\n public static String blockToString(final Block block) {\n if (block == null) {\n return \"null\";\n }\n final String blockIDName = GameData.getBlockRegistry().getNameForObject(block);\n return blockIDName == null ? block.getUnlocalizedName() : blockIDName;\n }\n\n public static String itemToString(final Item item) {\n if (item == null) {\n return \"null\";\n } else {\n final String itemIDName = GameData.getItemRegistry().getNameForObject(item);\n return itemIDName == null ? item.getUnlocalizedName() : itemIDName;\n }\n }\n}" ]
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import two.davincing.DaVincing; import two.davincing.ProxyBase; import two.davincing.item.PieceItem; import two.davincing.sculpture.SculptureBlock; import two.davincing.utils.Utils;
package two.davincing.renderer; @SideOnly(Side.CLIENT) public class PieceRenderer implements IItemRenderer { protected static final Minecraft mc = Minecraft.getMinecraft(); protected final RenderItem renderItem = new RenderItem(); protected ItemStack is; @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { return type == ItemRenderType.INVENTORY || type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED || type == ItemRenderType.EQUIPPED_FIRST_PERSON; } @Override public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return type == ItemRenderType.ENTITY || type == ItemRenderType.EQUIPPED_FIRST_PERSON; } @Override public void renderItem(ItemRenderType type, ItemStack itemStack, Object... data) { if (is == null) { is = new ItemStack(ProxyBase.blockSculpture.getBlock()); }
SculptureBlock sculpture = ProxyBase.blockSculpture.getBlock();
3
jazz-community/jazz-debug-environment
buildSrc/src/main/java/org/jazzcommunity/development/library/config/ConfigReader.java
[ "public class DetectOperatingSystem {\n public static boolean isWindows() {\n return OperatingSystem.current().isWindows();\n }\n\n public static boolean isLinux() {\n return OperatingSystem.current().isLinux();\n }\n}", "public final class FileTools {\n\n private static final Logger logger = LoggerFactory.getLogger(\"FileTools\");\n\n private FileTools() {}\n\n public static void copyAll(File f, File t) {\n Arrays.stream(Objects.requireNonNull(f.listFiles())).forEach(file -> copyFile(file, t));\n }\n\n public static void copyAll(String from, String to) {\n File f = toAbsolute(from);\n File t = toAbsolute(to);\n copyAll(f, t);\n }\n\n public static void createDirectories(String[] directories) {\n Arrays.stream(directories).map(FileTools::toAbsolute).forEach(FileTools::makeDirectory);\n }\n\n public static boolean exists(String path) {\n File file = toAbsolute(path);\n return file.exists();\n }\n\n public static boolean isEmpty(String path) {\n return getFiles(path).length == 0;\n }\n\n public static File[] getFiles(String path) {\n File file = toAbsolute(path);\n return file.listFiles();\n }\n\n public static File toAbsolute(String dir) {\n // TODO: This should use Path functionality to build the new file descriptor\n return new File(String.format(\"%s/%s\", System.getProperty(\"user.dir\"), dir));\n }\n\n public static File byVersion(String dir, String version) {\n return Arrays.stream(getFiles(dir))\n .filter(file -> file.getName().contains(version))\n .findFirst()\n .orElse(new File(\"File that doesn't exist\"));\n }\n\n public static String newestVersion(String dir) {\n // ugly workaround, but when this happens, there isn't anything there.\n if (getFiles(dir) == null || getFiles(dir).length <= 0) {\n return null;\n }\n\n File file = newestFile(dir);\n if (file.isDirectory()) {\n return file.getName();\n }\n return extractVersion(file);\n }\n\n public static File newestFile(String dir) {\n File[] files = getFiles(dir);\n\n if (files == null) {\n throw new RuntimeException(String.format(\"No files available in %s.\", dir));\n }\n\n VersionComparator comp = new VersionComparator();\n return Arrays.stream(files).max(comp).get();\n }\n\n public static void copyConfigs(String destination) {\n String source = \"tool/configs/\";\n logger.info(\"Copying configuration files from {} to {}\", source, destination);\n FileTools.makeDirectory(FileTools.toAbsolute(destination));\n FileTools.copyAll(source, destination);\n }\n\n public static void makeDirectory(File path) {\n try {\n Files.createDirectories(path.toPath());\n } catch (IOException e) {\n if (logger.isDebugEnabled()) {\n e.printStackTrace();\n }\n logger.error(\"Could not create {} because {}\", path, e.getMessage());\n }\n }\n\n public static void setExecutable(String filepath) {\n setExecutable(toAbsolute(filepath));\n }\n\n public static void setExecutable(File file) {\n if (System.getProperty(\"os.name\").contains(\"inux\")) {\n file.setExecutable(true);\n }\n }\n\n public static void copyFile(String from, String to) {\n copyFile(toAbsolute(from), toAbsolute(to));\n }\n\n public static void copyFile(File from, File to) {\n try {\n File destination = new File(to, from.getName());\n Files.copy(from.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n if (logger.isDebugEnabled()) {\n e.printStackTrace();\n }\n logger.error(\"Failed to copy files: {}\", e.getMessage());\n }\n }\n\n public static void backupFile(File from) {\n String name =\n String.format(\n \"backup/%s_%s.backup\",\n from.getName(), new SimpleDateFormat(\"yyyy-MM-dd-HH-mm-ss\").format(new Date()));\n\n if (!exists(\"backup\")) {\n createDirectories(new String[] {\"backup\"});\n }\n\n try {\n File destination = toAbsolute(name);\n Files.copy(from.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n if (logger.isDebugEnabled()) {\n e.printStackTrace();\n }\n logger.error(\"Failed to backup: {}\", e.getMessage());\n }\n }\n\n public static void deleteFolder(File folder) {\n try {\n MoreFiles.deleteRecursively(folder.toPath(), RecursiveDeleteOption.ALLOW_INSECURE);\n } catch (IOException e) {\n if (logger.isDebugEnabled()) {\n e.printStackTrace();\n }\n logger.error(\"Failed to delete folder {}: {}\", folder.getAbsolutePath(), e.getMessage());\n }\n }\n\n public static Boolean versionAvailable(String dir, String version) {\n boolean exists = FileTools.byVersion(dir, version).exists();\n\n if (!exists) {\n logger.error(\"Missing file for version {} in directory {}\", version, dir);\n }\n\n return exists;\n }\n\n public static String folderVersion(String path) {\n return new File(path).getName();\n }\n\n public static String extractVersion(File file) {\n // TODO: fix these regex, it's pretty much just look that it works so far\n Pattern pattern =\n // TODO: use lib function to get file ending, and use that for matching\n file.getName().endsWith(\"zip\")\n // TODO: just take the first number as the start of the version\n ? Pattern.compile(\"[-_]([0-9].*).zip\")\n : Pattern.compile(\"([0-9].*)$\");\n Matcher matcher = pattern.matcher(file.getName());\n // we only need exactly one match, so no need to loop\n matcher.find();\n // this must be the one match we're looking for, otherwise input is crap\n return matcher.group(1);\n }\n}", "public interface IniEntry {\n String getIniLine();\n\n String getPropertiesLine();\n\n boolean needsPropertyEntry();\n\n Stream<Path> getZip();\n}", "public final class PluginEntryFactory {\n private static final Logger logger = LoggerFactory.getLogger(\"PluginEntryFactory\");\n\n private PluginEntryFactory() {}\n\n private static boolean isSubModule(String path, File directory) {\n try {\n return directory.getCanonicalPath().contains(path)\n && directory.getCanonicalPath().length() > path.length();\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n public static IniEntry getEntry(File directory) {\n File[] files = directory.listFiles();\n\n if (!directory.isDirectory() || files == null) {\n return new InvalidEntry(directory);\n }\n\n List<String> parentCandidates =\n ConfigReader.flattenConfigs(\"jde/user/workspaces\")\n .map(entry -> entry + File.separator)\n .filter(path -> isSubModule(path, directory))\n .collect(Collectors.toList());\n\n // find out if this plugin is a \"child\" of another one\n if (parentCandidates.size() > 0) {\n // show warning for possibly wrong folder hierarchy\n if (parentCandidates.size() > 1) {\n logger.warn(\n \"More than one possible parent project found for plugin in '{}'. This is possibly due to a wrong folder hierarchy in plugin projects.\",\n directory);\n }\n String parent = parentCandidates.get(0);\n return new SubPluginEntry(directory, parent);\n }\n\n if (Arrays.stream(files).anyMatch(f -> f.getName().equals(\"META-INF\"))) {\n return new UiEntry(directory);\n }\n\n if (Arrays.stream(files).anyMatch(f -> f.getName().equals(\"plugin\"))) {\n return new ServiceEntry(directory);\n }\n\n logger.error(\n \"The plugin in '{}' seems to not conform to a supported plugin setup. Closely follow the plugin setup instructions. If the problem persists, please open an issue on github.\",\n directory);\n throw new RuntimeException(\"Invalid file configuration. Fatal.\");\n }\n}", "public class FileReader {\n private static final Logger logger = LoggerFactory.getLogger(\"FileReader\");\n\n private FileReader() {}\n\n public static Stream<String> raw(File path) {\n if (!path.exists()) {\n logger.error(\"File {} does not exist\", path);\n }\n\n CharSource source = Files.asCharSource(path, StandardCharsets.UTF_8);\n return raw(source);\n }\n\n public static Stream<String> raw(CharSource source) {\n try {\n return source.lines();\n } catch (IOException e) {\n if (logger.isDebugEnabled()) {\n e.printStackTrace();\n }\n logger.error(\"Error occurred reading files: {}\", e.getMessage());\n return Stream.empty();\n }\n }\n\n public static Stream<String> read(File path) {\n return raw(path).map(String::trim);\n }\n\n public static Stream<String> read(CharSource source) {\n return raw(source).map(String::trim);\n }\n}" ]
import com.google.common.io.CharSource; import com.google.common.io.Files; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jazzcommunity.development.library.DetectOperatingSystem; import org.jazzcommunity.development.library.FileTools; import org.jazzcommunity.development.library.config.plugin.IniEntry; import org.jazzcommunity.development.library.config.plugin.PluginEntryFactory; import org.jazzcommunity.development.library.file.FileReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.jazzcommunity.development.library.config; public class ConfigReader { private static final Logger logger = LoggerFactory.getLogger("ConfigReader"); public ConfigReader() {} public static String[] windowsTerminal() { return readConfig(FileTools.toAbsolute("jde/user/windows_terminal_emulator.cfg")) .findFirst() .map(s -> s.split(" ")) .orElseGet(() -> new String[] {"cmd", "/K", "start", "powershell", "./run_jetty.ps1"}); } public static String[] linuxTerminal() { return readConfig(FileTools.toAbsolute("jde/user/linux_terminal_emulator.cfg")) .findFirst() .map(s -> s.split(" ")) .orElseGet(() -> new String[] {"gnome-terminal", "--", "./run_jetty.sh"}); } public static String javaPath() { return readConfig(FileTools.toAbsolute("jde/user/java_command.cfg")) .findFirst() .orElseGet(ConfigReader::defaultJava); } /** * This returns a list because we need to have a possible null-check when writing to the jtwig * templates. Otherwise, this method would be a lot cleaner. * * <p>TODO: Move empty check to template */ public static List<String> runtimeParameters() { List<String> lines = readConfig(FileTools.toAbsolute("jde/user/run_time_parameters.cfg")) .collect(Collectors.toList()); return !lines.isEmpty() ? lines : null; } public static Stream<String> flattenConfigs(String directory) { return flattenConfigs(FileTools.toAbsolute(directory)); } public static Stream<String> flattenConfigs(File directory) { File[] files = directory.listFiles(); return Arrays.stream(files) .map(f -> Files.asCharSource(f, StandardCharsets.UTF_8)) .flatMap(FileReader::read) .filter(ConfigReader::isConfigLine); } public static Stream<IniEntry> userConfiguration() { return flattenConfigs(FileTools.toAbsolute("jde/user/workspaces")) .filter(ConfigReader::isConfigLine) .map(File::new)
.map(PluginEntryFactory::getEntry);
3
baratine/lucene-plugin
service/src/test/java/tests/TestSearchCollection.java
[ "public class LuceneEntry\n{\n private int _id;\n private float _score;\n private String _externalId;\n\n public LuceneEntry()\n {\n }\n\n public LuceneEntry(int id)\n {\n this(0, Float.MAX_VALUE);\n }\n\n public LuceneEntry(int id, float score)\n {\n this(id, score, null);\n }\n\n public LuceneEntry(int id, float score, String externalId)\n {\n _id = id;\n _score = score;\n _externalId = externalId;\n }\n\n public int getId()\n {\n return _id;\n }\n\n public void setId(int id)\n {\n _id = id;\n }\n\n public float getScore()\n {\n return _score;\n }\n\n public void setScore(float score)\n {\n _score = score;\n }\n\n public String getExternalId()\n {\n return _externalId;\n }\n\n public void setExternalId(String externalId)\n {\n _externalId = externalId;\n }\n\n @Override public String toString()\n {\n return \"LuceneEntry[\"\n + _id\n + \", \"\n + _score\n + \", '\"\n + _externalId\n + '\\''\n + ']';\n }\n}", "@Service(\"service\")\n@Api(LuceneFacade.class)\n@Path(\"/lucene\")\npublic class LuceneFacadeImpl implements LuceneFacade\n{\n private static final Logger log\n = Logger.getLogger(LuceneFacadeImpl.class.getName());\n\n @Inject\n @Service(\"/lucene-writer\")\n private LuceneWriter _indexWriter;\n\n @Inject\n @Service(\"/lucene-reader\")\n private LuceneReader _indexReader;\n\n private LuceneWriter getLuceneWriter(String id)\n {\n return _indexWriter;\n }\n\n @Override\n @Post(\"/index-file\")\n public void indexFile(@Body(\"collection\") String collection,\n @Body(\"path\") String path,\n Result<Boolean> result)\n throws LuceneException\n {\n checkCollection(collection);\n checkId(path);\n\n getLuceneWriter(path).indexFile(collection, path, result);\n }\n\n @Override\n @Post(\"/index-text\")\n public void indexText(@Body(\"collection\") String collection,\n @Body(\"id\") String id,\n @Body(\"text\") String text,\n Result<Boolean> result) throws LuceneException\n {\n checkCollection(collection);\n checkId(id);\n checkText(text);\n\n getLuceneWriter(id).indexText(collection, id, text, result);\n }\n\n @Override\n @Post(\"/index-map\")\n public void indexMap(@Body(\"collection\") String collection,\n @Body(\"id\") String id,\n @Body Form form,\n Result<Boolean> result) throws LuceneException\n {\n checkCollection(collection);\n checkId(id);\n checkMap(form);\n\n getLuceneWriter(id).indexMap(collection, id, form, result);\n }\n\n @Override\n @Get(\"/search\")\n public void search(@Query(\"collection\") String collection,\n @Query(\"query\") String query,\n @Query(\"limit\") int limit,\n Result<List<LuceneEntry>> result)\n throws LuceneException\n {\n checkCollection(collection);\n checkQuery(query);\n\n _indexReader.search(collection, query, result.of(x -> Arrays.asList(x)));\n }\n\n private void checkCollection(String collection)\n {\n if (collection == null || collection.isEmpty()) {\n throw new LuceneException(\"collection should have a value\");\n }\n }\n\n private void checkId(String id)\n {\n if (id == null || id.isEmpty()) {\n throw new LuceneException(\"id|path should have a value\");\n }\n }\n\n private void checkText(String text)\n {\n if (text == null) {\n throw new LuceneException(\"text should not be null\");\n }\n }\n\n private void checkQuery(String query)\n {\n if (query == null || query.isEmpty()) {\n throw new LuceneException(\"query should have a value\");\n }\n }\n\n private void checkMap(Form map)\n {\n if (map == null) {\n throw new LuceneException(\"map should not be null\");\n }\n }\n\n @Override\n @Post(\"/delete\")\n public void delete(@Body(\"collection\") String collection,\n @Body(\"id\") String id,\n Result<Boolean> result)\n throws LuceneException\n {\n getLuceneWriter(id).delete(collection, id, result);\n }\n\n @Override\n @Post\n public void clear(@Body(\"collection\") String collection, Result<Void> result)\n throws LuceneException\n {\n ResultStreamBuilder<Void> builder = _indexWriter.clear(collection);\n\n builder.collect(ArrayList<Void>::new, (a, b) -> {}, (a, b) -> {\n }).result(result.of((c -> null)));\n }\n}", "@Service(\"/lucene-reader\")\n@Api(LuceneReader.class)\n//@Workers(20)\npublic class LuceneReaderImpl implements LuceneReader\n{\n private final static AtomicLong sequence = new AtomicLong();\n\n private final static Logger log\n = Logger.getLogger(LuceneReaderImpl.class.getName());\n\n @Inject\n private LuceneIndexBean _luceneBean;// = LuceneIndexBean.getInstance();\n\n private BaratineIndexSearcher _searcher;\n\n private QueryParser _queryParser;\n private long _n;\n\n public LuceneReaderImpl()\n {\n _n = sequence.getAndIncrement();\n }\n\n @OnInit\n public void init(Result<Boolean> result)\n {\n log.log(Level.INFO, this + \" init()\");\n\n try {\n _queryParser = _luceneBean.createQueryParser();\n _luceneBean.init();\n\n result.ok(true);\n } catch (Throwable t) {\n log.log(Level.WARNING, \"error creating query parser\", t);\n\n result.fail(t);\n }\n }\n\n private QueryParser getQueryParser()\n {\n return _queryParser;\n }\n\n public void search(String collection,\n String query,\n Result<LuceneEntry[]> results)\n {\n if (log.isLoggable(Level.FINER))\n log.finer(String.format(\"search('%1$s', %2$s, %3$tH:%3$tM:%3$tS,:%3$tL)\",\n collection,\n query,\n new Date()));\n\n LuceneEntry[] entries = searchImpl(collection, query);\n\n if (log.isLoggable(Level.FINER))\n log.log(Level.FINER, String.format(\"%1$s accepting %2$d lucene entries\",\n results,\n entries.length));\n\n results.ok(entries);\n }\n\n public LuceneEntry[] searchImpl(String collection,\n String query)\n {\n QueryParser queryParser = getQueryParser();\n\n try {\n if (_searcher == null) {\n _searcher = _luceneBean.acquireSearcher();\n }\n else if (_searcher.getVersion()\n < _luceneBean.getSearcherSequence().get()) {\n _luceneBean.release(_searcher);\n\n _searcher = _luceneBean.acquireSearcher();\n }\n\n LuceneEntry[] entries = _luceneBean.search(_searcher,\n queryParser,\n collection,\n query,\n 255);\n\n return entries;\n } catch (Throwable e) {\n log.log(Level.WARNING, e.getMessage(), e);\n\n if (e instanceof RuntimeException)\n throw (RuntimeException) e;\n else\n throw new RuntimeException(e);\n }\n }\n\n @AfterBatch\n public void afterBatch() throws IOException\n {\n try {\n if (_searcher != null) {\n _luceneBean.release(_searcher);\n }\n } catch (IOException e) {\n log.log(Level.WARNING, e.getMessage(), e);\n } finally {\n _searcher = null;\n }\n }\n\n @OnDestroy\n public void onDestroy()\n {\n log.log(Level.INFO, String.format(\"%1$s destroy\", this));\n }\n\n @Override\n public String toString()\n {\n return LuceneReaderImpl.class.getSimpleName() + '[' + _n + ']';\n }\n}", "@Service(\"/lucene-writer\")\n@Api(LuceneWriter.class)\npublic class LuceneWriterImpl implements LuceneWriter\n{\n private final static Logger log\n = Logger.getLogger(LuceneWriterImpl.class.getName());\n\n @Inject\n private LuceneIndexBean _luceneBean;// = LuceneIndexBean.getInstance();\n private QueryParser _queryParser;\n\n @Inject\n @Service(\"/searcher-update-service\")\n private SearcherUpdateService _searcherUpdateService;\n\n @OnInit\n public void init(Result<Boolean> result)\n {\n log.log(Level.INFO, this + \" init()\");\n\n try {\n _luceneBean.init();\n\n _queryParser = _luceneBean.createQueryParser();\n\n result.ok(true);\n } catch (Throwable t) {\n log.log(Level.WARNING, \"error creating query parser\", t);\n\n result.fail(t);\n }\n }\n\n @Override\n @Modify\n public void indexFile(String collection, String path, Result<Boolean> result)\n throws LuceneException\n {\n result.ok(_luceneBean.indexFile(collection, path));\n }\n\n @Override\n @Modify\n public void indexText(String collection,\n String id,\n String text,\n Result<Boolean> result) throws LuceneException\n {\n boolean isSuccess = _luceneBean.indexText(collection, id, text);\n\n result.ok(isSuccess);\n }\n\n @Override\n @Modify\n public void indexMap(String collection,\n String id,\n Form map,\n Result<Boolean> result) throws LuceneException\n {\n result.ok(_luceneBean.indexMap(collection, id, map));\n }\n\n @Override\n @OnSave\n public void save(Result<Boolean> result)\n {\n sync();\n\n result.ok(true);\n }\n\n private void sync()\n {\n _searcherUpdateService.sync(Result.<Boolean>ignore());\n }\n\n @Override\n @Modify\n public void delete(String collection, String id, Result<Boolean> result)\n throws LuceneException\n {\n result.ok(_luceneBean.delete(collection, id));\n }\n\n @Override\n public ResultStreamBuilder<Void> clear(String collection)\n throws LuceneException\n {\n throw new AbstractMethodError();\n }\n\n @Modify\n public void clear(String collection, ResultStream<Boolean> result)\n throws LuceneException\n {\n _luceneBean.clear(_queryParser, collection);\n\n result.ok();\n }\n}", "@Service(\"/searcher-update-service\")\n@Api(SearcherUpdateService.class)\npublic class SearcherUpdateServiceImpl implements SearcherUpdateService\n{\n private static final Logger log\n = Logger.getLogger(SearcherUpdateServiceImpl.class.getName());\n\n @Inject\n private LuceneIndexBean _luceneIndexBean;\n private AtomicLong _refreshSequence = new AtomicLong();\n\n @Inject\n @Service(\"timer:///\")\n private Timers _timer;\n private Consumer<Cancel> _alarm;\n\n private SearcherUpdateService _self;\n\n @OnInit\n public void init()\n {\n _self = ServiceRef.current().as(SearcherUpdateService.class);\n }\n\n @Override\n public void sync(Result<Boolean> result)\n {\n result.ok(true);\n }\n\n @AfterBatch\n public void afterBatch()\n {\n log.finer(\"@AfterBatch received\");\n\n refresh(false);\n }\n\n private boolean isTimerSet()\n {\n return _alarm != null;\n }\n\n private void setTimer()\n {\n try {\n if (log.isLoggable(Level.FINER))\n log.finer(String.format(\"setting timer for %1$d ms\",\n _luceneIndexBean.getSoftCommitMaxAge()));\n\n _timer.runAfter(_alarm = h -> onTimer(_refreshSequence.get()),\n _luceneIndexBean.getSoftCommitMaxAge(),\n TimeUnit.MILLISECONDS,\n Result.<Cancel>ignore());\n } catch (RuntimeException e) {\n log.log(Level.WARNING, e.getMessage(), e);\n\n throw e;\n }\n }\n\n private void clearTimer()\n {\n _alarm = null;\n }\n\n public void onTimer(long seq)\n {\n log.finer(\"on timer, updates-count: \" + _luceneIndexBean.getUpdatesCount());\n\n if (seq == _refreshSequence.get()) {\n _self.refresh(true);\n }\n else if (_luceneIndexBean.getUpdatesCount() > 0) {\n setTimer();\n }\n else {\n clearTimer();\n }\n }\n\n public void refresh(boolean isTimer)\n {\n if (isTimer) {\n clearTimer();\n\n refreshImpl();\n }\n else if (_luceneIndexBean.getUpdatesCount()\n >= _luceneIndexBean.getSoftCommitMaxDocs()) {\n refreshImpl();\n }\n else if (!isTimerSet() && _luceneIndexBean.getUpdatesCount() > 0) {\n setTimer();\n }\n }\n\n public void refreshImpl()\n {\n try {\n _refreshSequence.incrementAndGet();\n\n _luceneIndexBean.commit();\n _luceneIndexBean.updateSearcher();\n } catch (Throwable t) {\n log.log(Level.WARNING, t.getMessage(), t);\n }\n }\n}" ]
import java.io.IOException; import java.util.concurrent.ExecutionException; import com.caucho.junit.ConfigurationBaratine; import com.caucho.junit.RunnerBaratine; import com.caucho.junit.ServiceTest; import com.caucho.lucene.LuceneEntry; import com.caucho.lucene.LuceneFacadeImpl; import com.caucho.lucene.LuceneReaderImpl; import com.caucho.lucene.LuceneWriterImpl; import com.caucho.lucene.SearcherUpdateServiceImpl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith;
package tests; /** * title: tests collection */ @RunWith(RunnerBaratine.class) @ServiceTest(LuceneWriterImpl.class) @ServiceTest(LuceneReaderImpl.class)
@ServiceTest(LuceneFacadeImpl.class)
1
ebolwidt/cassowary-java
src/main/java/org/klomp/cassowary/clconstraint/ClLinearInequality.java
[ "public class CL {\n protected final static boolean fDebugOn = false;\n public static boolean fTraceOn = false; // true;\n protected final static boolean fTraceAdded = false;\n protected final static boolean fGC = false;\n\n protected static void debugprint(String s) {\n System.err.println(s);\n }\n\n protected static void traceprint(String s) {\n System.err.println(s);\n }\n\n protected static void fnenterprint(String s) {\n System.err.println(\"* \" + s);\n }\n\n protected static void fnexitprint(String s) {\n System.err.println(\"- \" + s);\n }\n\n public static final byte GEQ = 1;\n public static final byte LEQ = 2;\n\n public static ClLinearExpression Plus(ClLinearExpression e1, ClLinearExpression e2) {\n return e1.plus(e2);\n }\n\n public static ClLinearExpression Plus(ClLinearExpression e1, double e2) {\n return e1.plus(new ClLinearExpression(e2));\n }\n\n public static ClLinearExpression Plus(double e1, ClLinearExpression e2) {\n return (new ClLinearExpression(e1)).plus(e2);\n }\n\n public static ClLinearExpression Plus(ClVariable e1, ClLinearExpression e2) {\n return (new ClLinearExpression(e1)).plus(e2);\n }\n\n public static ClLinearExpression Plus(ClLinearExpression e1, ClVariable e2) {\n return e1.plus(new ClLinearExpression(e2));\n }\n\n public static ClLinearExpression Plus(ClVariable e1, double e2) {\n return (new ClLinearExpression(e1)).plus(new ClLinearExpression(e2));\n }\n\n public static ClLinearExpression Plus(double e1, ClVariable e2) {\n return (new ClLinearExpression(e1)).plus(new ClLinearExpression(e2));\n }\n\n public static ClLinearExpression Minus(ClLinearExpression e1, ClLinearExpression e2) {\n return e1.minus(e2);\n }\n\n public static ClLinearExpression Minus(double e1, ClLinearExpression e2) {\n return (new ClLinearExpression(e1)).minus(e2);\n }\n\n public static ClLinearExpression Minus(ClLinearExpression e1, double e2) {\n return e1.minus(new ClLinearExpression(e2));\n }\n\n public static ClLinearExpression Times(ClLinearExpression e1, ClLinearExpression e2) throws NonlinearExpressionException {\n return e1.times(e2);\n }\n\n public static ClLinearExpression Times(ClLinearExpression e1, ClVariable e2) throws NonlinearExpressionException {\n return e1.times(new ClLinearExpression(e2));\n }\n\n public static ClLinearExpression Times(ClVariable e1, ClLinearExpression e2) throws NonlinearExpressionException {\n return (new ClLinearExpression(e1)).times(e2);\n }\n\n public static ClLinearExpression Times(ClLinearExpression e1, double e2) throws NonlinearExpressionException {\n return e1.times(new ClLinearExpression(e2));\n }\n\n public static ClLinearExpression Times(double e1, ClLinearExpression e2) throws NonlinearExpressionException {\n return (new ClLinearExpression(e1)).times(e2);\n }\n\n public static ClLinearExpression Times(double n, ClVariable clv) throws NonlinearExpressionException {\n return (new ClLinearExpression(clv, n));\n }\n\n public static ClLinearExpression Times(ClVariable clv, double n) throws NonlinearExpressionException {\n return (new ClLinearExpression(clv, n));\n }\n\n public static ClLinearExpression Divide(ClLinearExpression e1, ClLinearExpression e2) throws NonlinearExpressionException {\n return e1.divide(e2);\n }\n\n public static boolean approx(double a, double b) {\n double epsilon = 1.0e-8;\n if (a == 0.0) {\n return (Math.abs(b) < epsilon);\n } else if (b == 0.0) {\n return (Math.abs(a) < epsilon);\n } else {\n return (Math.abs(a - b) < Math.abs(a) * epsilon);\n }\n }\n\n public static boolean approx(ClVariable clv, double b) {\n return approx(clv.getValue(), b);\n }\n\n static boolean approx(double a, ClVariable clv) {\n return approx(a, clv.getValue());\n }\n}", "public class CLInternalError extends CLException {\n\n public CLInternalError(String s) {\n super(s);\n }\n\n}", "public abstract class ClAbstractVariable {\n private String _name;\n\n private static int iVariableNumber;\n\n public ClAbstractVariable(String name) {\n _name = name;\n iVariableNumber++;\n }\n\n public ClAbstractVariable() {\n _name = \"v\" + iVariableNumber;\n iVariableNumber++;\n }\n\n public ClAbstractVariable(long varnumber, String prefix) {\n _name = prefix + varnumber;\n iVariableNumber++;\n }\n\n public String name() {\n return _name;\n }\n\n public void setName(String name) {\n _name = name;\n }\n\n public boolean isDummy() {\n return false;\n }\n\n public abstract boolean isExternal();\n\n public abstract boolean isPivotable();\n\n public abstract boolean isRestricted();\n\n @Override\n public abstract String toString();\n\n public static int numCreated() {\n return iVariableNumber;\n }\n\n}", "public class ClLinearExpression extends CL {\n private double _constant;\n private IdentityHashMap<ClAbstractVariable, ClDouble> _terms;\n\n public ClLinearExpression(ClAbstractVariable clv, double value, double constant) {\n if (CL.fGC)\n System.err.println(\"new ClLinearExpression\");\n\n _constant = constant;\n _terms = new IdentityHashMap<ClAbstractVariable, ClDouble>(1);\n if (clv != null)\n _terms.put(clv, new ClDouble(value));\n }\n\n public ClLinearExpression(double num) {\n this(null, 0, num);\n }\n\n public ClLinearExpression() {\n this(0);\n }\n\n public ClLinearExpression(ClAbstractVariable clv, double value) {\n this(clv, value, 0.0);\n }\n\n public ClLinearExpression(ClAbstractVariable clv) {\n this(clv, 1, 0);\n }\n\n protected ClLinearExpression(double constant, Map<ClAbstractVariable, ClDouble> terms) {\n if (CL.fGC)\n System.err.println(\"clone ClLinearExpression\");\n _constant = constant;\n _terms = new IdentityHashMap<ClAbstractVariable, ClDouble>();\n // need to unalias the ClDouble-s that we clone (do a deep clone)\n for (Map.Entry<ClAbstractVariable, ClDouble> e : terms.entrySet()) {\n _terms.put(e.getKey(), e.getValue().clone());\n }\n }\n\n public ClLinearExpression multiplyMe(double x) {\n _constant *= x;\n\n for (ClDouble cld : _terms.values()) {\n cld.setValue(cld.doubleValue() * x);\n }\n return this;\n }\n\n @Override\n public final ClLinearExpression clone() {\n return new ClLinearExpression(_constant, _terms);\n }\n\n public final ClLinearExpression times(double x) {\n return clone().multiplyMe(x);\n }\n\n public final ClLinearExpression times(ClLinearExpression expr) throws NonlinearExpressionException {\n if (isConstant()) {\n return expr.times(_constant);\n } else if (!expr.isConstant()) {\n throw new NonlinearExpressionException();\n }\n return times(expr._constant);\n }\n\n public final ClLinearExpression plus(ClLinearExpression expr) {\n return clone().addExpression(expr, 1.0);\n }\n\n public final ClLinearExpression plus(ClVariable var) throws NonlinearExpressionException {\n return clone().addVariable(var, 1.0);\n }\n\n public final ClLinearExpression minus(ClLinearExpression expr) {\n return clone().addExpression(expr, -1.0);\n }\n\n public final ClLinearExpression minus(ClVariable var) throws NonlinearExpressionException {\n return clone().addVariable(var, -1.0);\n }\n\n public final ClLinearExpression divide(double x) throws NonlinearExpressionException {\n if (CL.approx(x, 0.0)) {\n throw new NonlinearExpressionException();\n }\n return times(1.0 / x);\n }\n\n public final ClLinearExpression divide(ClLinearExpression expr) throws NonlinearExpressionException {\n if (!expr.isConstant()) {\n throw new NonlinearExpressionException();\n }\n return divide(expr._constant);\n }\n\n public final ClLinearExpression divFrom(ClLinearExpression expr) throws NonlinearExpressionException {\n if (!isConstant() || CL.approx(_constant, 0.0)) {\n throw new NonlinearExpressionException();\n }\n return expr.divide(_constant);\n }\n\n public final ClLinearExpression subtractFrom(ClLinearExpression expr) {\n return expr.minus(this);\n }\n\n // Add n*expr to this expression from another expression expr.\n // Notify the solver if a variable is added or deleted from this\n // expression.\n public final ClLinearExpression addExpression(ClLinearExpression expr, double n, ClAbstractVariable subject, ClTableau solver) {\n incrementConstant(n * expr.constant());\n\n for (Map.Entry<ClAbstractVariable, ClDouble> e : expr.terms().entrySet()) {\n addVariable(e.getKey(), e.getValue().doubleValue() * n, subject, solver);\n }\n return this;\n }\n\n // Add n*expr to this expression from another expression expr.\n public final ClLinearExpression addExpression(ClLinearExpression expr, double n) {\n incrementConstant(n * expr.constant());\n\n for (Map.Entry<ClAbstractVariable, ClDouble> e : expr.terms().entrySet()) {\n addVariable(e.getKey(), e.getValue().doubleValue() * n);\n }\n return this;\n }\n\n public final ClLinearExpression addExpression(ClLinearExpression expr) {\n return addExpression(expr, 1.0);\n }\n\n // Add a term c*v to this expression. If the expression already\n // contains a term involving v, add c to the existing coefficient.\n // If the new coefficient is approximately 0, delete v.\n public final ClLinearExpression addVariable(ClAbstractVariable v, double c) {\n if (fTraceOn)\n fnenterprint(\"addVariable:\" + v + \", \" + c);\n\n ClDouble coeff = _terms.get(v);\n if (coeff != null) {\n double new_coefficient = coeff.doubleValue() + c;\n if (CL.approx(new_coefficient, 0.0)) {\n _terms.remove(v);\n } else {\n coeff.setValue(new_coefficient);\n }\n } else {\n if (!CL.approx(c, 0.0)) {\n _terms.put(v, new ClDouble(c));\n }\n }\n return this;\n }\n\n public final ClLinearExpression addVariable(ClAbstractVariable v) {\n return addVariable(v, 1.0);\n }\n\n public final ClLinearExpression setVariable(ClAbstractVariable v, double c) {\n // assert(c != 0.0);\n ClDouble coeff = _terms.get(v);\n if (coeff != null)\n coeff.setValue(c);\n else\n _terms.put(v, new ClDouble(c));\n return this;\n }\n\n // Add a term c*v to this expression. If the expression already\n // contains a term involving v, add c to the existing coefficient.\n // If the new coefficient is approximately 0, delete v. Notify the\n // solver if v appears or disappears from this expression.\n public final ClLinearExpression addVariable(ClAbstractVariable v, double c, ClAbstractVariable subject, ClTableau solver) {\n // body largely duplicated above\n if (fTraceOn)\n fnenterprint(\"addVariable:\" + v + \", \" + c + \", \" + subject + \", ...\");\n\n ClDouble coeff = _terms.get(v);\n if (coeff != null) {\n double new_coefficient = coeff.doubleValue() + c;\n if (CL.approx(new_coefficient, 0.0)) {\n solver.noteRemovedVariable(v, subject);\n _terms.remove(v);\n } else {\n coeff.setValue(new_coefficient);\n }\n } else {\n if (!CL.approx(c, 0.0)) {\n _terms.put(v, new ClDouble(c));\n solver.noteAddedVariable(v, subject);\n }\n }\n return this;\n }\n\n // Return a pivotable variable in this expression. (It is an error\n // if this expression is constant -- signal ExCLInternalError in\n // that case). Return null if no pivotable variables\n public final ClAbstractVariable anyPivotableVariable() throws CLInternalError {\n if (isConstant()) {\n throw new CLInternalError(\"anyPivotableVariable called on a constant\");\n }\n\n for (ClAbstractVariable clv : _terms.keySet()) {\n if (clv.isPivotable())\n return clv;\n }\n\n // No pivotable variables, so just return null, and let the caller\n // error if needed\n return null;\n }\n\n // Replace var with a symbolic expression expr that is equal to it.\n // If a variable has been added to this expression that wasn't there\n // before, or if a variable has been dropped from this expression\n // because it now has a coefficient of 0, inform the solver.\n // PRECONDITIONS:\n // var occurs with a non-zero coefficient in this expression.\n public final void substituteOut(ClAbstractVariable var, ClLinearExpression expr, ClAbstractVariable subject, ClTableau solver) {\n if (fTraceOn)\n fnenterprint(\"CLE:substituteOut: \" + var + \", \" + expr + \", \" + subject + \", ...\");\n if (fTraceOn)\n traceprint(\"this = \" + this);\n\n double multiplier = _terms.remove(var).doubleValue();\n incrementConstant(multiplier * expr.constant());\n\n for (Map.Entry<ClAbstractVariable, ClDouble> e : expr.terms().entrySet()) {\n ClAbstractVariable clv = e.getKey();\n double coeff = e.getValue().doubleValue();\n ClDouble d_old_coeff = _terms.get(clv);\n if (d_old_coeff != null) {\n double old_coeff = d_old_coeff.doubleValue();\n double newCoeff = old_coeff + multiplier * coeff;\n if (CL.approx(newCoeff, 0.0)) {\n solver.noteRemovedVariable(clv, subject);\n _terms.remove(clv);\n } else {\n d_old_coeff.setValue(newCoeff);\n }\n } else {\n // did not have that variable already\n _terms.put(clv, new ClDouble(multiplier * coeff));\n solver.noteAddedVariable(clv, subject);\n }\n }\n if (fTraceOn)\n traceprint(\"Now this is \" + this);\n }\n\n // This linear expression currently represents the equation\n // oldSubject=self. Destructively modify it so that it represents\n // the equation newSubject=self.\n //\n // Precondition: newSubject currently has a nonzero coefficient in\n // this expression.\n //\n // NOTES\n // Suppose this expression is c + a*newSubject + a1*v1 + ... + an*vn.\n //\n // Then the current equation is\n // oldSubject = c + a*newSubject + a1*v1 + ... + an*vn.\n // The new equation will be\n // newSubject = -c/a + oldSubject/a - (a1/a)*v1 - ... - (an/a)*vn.\n // Note that the term involving newSubject has been dropped.\n public final void changeSubject(ClAbstractVariable old_subject, ClAbstractVariable new_subject) {\n ClDouble cld = _terms.get(old_subject);\n if (cld != null)\n cld.setValue(newSubject(new_subject));\n else\n _terms.put(old_subject, new ClDouble(newSubject(new_subject)));\n }\n\n // This linear expression currently represents the equation self=0. Destructively modify it so\n // that subject=self represents an equivalent equation.\n //\n // Precondition: subject must be one of the variables in this expression.\n // NOTES\n // Suppose this expression is\n // c + a*subject + a1*v1 + ... + an*vn\n // representing\n // c + a*subject + a1*v1 + ... + an*vn = 0\n // The modified expression will be\n // subject = -c/a - (a1/a)*v1 - ... - (an/a)*vn\n // representing\n // subject = -c/a - (a1/a)*v1 - ... - (an/a)*vn\n //\n // Note that the term involving subject has been dropped.\n // Returns the reciprocal, so changeSubject can use it, too\n public final double newSubject(ClAbstractVariable subject) {\n if (fTraceOn)\n fnenterprint(\"newSubject:\" + subject);\n ClDouble coeff = _terms.remove(subject);\n double reciprocal = 1.0 / coeff.doubleValue();\n multiplyMe(-reciprocal);\n return reciprocal;\n }\n\n // Return the coefficient corresponding to variable var, i.e.,\n // the 'ci' corresponding to the 'vi' that var is:\n // v1*c1 + v2*c2 + .. + vn*cn + c\n public final double coefficientFor(ClAbstractVariable var) {\n ClDouble coeff = _terms.get(var);\n if (coeff != null)\n return coeff.doubleValue();\n else\n return 0.0;\n }\n\n public final double constant() {\n return _constant;\n }\n\n public final void set_constant(double c) {\n _constant = c;\n }\n\n public final Map<ClAbstractVariable, ClDouble> terms() {\n return _terms;\n }\n\n public final void incrementConstant(double c) {\n _constant += c;\n }\n\n public final boolean isConstant() {\n return _terms.size() == 0;\n }\n\n @Override\n public final String toString() {\n StringBuffer bstr = new StringBuffer();\n Iterator<ClAbstractVariable> e = _terms.keySet().iterator();\n\n if (!CL.approx(_constant, 0.0) || _terms.size() == 0) {\n bstr.append(_constant);\n } else {\n if (_terms.size() == 0) {\n return bstr.toString();\n }\n ClAbstractVariable clv = e.next();\n ClDouble coeff = _terms.get(clv);\n bstr.append(coeff.toString() + \"*\" + clv.toString());\n }\n for (; e.hasNext();) {\n ClAbstractVariable clv = e.next();\n ClDouble coeff = _terms.get(clv);\n bstr.append(\" + \" + coeff.toString() + \"*\" + clv.toString());\n }\n return bstr.toString();\n }\n\n public final static ClLinearExpression Plus(ClLinearExpression e1, ClLinearExpression e2) {\n return e1.plus(e2);\n }\n\n public final static ClLinearExpression Minus(ClLinearExpression e1, ClLinearExpression e2) {\n return e1.minus(e2);\n }\n\n public final static ClLinearExpression Times(ClLinearExpression e1, ClLinearExpression e2)\n throws NonlinearExpressionException {\n return e1.times(e2);\n }\n\n public final static ClLinearExpression Divide(ClLinearExpression e1, ClLinearExpression e2)\n throws NonlinearExpressionException {\n return e1.divide(e2);\n }\n\n public final static boolean FEquals(ClLinearExpression e1, ClLinearExpression e2) {\n return e1 == e2;\n }\n\n}", "public class ClStrength {\n public static final ClStrength required = new ClStrength(\"<Required>\", 1000, 1000, 1000);\n\n public static final ClStrength strong = new ClStrength(\"strong\", 1.0, 0.0, 0.0);\n\n public static final ClStrength medium = new ClStrength(\"medium\", 0.0, 1.0, 0.0);\n\n public static final ClStrength weak = new ClStrength(\"weak\", 0.0, 0.0, 1.0);\n\n private String _name;\n\n private ClSymbolicWeight _symbolicWeight;\n\n public ClStrength(String name, ClSymbolicWeight symbolicWeight) {\n _name = name;\n _symbolicWeight = symbolicWeight;\n }\n\n public ClStrength(String name, double w1, double w2, double w3) {\n this(name, new ClSymbolicWeight(w1, w2, w3));\n }\n\n public boolean isRequired() {\n return (this == required);\n }\n\n @Override\n public String toString() {\n return getName() + (!isRequired() ? (\":\" + getSymbolicWeight()) : \"\");\n }\n\n public ClSymbolicWeight getSymbolicWeight() {\n return _symbolicWeight;\n }\n\n public String getName() {\n return _name;\n }\n\n}", "public class ClVariable extends ClAbstractVariable {\n\n private double _value;\n\n private Object _attachedObject;\n\n public ClVariable(String name, double value) {\n super(name);\n _value = value;\n }\n\n public ClVariable(String name) {\n super(name);\n _value = 0.0;\n }\n\n public ClVariable(double value) {\n _value = value;\n }\n\n public ClVariable() {\n _value = 0.0;\n }\n\n public ClVariable(long number, String prefix, double value) {\n super(number, prefix);\n _value = value;\n }\n\n public ClVariable(long number, String prefix) {\n super(number, prefix);\n _value = 0.0;\n }\n\n @Override\n public boolean isDummy() {\n return false;\n }\n\n @Override\n public boolean isExternal() {\n return true;\n }\n\n @Override\n public boolean isPivotable() {\n return false;\n }\n\n @Override\n public boolean isRestricted() {\n return false;\n }\n\n @Override\n public String toString() {\n return \"[\" + name() + \":\" + _value + \"]\";\n }\n\n public final double getValue() {\n return _value;\n }\n\n // change the value held -- should *not* use this if the variable is\n // in a solver -- instead use addEditVar() and suggestValue() interface\n public final void setValue(double value) {\n _value = value;\n }\n\n // permit overriding in subclasses in case something needs to be\n // done when the value is changed by the solver\n // may be called when the value hasn't actually changed -- just\n // means the solver is setting the external variable\n public void change_value(double value) {\n _value = value;\n }\n\n public void setAttachedObject(Object o) {\n _attachedObject = o;\n }\n\n public Object getAttachedObject() {\n return _attachedObject;\n }\n\n}" ]
import org.klomp.cassowary.CL; import org.klomp.cassowary.CLInternalError; import org.klomp.cassowary.ClAbstractVariable; import org.klomp.cassowary.ClLinearExpression; import org.klomp.cassowary.ClStrength; import org.klomp.cassowary.ClVariable;
/* * Cassowary Incremental Constraint Solver * Original Smalltalk Implementation by Alan Borning * * Java Implementation by: * Greg J. Badros * Erwin Bolwidt * * (C) 1998, 1999 Greg J. Badros and Alan Borning * (C) Copyright 2012 Erwin Bolwidt * * See the file LICENSE for legal details regarding this software */ package org.klomp.cassowary.clconstraint; public class ClLinearInequality extends ClLinearConstraint { public ClLinearInequality(ClLinearExpression cle, ClStrength strength, double weight) { super(cle, strength, weight); } public ClLinearInequality(ClLinearExpression cle, ClStrength strength) { super(cle, strength); } public ClLinearInequality(ClLinearExpression cle) { super(cle); } public ClLinearInequality(ClVariable clv1, byte op_enum, ClVariable clv2, ClStrength strength, double weight) throws CLInternalError { super(new ClLinearExpression(clv2), strength, weight); if (op_enum == CL.GEQ) { _expression.multiplyMe(-1.0); _expression.addVariable(clv1); } else if (op_enum == CL.LEQ) { _expression.addVariable(clv1, -1.0); } else // the operator was invalid throw new CLInternalError("Invalid operator in ClLinearInequality constructor"); } public ClLinearInequality(ClVariable clv1, byte op_enum, ClVariable clv2, ClStrength strength) throws CLInternalError { this(clv1, op_enum, clv2, strength, 1.0); } public ClLinearInequality(ClVariable clv1, byte op_enum, ClVariable clv2) throws CLInternalError { this(clv1, op_enum, clv2, ClStrength.required, 1.0); } public ClLinearInequality(ClVariable clv, byte op_enum, double val, ClStrength strength, double weight) throws CLInternalError { super(new ClLinearExpression(val), strength, weight); if (op_enum == CL.GEQ) { _expression.multiplyMe(-1.0); _expression.addVariable(clv); } else if (op_enum == CL.LEQ) { _expression.addVariable(clv, -1.0); } else // the operator was invalid throw new CLInternalError("Invalid operator in ClLinearInequality constructor"); } public ClLinearInequality(ClVariable clv, byte op_enum, double val, ClStrength strength) throws CLInternalError { this(clv, op_enum, val, strength, 1.0); } public ClLinearInequality(ClVariable clv, byte op_enum, double val) throws CLInternalError { this(clv, op_enum, val, ClStrength.required, 1.0); } public ClLinearInequality(ClLinearExpression cle1, byte op_enum, ClLinearExpression cle2, ClStrength strength, double weight) throws CLInternalError { super(cle2.clone(), strength, weight); if (op_enum == CL.GEQ) { _expression.multiplyMe(-1.0); _expression.addExpression(cle1); } else if (op_enum == CL.LEQ) { _expression.addExpression(cle1, -1.0); } else // the operator was invalid throw new CLInternalError("Invalid operator in ClLinearInequality constructor"); } public ClLinearInequality(ClLinearExpression cle1, byte op_enum, ClLinearExpression cle2, ClStrength strength) throws CLInternalError { this(cle1, op_enum, cle2, strength, 1.0); } public ClLinearInequality(ClLinearExpression cle1, byte op_enum, ClLinearExpression cle2) throws CLInternalError { this(cle1, op_enum, cle2, ClStrength.required, 1.0); }
public ClLinearInequality(ClAbstractVariable clv, byte op_enum, ClLinearExpression cle, ClStrength strength, double weight)
2
gto76/fun-photo-time
src/main/java/si/gto76/funphototime/enums/MultipleParameterFilter.java
[ "public class MyInternalFrame extends JInternalFrame \n\t\t\t\t\t\timplements InternalFrameListener /*, MouseMotionListener*/ {\n\t\n\tprivate static final long serialVersionUID = -1665181775406001910L;\n\t\n\t// TODO: This is true for metal L&F, probably not for others,\n\t// and will thus probably effect tile operation to overlap frames a little in other L&Fls.\n\t// I guess java has those numbers somewhere, I just didn't realy look for them.\n\tpublic static final int BORDER_WIDTH = 10;\n\tpublic static final int BORDER_HEIGHT = 32;\n\t\n\tprivate ImageIcon icon;\n\tprivate BufferedImage originalImg; //image that is not resized\n\t\n\t//kolk okvirjev je ze bilo odprtih\n\tprivate static int openFrameCount = 0;\n\tprivate int zoom = 100;\n\tprivate String fileName;\n\tprivate int fileNameInstanceNo;\n\t\n\t//public long sizeOfOriginalImage;\n\n\tThread thread;\n\tpublic final FunPhotoTimeFrame mainFrame;\n\n\n\t/*\n\t * CONSTRUCTORS\n\t */\n\t\n\t// Used when importing from other frame\n\tpublic MyInternalFrame(FunPhotoTimeFrame mainFrame, BufferedImage imgIn, MyInternalFrame frameIn) {\n\t\tsuper(\"\", true, true, true, true);\n\t\tthis.mainFrame = mainFrame;\n\t\tthis.setTitle(fileName);\n\t\t//če ni frameIn zoom 100% zaenkrat ostane brez originalne slike\n\t\t//(ker jo more en od FilterThreadov, ki teče v ozadju še narest)\n\t if ( frameIn.getZoom() == 100 ) {\n\t \toriginalImg = imgIn;\n\t }\n\t this.zoom = frameIn.zoom;\n\t fileName = frameIn.getFileName(); \n\t init(mainFrame, imgIn);\n\t}\n\t\n\t// Used when importing from file\n\tpublic MyInternalFrame(FunPhotoTimeFrame mainFrame, BufferedImage imgIn, String title) {\n\t\tsuper(\"\", true, true, true, true);\n\t\tthis.mainFrame = mainFrame;\n\t\toriginalImg = imgIn;\n\t\tthis.zoom = 100;\n\t this.fileName = title;\n\t init(mainFrame, imgIn);\n\t}\n\t\n\t// Initializes the window components\n\tprivate void init(FunPhotoTimeFrame mainFrame, BufferedImage imgIn) {\n\t\tfileNameInstanceNo = ++openFrameCount;\n\t\trefreshTitle();\n\t\t\n\t icon = new ImageIcon((Image)imgIn, \"description\");\n\t JLabel label = new JLabel(icon);\n\t label.setBackground(Conf.BACKGROUND_COLOR);\n\t label.setOpaque(true);\n JScrollPane scrollPane = new JScrollPane(label);\n\n scrollPane.getVerticalScrollBar().setUnitIncrement(Conf.SCROLL_PANE_SPEED); \n scrollPane.getHorizontalScrollBar().setUnitIncrement(Conf.SCROLL_PANE_SPEED);\n \n this.getContentPane().add(scrollPane, BorderLayout.CENTER);\n\t setLocation(Conf.X_OFFSET*(openFrameCount%10), Conf.Y_OFFSET*(openFrameCount%10));\n\t \n\t pack();\n\t\taddInternalFrameListener(this);\n\n\t\t/*\n\t\t * KEY SHORTCUTS\n\t\t */\n\t\t// Get the KeyStroke for our hot key\n \tKeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK, true);\n \t// Get the input map for our component\n \t// In this case we are interested in key strokes in the focussed window\n \tInputMap inputMap = this.getInputMap(JComponent.WHEN_FOCUSED);\n \t// Map the key stroke to our \"action key\" (see below)\n \tinputMap.put(key, \"my_action\");\n \t// Get the action map for our component\n \tActionMap actionMap = this.getActionMap();\n \t// Add the required action listener to out action map\n \tactionMap.put(\"my_action\", new AbstractAction() {\n\t\t\tprivate static final long serialVersionUID = 4883602111122331080L;\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n \ttry {\n\t\t\t\t\tsetClosed(true);\n\t\t\t\t} catch (PropertyVetoException e1) {\n\t\t\t\t\te1.printStackTrace();\n\t\t\t\t}\n }\n \t});\n\t}\n\t\n\t\n\t/*\n\t * FUNCTIONS\n\t */\n\t\n\tpublic Dimension getOriginalImageSize() {\n\t\tif (originalImg != null) {\n\t\t\treturn new Dimension(\n\t\t\t\toriginalImg.getWidth(), \n\t\t\t\toriginalImg.getHeight()\n\t\t\t);\n\t\t}\n\t\tBufferedImage img = getImg();\n\t\tdouble lengthFactor = 100.0 / zoom;\n\t\treturn new Dimension(\n\t\t\t(int) (img.getWidth() * lengthFactor), \n\t\t\t(int) (img.getHeight() * lengthFactor)\n\t\t);\n\t}\n\t\n\tpublic long getOriginalImageMemoryFootprint() {\n\t\treturn (long) (Utility.getSizeOfImage(getImg()) * Utility.getSurfaceAreaFactorForZoom(zoom));\n\t}\n\n\tpublic long getMemoryFootprint() { \n\t\tlong sum = Utility.getSizeOfImage(getImg());\n\t\tif (zoom != 100) {\n\t\t\tsum += sum * Utility.getSurfaceAreaFactorForZoom(zoom);\n\t\t}\n\t\treturn sum;\n\t}\n\n\tpublic void anounceThread(Thread thread) {\n\t\tthis.thread = thread;\n\t}\n\n\tpublic String getFileName() {\n\t\treturn fileName;\n }\n\t\n\tpublic String getFileNameWithInstanceNo() {\n\t\treturn fileName+\" #\"+fileNameInstanceNo;\n\t}\n\t\n\tpublic BufferedImage getImg() { //zoomed, displayed img\n\t\tBufferedImage bf = (BufferedImage) icon.getImage();\n \treturn bf;\n }\n \n public BufferedImage getOriginalImg() {\n\t\treturn originalImg;\n }\n \n public void setImg(BufferedImage imgIn) {\n \ticon.setImage((Image) imgIn);\n }\n \n public void setOriginalImg(BufferedImage imgIn) {\n \toriginalImg = imgIn;\n }\n \n public int getZoom() {\n \treturn zoom;\n }\n \n /// ZOOM /////////////////////////////////////////////////\n public void setZoom(int cent) {\n \twaitForThread();\n \tif ( originalImg != null && cent < 100 && cent > 0 && cent != zoom) {\n \t\tzoom = cent;\n \t\trefreshImage();\n\t }\n }\n \n public void zoomOut() { //za 50 posto\n \twaitForThread();\n \tif ( originalImg != null && (zoom / 2) > 0) {\n \t\tzoom /= 2;\n \t\trefreshImage();\n \t}\n\t}\n\t\n\tpublic void zoomOut(int cent) { //za cent\n \twaitForThread();\n \tif (cent < 1) return;\n \tif ( originalImg != null && zoom - cent > 0 ) {\n \t\tzoom -= cent;\n \t\trefreshImage();\n \t}\n\t}\n\t\n\tpublic void zoomIn() { //za 50 posto\n \twaitForThread();\n\t\tif ( originalImg != null && zoom * 2 < 100 ) {\n\t \tzoom *= 2;\n\t \trefreshImage();\n\t \treturn;\n\t }\n\t if ( originalImg != null && zoom * 2 == 100) {\n\t \tactualSize();\n\t }\n\t}\n\t\n\tpublic void zoomIn(int cent) { //za cent\n\t\twaitForThread();\n\t\tif (cent < 1) return;\n\t\tif ( originalImg != null && zoom + cent < 100 ) {\n\t \tzoom += cent;\n\t \trefreshImage();\n\t \treturn;\n\t }\n\t if ( originalImg != null && zoom + cent == 100) {\n\t \tactualSize();\n\t }\n\t}\n\t\n\tpublic void actualSize() {\n \twaitForThread();\n\t\tif ( originalImg != null && zoom!=100 ) {\n\t\t\tzoom = 100;\n\t\t\trefreshImage();\n\t\t}\n\t}\n\t\n\t/// REFRESHMENTS ////////////////////////////////////////////\n\tprivate void refreshImage() {\n\t\tboolean isMax = this.isMaximum;\n\t\tif (zoom == 100) {\n\t\t\ticon.setImage(originalImg);\n\t\t} else {\n\t\t\ticon.setImage(Zoom.out(originalImg, zoom));\n\t\t}\n\t\trefreshTitle();\n \tpack();\n\n \tif (isMax) {\n \t\ttry {\n\t\t\t\tthis.setMaximum(true);\n\t\t\t} catch (PropertyVetoException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n \t}\n\t}\n\t\n\tprivate void refreshTitle() {\n\t\tString title;\n\t\tif (zoom == 100) {\n\t\t\ttitle = fileName+\" #\"+fileNameInstanceNo;\n\t\t}\n\t\telse {\n\t\t\ttitle = fileName+\" #\"+fileNameInstanceNo+\" / zoom: \"+zoom+\"%\";\n\t\t}\n\t\tthis.setTitle(title);\n\t}\n\t/////////////////////////////////////////////////\n\t\n\tpublic void waitForThread() {\n\t\tif ( thread != null ) {\n\t\t\t//se sprehodimo skoz celo hierarhijo da prodemo do glavnega frejma\n\t\t\t//Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR);\n\t\t\t//JRootPane mainFrame = (JRootPane) this.getParent().getParent().getParent();\n\t\t\t//HourglassThread hourglassThread = new HourglassThread(mainFrame);\n\t\t\t//mainFrame.setCursor(hourglassCursor);\n\t\t\ttry {\n\t\t\t\tthread.join();\n\t\t\t}\n\t\t\tcatch ( InterruptedException f ) {}\n\t\t\t//Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);\n\t\t\t//mainFrame.setCursor(hourglassCursor);\n\t\t}\n\t}\n\t\n\tpublic String toString() {\n \treturn getTitle();\n }\n\n\t/*\n\t * INTERNAL FRAME EVENTS\n\t */\n\n\tpublic void internalFrameClosing(InternalFrameEvent e) {\n\t}\n\n public void internalFrameClosed(InternalFrameEvent e) {\n\t\t//prekine nit ko se zepre\n\t\t/*\n \tif ( thread != null ) {\n\t\t\tthread.interrupt();\n\t\t\ttry {\n\t\t\t\tthread.join();\n\t\t\t}\n\t\t\tcatch ( InterruptedException f ) { \n\t\t\t}\n\t\t}\n\t\t*/\n \t\n \tmainFrame.lastClosedIntrnalFrame = this;\n \t\n\t\t//odstrani okno iz view menija\n\t\tmainFrame.removeInternalFrameReference(this); \n\t\tmainFrame.desktop.selectFrame(true); // Garbage collection hack.\n\t}\n\n public void internalFrameOpened(InternalFrameEvent e) {\n\t}\n\n public void internalFrameIconified(InternalFrameEvent e) {\n\t}\n\n public void internalFrameDeiconified(InternalFrameEvent e) {\n\t}\n\n public void internalFrameActivated(InternalFrameEvent e) {\n \tmainFrame.vmu.refreshItems(mainFrame);\n\t}\n\n public void internalFrameDeactivated(InternalFrameEvent e) {\n\t}\n\n\n /*\n * MOUSE MOTION LISTENER\n */\n\n //hand move tool:\n \n /*\n\t@Override\n\tpublic void mouseMoved(MouseEvent arg0) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void mouseDragged(MouseEvent e){\n\t\tif(SwingUtilities.isLeftMouseButton(e)){\n\t\t\t//make sure the point is within bounds of image\n\t\t\tint l_x, l_y;\n\t\t\tPoint tempPoint = new Point(e.getPoint());\n\t\t\tl_x = source.getWidth();\n\t\t\tl_y = source.getHeight();\n\t\t\tif( tempPoint.x > l_x)\n\t\t\t\ttempPoint.x = l_x;\n\t\t\tif( tempPoint.y > l_y)\n\t\t\t\ttempPoint.y = l_y;\n\t\t\tsel.updateSelectionArea(tempPoint);\n\t\t\trepaint(); \n\t\t}\n\t\telse if(SwingUtilities.isRightMouseButton(e)){\n\t\t\tJViewport viewport = parent.getViewport();\n\t\t\tJScrollBar jsbY= parent.getVerticalScrollBar();\n\t\t\tJScrollBar jsbX= parent.getHorizontalScrollBar();\n\t\t\ttry{\n\t\t\t\tPoint newPosition = parent.getMousePosition();\n\t\t\t\t\n\t\t\t\tint dx, dy;\n\t\t\t\tdx = panAnchor.x - newPosition.x;\n\t\t\t\tdy = panAnchor.y - newPosition.y;\n\t\t\t\t\n\t\t\t\t// update pan anchor\n\t\t\t\tpanAnchor.x = newPosition.x;\n\t\t\t\tpanAnchor.y = newPosition.y;\n\t\t\t\t\n\t\t\t\tint x, y;\n\t\t\t\tx = viewport.getViewPosition().x + dx;\n\t\t\t\ty = viewport.getViewPosition().y + dy;\n\t\t\t\t\n\t\t\t\tif ( x < 1 || this.getDims().width < parent.getVisibleRect().width + jsbY.getWidth())\n\t\t\t\t\tx = 1;\n\t\t\t\telse if( x > (this.getDims().width - parent.getVisibleRect().width + jsbY.getWidth()))\n\t\t\t\t\tx = this.getDims().width - parent.getVisibleRect().width + jsbY.getWidth();\n\t\t\t\t\n\t\t\t\tif ( y < 1 || this.getDims().height < parent.getVisibleRect().height + jsbX.getHeight())\n\t\t\t\t\ty = 1;\n\t\t\t\telse if( y > (this.getDims().height - parent.getVisibleRect().height + jsbX.getHeight()))\n\t\t\t\t\ty = this.getDims().height - parent.getVisibleRect().height + jsbX.getHeight();\n\t\t\t\t\n\t\t\t\tviewport.setViewPosition(new Point(x,y));\n\t\t\t}\n\t\t\tcatch(Exception e2){}\n\t\t\t\n\t\t\trepaint();\n\t\t}\n\t\t\n\t}\n\t*/\n\t\n}", "public class Utility {\n\t\n\tpublic static BufferedImage getHistogramImage (double[] histogram) {\n //naredi sliko histograma\n\t\tfinal int height = 150;\n \tfinal Color red = Color.red;\n \tfinal Color white = Color.white;\n\n \tBufferedImage img = \n\t\t\tnew BufferedImage(256, height, BufferedImage.TYPE_INT_ARGB);\n\t\tGraphics2D g2 = img.createGraphics();\n \t\n \tint height2;\n \tg2.setPaint(white);\n \tg2.fill (new Rectangle2D.Double(0, 0, 256, height));\n \tg2.setPaint(red);\n \t//Gre cez vseh 256 polj od histograma[] in narise navpicno crto\n \tfor (int i = 0; i < 256; i++) {\n \t\theight2 = height - (int)(histogram[i] * height * Conf.HISTOGRAM_VERTICAL_ZOOM);\n \t\tg2.draw(new Line2D.Double(i, height, i, height2));\n\t\t}\n\t\treturn img;\n\t}\n\t\n\tpublic static double[] getHistogram(BufferedImage img) {\n \t//Vrne array z vrednostmi v procentih (0 - 1, koliko je vsake svetlosti\n \t//na sliki, zacensi s cisto crno (0) in naprej do ciste bele (255)\n \tint height = img.getHeight();\n\t\tint width = img.getWidth();\n\t\tint rgb;\n\t\tdouble pixelWeight = 1.0 / (height * width);\n\t\tdouble[] histogram = new double[256];\n\t\t\n\t\tfor (int i = 0; i < height; i++) {\n\t\t\tfor (int j = 0; j < width; j++) {\n\t\t\t\trgb = img.getRGB(j, i);\n\t\t\t\tint bw = Filters.getGrayLevel2(rgb);\n\t\t\t\thistogram[bw]+= pixelWeight;\n\t\t\t}\n\t\t}\n\t\treturn histogram;\t\n\t} \n\t\n\tpublic static BufferedImage declareNewBufferedImage(int x, int y) {\n \t//naredi novo prazno sliko zeljene velikosti\n\t\tBufferedImage imgOut = new BufferedImage(x, \n\t\t\t\t\t\t\t\ty, \n\t\t\t\t\t\t\t\tBufferedImage.TYPE_INT_RGB );\n\t\treturn imgOut;\n }\n\t\n\tpublic static BufferedImage declareNewBufferedImage(BufferedImage img) {\n \t//naredi novo prazno sliko enake velikosti \n \t//kot jo ima tista, ki jo podamo kot argument\n \tImageTypeSpecifier its = new ImageTypeSpecifier(img);\n\t\tBufferedImage imgOut = new BufferedImage(img.getWidth(), \n\t\t\t\t\t\t\t\timg.getHeight(), \n\t\t\t\t\t\t\t\tits.getBufferedImageType() );\n\t\treturn imgOut;\n }\n \n public static BufferedImage declareNewBufferedImage(BufferedImage img1, BufferedImage img2) {\n \tint h1 = img1.getHeight();\n\t\tint w1 = img1.getWidth();\n\t\tint h2 = img2.getHeight();\n\t\tint w2 = img2.getWidth();\n\t\tint height = (h1 < h2) ? h1 : h2;\n\t\tint width = (w1 < w2) ? w1 : w2;\n \t//uzame sirino od ozje slike in visino od nizje\n\t\t//taksnih dimenzij je potem izhodna slika\n \tImageTypeSpecifier its = new ImageTypeSpecifier(img1);\n\t\tBufferedImage imgOut = new BufferedImage(width, height, \n\t\t\t\t\t\t\t\tits.getBufferedImageType() );\n\t\treturn imgOut;\n }\n \n public static void copyBufferedImage(BufferedImage imgOrig, BufferedImage imgCopy) {\n \tint height = imgCopy.getHeight();\n\t\tint width = imgCopy.getWidth();\n\t\tint rgb;\n\t\t\n\t\tfor (int i = 0; i < height; i++) {\n\t\t\tfor (int j = 0; j < width; j++) {\n\t\t\t\trgb = imgOrig.getRGB(j, i);\n\t\t\t\timgCopy.setRGB(j, i, rgb);\n\t\t\t}\n\t\t}\n }\n \n public static BufferedImage declareNewBufferedImageAndCopy(BufferedImage img) {\n \tBufferedImage imgOut = declareNewBufferedImage(img);\n \tcopyBufferedImage(img, imgOut);\n \treturn imgOut;\n }\n \n public static String histogramToString(double[] histogram) {\n\t\tStringBuilder sb = new StringBuilder();\n \tfor (int i = 0; i < histogram.length; i++) {\n \t\tsb.append(i + \" \" + histogram[i] + \"\\t\");\n\t\t}\n \treturn sb.toString();\n\t}\n \n public static void initializeArray(int[] arr) {\n \tfor (int i = 0; i < arr.length; i++) {\n \t\tarr[i] = 0;\n \t}\n }\n \n public static void initializeArray(int[][] arr) {\n \tfor (int i = 0; i < arr.length; i++) {\n \t\tfor (int j = 0; j < arr[0].length; j++) {\n \t\t\tarr[i][j] = 0;\n \t\t}\n \t}\n }\n \n public static BufferedImage waitForOriginalImage(MyInternalFrame frame) {\n\t\twhile (frame.getOriginalImg() == null) {\n\t\t\ttry {\n\t\t\t\tTimeUnit.MILLISECONDS.sleep(Conf.ORIGINAL_IMAGE_WAITING_INTERVAL_MSEC);\n\t\t\t} catch (InterruptedException e1) {\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\t\t}\n return frame.getOriginalImg();\n }\n \n public static Point centerTheCenter(Point center, int width, int Height) {\n \treturn new Point(\n \t\tcenter.x - width/2,\n \t\tcenter.y - width/2\n \t); \t\n }\n\n\tpublic static long getSizeOfImage(BufferedImage imgIn) {\n\t\treturn (long) ( imgIn.getHeight() * imgIn.getWidth() * 3 );\n\t}\n\t\n\tpublic static long getSizeOfImage(ImageIcon imgIn) {\n\t\treturn (long) ( imgIn.getIconHeight() * imgIn.getIconWidth() * 3 );\n\t}\n\t\n\tpublic static double getSurfaceAreaFactorForZoom(int zoom) {\n\t\treturn Math.pow(1.0/(zoom/100.0), 2);\n\t}\n\t\n}", "public class ColorsDialog extends FilterDialog\n\t\t\t\t\t\t\timplements FilterDialogThatReturnsInts {\n\t// R, G and B sliders\n\tprotected JSlider[] sld = new JSlider[3];\n\t\n\tpublic ColorsDialog( MyInternalFrame selectedFrame) {\n\t\tsuper(selectedFrame, \"RGB\", BoxLayout.Y_AXIS, 300, 205);\n\t\t\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tsld[i] = new JSlider(JSlider.HORIZONTAL,\n\t \t\t\t\t\t\t-100, 100, 0);\n\t sld[i].setMajorTickSpacing(100);\n\t\t\tsld[i].setMinorTickSpacing(10);\n\t\t\tsld[i].setPaintTicks(true);\n\t\t\tsld[i].setPaintLabels(true);\n\t\t\t\n\t\t\tsld[i].addChangeListener(this);\n\t\t\t//super.addComponent(sld[i]);\n\t\t\t//sld[i].fireStateChanged();\n\t\t}\n\t\tsuper.addComponents(sld);\n\t}\n\n\tpublic void stateChanged(ChangeEvent e) {\n\t\tactionWhenStateChanged();\n\t}\n\n\tprotected void actionWhenStateChanged() {\n\t\tstopActiveThread();\n\t\tfilterThread = new ColorsThread(imgIn, imgOut, getInts(), selectedFrame);\n\t}\n \n public int[] getInts() {\n \tint[] values = new int[3];\n \tfor (int i = 0; i < 3; i++) {\n \t\tvalues[i] = sld[i].getValue(); \n \t}\n \treturn values;\n\t}\n \n}", "public interface FilterDialogThatReturnsInts {\n\tpublic int[] getInts();\n\tpublic boolean wasCanceled();\n\tpublic BufferedImage getProcessedImage();\n\tpublic void resetOriginalImage();\n}", "public class HistogramStretchingDialog extends FilterDialog\n\t\t\t\t\t\t\t\timplements ChangeListener, FilterDialogThatReturnsInts {\n\n private BufferedImage histogramImg1, histogramImg2;\n private JPanel p;\n private ImageIcon icon;\n private JLabel label;\n private JSlider sld1, sld2;\n private JOptionPane op;\n private JDialog dlg;\n \n //TODO 2 Ce ga zaprem z x-om pride do napake\n public HistogramStretchingDialog( MyInternalFrame selectedFrame, BufferedImage histogramImg ) {\n \tsuper(selectedFrame, \"Histogram\"); \n \t\n \thistogramImg1 = histogramImg;\n histogramImg2 = Utility.declareNewBufferedImageAndCopy(histogramImg1);\n \t\n \tp = new JPanel();\n \tp.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));\n \t\n icon = new ImageIcon((Image)histogramImg2, \"description\");\n \n label = new JLabel(icon);\n label.setHorizontalAlignment(JLabel.CENTER);\n\t\tp.add(label);\n \n sld1 = new JSlider(JSlider.HORIZONTAL, 0, 255, 0);\n sld1.addChangeListener(this);\n p.add(sld1);\n \n sld2 = new JSlider(JSlider.HORIZONTAL, 0, 255, 255);\n sld2.addChangeListener(this);\n p.add(sld2);\n \n op = new JOptionPane(p,\n \t\tJOptionPane.PLAIN_MESSAGE,\n \t\tJOptionPane.OK_CANCEL_OPTION);\n \t\n \tdlg = op.createDialog(\"Histogram\"); //(this, \"Histogram\");\n \tdlg.setSize(300, 264);\n \tdlg.setLocation(MyDialog.location);\n \tdlg.setAlwaysOnTop(true);\n \tdlg.setVisible(true);\n \tdlg.dispose();\n }\n \n public int[] getInts() {\n \t//Vrne vrednosti slajderjev\n \tint[] value = new int[2];\n \tvalue[0] = sld1.getValue();\n \tvalue[1] = sld2.getValue();\n \treturn value;\n }\n \n public boolean wasCanceled() {\n \t//pogleda ce je uporabnik zaprl dialog z cancel gumbom\n \tMyDialog.location = dlg.getLocation();\n \tint option = ((Integer)op.getValue()).intValue();\n\t\tif (option == JOptionPane.CANCEL_OPTION) return true;\n\t\telse return false;\n }\n \n public void stateChanged(ChangeEvent e) {\n \tprocessPicture(); \t\n \t// Poslusa slajderja in sproti izrisuje pomozne crte na histogram\n \t//Kako zdej od tle spreminjat ikono v labelu v dialogu?\n histogramImg2 = Utility.declareNewBufferedImageAndCopy(histogramImg1);\n \n int val1 = sld1.getValue();\n int val2 = sld2.getValue();\n \n //Da se ne morta prekrizat\n if ( val1 >= val2 ) {\n \tsld1.setValue(val2);\n }\n if ( val2 <= val1 ) {\n \tsld2.setValue(val1);\n }\n \n\t\tGraphics2D g2 = histogramImg2.createGraphics();\n \tfinal Color black = Color.black;\n \tfinal int height = 400;\n \tint height2 = 0;\n \t\n \tg2.setPaint(black);\n \t\n \t//da rise crtkani crti\n \tfinal float dash1[] = {10.0f};\n\t final BasicStroke dashed = new BasicStroke(1.0f, \n\t BasicStroke.CAP_BUTT, \n\t BasicStroke.JOIN_MITER, \n\t 10.0f, dash1, 0.0f);\n\t\tg2.setStroke(dashed);\n\t\t\n \tg2.draw(new Line2D.Double(val1, height, val1, height2));\n \tg2.draw(new Line2D.Double(val2, height, val2, height2));\n\t\t\n\t\ticon.setImage((Image) histogramImg2);\n \n dlg.repaint(100, 0, 0, 1000, 1000);\n \n } \n \n\tprotected void processPicture() {\n\t\tstopActiveThread();\n\t\t//nato naredi novo nit\n\t\tfilterThread = new HistogramStretchingThread(imgIn, imgOut, getInts(), selectedFrame);\n\t}\n\n}", "public class ColorsThread2 extends FilterThread2 {\n\t\n\tprivate int[] value;\n\t\n\tpublic ColorsThread2( BufferedImage imgIn, int[] value, MyInternalFrame selectedFrame ) {\n\t\tsuper(imgIn, selectedFrame);\n\t\tthis.value = value;\n\t}\n\t\t\n\tprotected int filtriraj(int rgb) {\n\t\treturn Filters.getColors(rgb, value);\n\t}\n\n}", "public class HistogramStretchingThread2 extends FilterThread2 {\n\tprivate int[] bounds; // Probably not neaded\n\tprivate int[] mappingArray;\n\t\n\tpublic HistogramStretchingThread2( BufferedImage imgIn, int[] bounds, MyInternalFrame selectedFrame ) {\n\t\tsuper(imgIn, selectedFrame);\n\t\tthis.bounds = bounds;\n\t\tmappingArray = Filters.calculateMappingArrayForStretching(bounds[0], bounds[1]);\n\t}\n\t\t\n\tprotected int filtriraj(int rgb) {\n\t\t// Wait till mappingArray is calculated\n\t\tif ( mappingArray == null ) { \n\t\t\tmappingArray = Filters.calculateMappingArrayForStretching(bounds[0], bounds[1]);\n\t\t}\n\t\treturn Filters.getHistogramMapping(rgb, mappingArray);\n\t}\n\n}" ]
import java.awt.image.BufferedImage; import si.gto76.funphototime.MyInternalFrame; import si.gto76.funphototime.Utility; import si.gto76.funphototime.dialogs.ColorsDialog; import si.gto76.funphototime.dialogs.FilterDialogThatReturnsInts; import si.gto76.funphototime.dialogs.HistogramStretchingDialog; import si.gto76.funphototime.filterthreads2.ColorsThread2; import si.gto76.funphototime.filterthreads2.HistogramStretchingThread2;
package si.gto76.funphototime.enums; public enum MultipleParameterFilter { HISTOGRAM_STRETCHING, COLOR_BALANCE; public FilterDialogThatReturnsInts getDialog(MyInternalFrame frame) { switch (this) { case HISTOGRAM_STRETCHING: double[] histogram = Utility.getHistogram(frame.getImg()); BufferedImage histogramImg = Utility.getHistogramImage(histogram);
return new HistogramStretchingDialog(frame, histogramImg);
4
protolambda/blocktopograph
app/src/main/java/com/protolambda/blocktopograph/WorldActivity.java
[ "public enum Dimension {\n\n OVERWORLD(0, \"overworld\", \"Overworld\", 16, 16, 128, 1, MapType.OVERWORLD_SATELLITE),\n NETHER(1, \"nether\", \"Nether\", 16, 16, 128, 8, MapType.NETHER),\n END(2, \"end\", \"End\", 16, 16, 128, 1, MapType.END_SATELLITE);//mcpe: SOON^TM /jk\n\n public final int id;\n public final int chunkW, chunkL, chunkH;\n public final int dimensionScale;\n public final String dataName, name;\n public final MapType defaultMapType;\n\n Dimension(int id, String dataName, String name, int chunkW, int chunkL, int chunkH, int dimensionScale, MapType defaultMapType){\n this.id = id;\n this.dataName = dataName;\n this.name = name;\n this.chunkW = chunkW;\n this.chunkL = chunkL;\n this.chunkH = chunkH;\n this.dimensionScale = dimensionScale;\n this.defaultMapType = defaultMapType;\n }\n\n private static Map<String, Dimension> dimensionMap = new HashMap<>();\n\n static {\n for(Dimension dimension : Dimension.values()){\n dimensionMap.put(dimension.dataName, dimension);\n }\n }\n\n public static Dimension getDimension(String dataName){\n if(dataName == null) return null;\n return dimensionMap.get(dataName.toLowerCase());\n }\n\n public static Dimension getDimension(int id){\n for(Dimension dimension : values()){\n if(dimension.id == id) return dimension;\n }\n return null;\n }\n\n}", "public class AbstractMarker implements NamedBitmapProviderHandle {\n\n public final int x, y, z;\n public final Dimension dimension;\n\n public final NamedBitmapProvider namedBitmapProvider;\n\n public final boolean isCustom;\n\n public AbstractMarker(int x, int y, int z, Dimension dimension, NamedBitmapProvider namedBitmapProvider, boolean isCustom) {\n this.x = x;\n this.y = y;\n this.z = z;\n this.dimension = dimension;\n this.namedBitmapProvider = namedBitmapProvider;\n this.isCustom = isCustom;\n }\n\n public int getChunkX(){\n return x >> 4;\n }\n\n public int getChunkZ(){\n return z >> 4;\n }\n\n public MarkerImageView view;\n\n public MarkerImageView getView(Context context) {\n if(view != null) return view;\n view = new MarkerImageView(context, this);\n this.loadIcon(view);\n return view;\n }\n\n /**\n * Loads the provided bitmap into the image view.\n * @param iconView The view to load the icon into.\n */\n public void loadIcon(ImageView iconView) {\n iconView.setImageBitmap(this.getNamedBitmapProvider().getBitmap());\n }\n\n @NonNull\n @Override\n public NamedBitmapProvider getNamedBitmapProvider() {\n return namedBitmapProvider;\n }\n\n public AbstractMarker copy(int x, int y, int z, Dimension dimension) {\n return new AbstractMarker(x, y, z, dimension, this.namedBitmapProvider, this.isCustom);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n AbstractMarker that = (AbstractMarker) o;\n\n return x == that.x\n && y == that.y\n && z == that.z\n && dimension == that.dimension\n && (namedBitmapProvider != null\n ? namedBitmapProvider.equals(that.namedBitmapProvider)\n : that.namedBitmapProvider == null);\n\n }\n\n @Override\n public int hashCode() {\n int result = Vector3.intHash(x, y, z);\n result = 31 * result + (dimension != null ? dimension.hashCode() : 0);\n result = 31 * result + (namedBitmapProvider != null ? namedBitmapProvider.hashCode() : 0);\n return result;\n }\n}", "public class NBTConstants {\n\n public enum NBTType {\n\n END(0, EndTag.class, \"EndTag\"),\n BYTE(1, ByteTag.class, \"ByteTag\"),\n SHORT(2, ShortTag.class, \"ShortTag\"),\n INT(3, IntTag.class, \"IntTag\"),\n LONG(4, LongTag.class, \"LongTag\"),\n FLOAT(5, FloatTag.class, \"FloatTag\"),\n DOUBLE(6, DoubleTag.class, \"DoubleTag\"),\n BYTE_ARRAY(7, ByteArrayTag.class, \"ByteArrayTag\"),\n STRING(8, StringTag.class, \"StringTag\"),\n LIST(9, ListTag.class, \"ListTag\"),\n COMPOUND(10, CompoundTag.class, \"CompoundTag\"),\n INT_ARRAY(11, IntArrayTag.class, \"IntArrayTag\"),\n\n //Is this one even used?!? Maybe used in mods?\n SHORT_ARRAY(100, ShortArrayTag.class, \"ShortArrayTag\");\n\n public final int id;\n public final Class<? extends Tag> tagClazz;\n public final String displayName;\n\n static public Map<Integer, NBTType> typesByID = new HashMap<>();\n static public Map<Class<? extends Tag>, NBTType> typesByClazz = new HashMap<>();\n\n NBTType(int id, Class<? extends Tag> tagClazz, String displayName){\n this.id = id;\n this.tagClazz = tagClazz;\n this.displayName = displayName;\n }\n\n //not all NBT types are meant to be created in an editor, the END tag for example.\n public static String[] editorOptions_asString;\n public static NBTType[] editorOptions_asType = new NBTType[]{\n BYTE,\n SHORT,\n INT,\n LONG,\n FLOAT,\n DOUBLE,\n BYTE_ARRAY,\n STRING,\n LIST,\n COMPOUND,\n INT_ARRAY,\n SHORT_ARRAY\n };\n\n static {\n\n\n int len = editorOptions_asType.length;\n editorOptions_asString = new String[len];\n for(int i = 0; i < len; i++){\n editorOptions_asString[i] = editorOptions_asType[i].displayName;\n }\n\n\n //fill maps\n for(NBTType type : NBTType.values()){\n typesByID.put(type.id, type);\n typesByClazz.put(type.tagClazz, type);\n }\n }\n\n public static Tag newInstance(String tagName, NBTType type){\n switch (type){\n case END: return new EndTag();\n case BYTE: return new ByteTag(tagName, (byte) 0);\n case SHORT: return new ShortTag(tagName, (short) 0);\n case INT: return new IntTag(tagName, 0);\n case LONG: return new LongTag(tagName, 0L);\n case FLOAT: return new FloatTag(tagName, 0f);\n case DOUBLE: return new DoubleTag(tagName, 0.0);\n case BYTE_ARRAY: return new ByteArrayTag(tagName, null);\n case STRING: return new StringTag(tagName, \"\");\n case LIST: return new ListTag(tagName, new ArrayList<Tag>());\n case COMPOUND: return new CompoundTag(tagName, new ArrayList<Tag>());\n default: return null;\n }\n }\n\n }\n\n public static final Charset CHARSET = Charset.forName(\"UTF-8\");\n\n}", "public class NBTChunkData extends ChunkData {\n\n public List<Tag> tags = new ArrayList<>();\n\n public final ChunkTag dataType;\n\n public NBTChunkData(Chunk chunk, ChunkTag dataType) {\n super(chunk);\n this.dataType = dataType;\n }\n\n public void load() throws WorldData.WorldDBLoadException, WorldData.WorldDBException, IOException {\n loadFromByteArray(chunk.worldData.getChunkData(chunk.x, chunk.z, dataType, this.chunk.dimension, (byte) 0, false));\n }\n\n public void loadFromByteArray(byte[] data) throws IOException {\n if (data != null && data.length > 0) this.tags = DataConverter.read(data);\n }\n\n public void write() throws WorldData.WorldDBException, IOException {\n if (this.tags == null) this.tags = new ArrayList<>();\n byte[] data = DataConverter.write(this.tags);\n this.chunk.worldData.writeChunkData(this.chunk.x, this.chunk.z, this.dataType, this.chunk.dimension, (byte) 0, false, data);\n }\n\n @Override\n public void createEmpty() {\n if(this.tags == null) this.tags = new ArrayList<>();\n this.tags.add(new IntTag(\"Placeholder\", 42));\n }\n\n}", "public class MapFragment extends Fragment {\n\n private WorldActivityInterface worldProvider;\n\n private MCTileProvider minecraftTileProvider;\n\n private TileView tileView;\n\n //procedural markers can be iterated while other threads add things to it;\n // iterating performance is not really affected because of the small size;\n public CopyOnWriteArraySet<AbstractMarker> proceduralMarkers = new CopyOnWriteArraySet<>();\n\n public Set<AbstractMarker> staticMarkers = new HashSet<>();\n\n public AbstractMarker spawnMarker;\n public AbstractMarker localPlayerMarker;\n\n\n\n\n @Override\n public void onPause() {\n super.onPause();\n\n //pause drawing the map\n this.tileView.pause();\n }\n\n @Override\n public void onStart() {\n super.onStart();\n\n getActivity().setTitle(this.worldProvider.getWorld().getWorldDisplayName());\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.MAPFRAGMENT_OPEN);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n //resume drawing the map\n this.tileView.resume();\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.MAPFRAGMENT_RESUME);\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n }\n\n\n public DimensionVector3<Float> getMultiPlayerPos(String dbKey) throws Exception {\n try {\n WorldData wData = worldProvider.getWorld().getWorldData();\n wData.openDB();\n byte[] data = wData.db.get(dbKey.getBytes(NBTConstants.CHARSET));\n if(data == null) throw new Exception(\"no data!\");\n final CompoundTag player = (CompoundTag) DataConverter.read(data).get(0);\n\n ListTag posVec = (ListTag) player.getChildTagByKey(\"Pos\");\n if (posVec == null || posVec.getValue() == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (posVec.getValue().size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n IntTag dimensionId = (IntTag) player.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n Dimension dimension = Dimension.getDimension(dimensionId.getValue());\n if(dimension == null) dimension = Dimension.OVERWORLD;\n\n return new DimensionVector3<>(\n (float) posVec.getValue().get(0).getValue(),\n (float) posVec.getValue().get(1).getValue(),\n (float) posVec.getValue().get(2).getValue(),\n dimension);\n\n } catch (Exception e) {\n Log.e(e.getMessage());\n\n Exception e2 = new Exception(\"Could not find \"+dbKey);\n e2.setStackTrace(e.getStackTrace());\n throw e2;\n }\n }\n\n public DimensionVector3<Float> getPlayerPos() throws Exception {\n try {\n WorldData wData = worldProvider.getWorld().getWorldData();\n wData.openDB();\n byte[] data = wData.db.get(World.SpecialDBEntryType.LOCAL_PLAYER.keyBytes);\n\n final CompoundTag player = data != null\n ? (CompoundTag) DataConverter.read(data).get(0)\n : (CompoundTag) worldProvider.getWorld().level.getChildTagByKey(\"Player\");\n\n ListTag posVec = (ListTag) player.getChildTagByKey(\"Pos\");\n if (posVec == null || posVec.getValue() == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (posVec.getValue().size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n IntTag dimensionId = (IntTag) player.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n Dimension dimension = Dimension.getDimension(dimensionId.getValue());\n if(dimension == null) dimension = Dimension.OVERWORLD;\n\n return new DimensionVector3<>(\n (float) posVec.getValue().get(0).getValue(),\n (float) posVec.getValue().get(1).getValue(),\n (float) posVec.getValue().get(2).getValue(),\n dimension);\n\n } catch (Exception e) {\n Log.e(e.toString());\n\n Exception e2 = new Exception(\"Could not find player.\");\n e2.setStackTrace(e.getStackTrace());\n throw e2;\n }\n }\n\n public DimensionVector3<Integer> getSpawnPos() throws Exception {\n try {\n CompoundTag level = this.worldProvider.getWorld().level;\n int spawnX = ((IntTag) level.getChildTagByKey(\"SpawnX\")).getValue();\n int spawnY = ((IntTag) level.getChildTagByKey(\"SpawnY\")).getValue();\n int spawnZ = ((IntTag) level.getChildTagByKey(\"SpawnZ\")).getValue();\n if(spawnY == 256){\n TerrainChunkData data = new ChunkManager(\n this.worldProvider.getWorld().getWorldData(), Dimension.OVERWORLD)\n .getChunk(spawnX >> 4, spawnZ >> 4)\n .getTerrain((byte) 0);\n if(data.load2DData()) spawnY = data.getHeightMapValue(spawnX % 16, spawnZ % 16) + 1;\n }\n return new DimensionVector3<>( spawnX, spawnY, spawnZ, Dimension.OVERWORLD);\n } catch (Exception e){\n throw new Exception(\"Could not find spawn\");\n }\n }\n\n public static class MarkerListAdapter extends ArrayAdapter<AbstractMarker> {\n\n\n MarkerListAdapter(Context context, List<AbstractMarker> objects) {\n super(context, 0, objects);\n }\n\n @NonNull\n @Override\n public View getView(int position, View convertView, @NonNull ViewGroup parent) {\n\n RelativeLayout v = (RelativeLayout) convertView;\n\n if (v == null) {\n LayoutInflater vi;\n vi = LayoutInflater.from(getContext());\n v = (RelativeLayout) vi.inflate(R.layout.marker_list_entry, parent, false);\n }\n\n AbstractMarker m = getItem(position);\n\n if (m != null) {\n TextView name = (TextView) v.findViewById(R.id.marker_name);\n TextView xz = (TextView) v.findViewById(R.id.marker_xz);\n ImageView icon = (ImageView) v.findViewById(R.id.marker_icon);\n\n name.setText(m.getNamedBitmapProvider().getBitmapDisplayName());\n String xzStr = String.format(Locale.ENGLISH, \"x: %d, y: %d, z: %d\", m.x, m.y, m.z);\n xz.setText(xzStr);\n\n m.loadIcon(icon);\n\n }\n\n return v;\n }\n\n }\n\n public enum MarkerTapOption {\n\n TELEPORT_LOCAL_PLAYER(R.string.teleport_local_player),\n REMOVE_MARKER(R.string.remove_custom_marker);\n\n public final int stringId;\n\n MarkerTapOption(int id){\n this.stringId = id;\n }\n\n }\n\n public String[] getMarkerTapOptions(){\n MarkerTapOption[] values = MarkerTapOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n\n //TODO handle savedInstance...\n\n\n View rootView = inflater.inflate(R.layout.map_fragment, container, false);\n RelativeLayout worldContainer = (RelativeLayout) rootView.findViewById(R.id.world_tileview_container);\n assert worldContainer != null;\n\n /*\n GPS button: moves camera to player position\n */\n FloatingActionButton fabGPSPlayer = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_player);\n assert fabGPSPlayer != null;\n fabGPSPlayer.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n if(tileView == null) throw new Exception(\"No map available.\");\n\n DimensionVector3<Float> playerPos = getPlayerPos();\n\n Snackbar.make(tileView,\n getString(R.string.something_at_xyz_dim_float, getString(R.string.player),\n playerPos.x, playerPos.y, playerPos.z, playerPos.dimension.name),\n Snackbar.LENGTH_SHORT)\n .setAction(\"Action\", null).show();\n\n if(playerPos.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(playerPos.dimension.defaultMapType, playerPos.dimension);\n }\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_PLAYER);\n\n frameTo((double) playerPos.x, (double) playerPos.z);\n\n } catch (Exception e){\n e.printStackTrace();\n Snackbar.make(view, R.string.failed_find_player, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n /*\n GPS button: moves camera to spawn\n */\n FloatingActionButton fabGPSSpawn = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_spawn);\n assert fabGPSSpawn != null;\n fabGPSSpawn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n DimensionVector3<Integer> spawnPos = getSpawnPos();\n\n Snackbar.make(tileView,\n getString(R.string.something_at_xyz_dim_int, getString(R.string.spawn),\n spawnPos.x, spawnPos.y, spawnPos.z, spawnPos.dimension.name),\n Snackbar.LENGTH_SHORT)\n .setAction(\"Action\", null).show();\n\n if(spawnPos.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(spawnPos.dimension.defaultMapType, spawnPos.dimension);\n }\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_SPAWN);\n\n frameTo((double) spawnPos.x, (double) spawnPos.z);\n\n } catch (Exception e){\n e.printStackTrace();\n Snackbar.make(view, R.string.failed_find_spawn, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n\n final Activity activity = getActivity();\n\n if(activity == null){\n new Exception(\"MapFragment: activity is null, cannot set worldProvider!\").printStackTrace();\n return null;\n }\n try {\n //noinspection ConstantConditions\n worldProvider = (WorldActivityInterface) activity;\n } catch (ClassCastException e){\n new Exception(\"MapFragment: activity is not an worldprovider, cannot set worldProvider!\", e).printStackTrace();\n return null;\n }\n\n\n //show the toolbar if the fab menu is opened\n FloatingActionMenu fabMenu = (FloatingActionMenu) rootView.findViewById(R.id.fab_menu);\n fabMenu.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {\n @Override\n public void onMenuToggle(boolean opened) {\n if(opened) worldProvider.showActionBar();\n else worldProvider.hideActionBar();\n }\n });\n\n\n\n FloatingActionButton fabGPSMarker = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_marker);\n assert fabGPSMarker != null;\n fabGPSMarker.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n Collection<AbstractMarker> markers = worldProvider.getWorld().getMarkerManager().getMarkers();\n\n if(markers.isEmpty()){\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n TextView msg = new TextView(activity);\n float dpi = activity.getResources().getDisplayMetrics().density;\n msg.setPadding((int)(19*dpi), (int)(5*dpi), (int)(14*dpi), (int)(5*dpi));\n msg.setMaxLines(20);\n msg.setText(R.string.no_custom_markers);\n builder.setView(msg)\n .setTitle(R.string.no_custom_markers_title)\n .setCancelable(true)\n .setNeutralButton(android.R.string.ok, null)\n .show();\n } else {\n\n AlertDialog.Builder markerDialogBuilder = new AlertDialog.Builder(activity);\n markerDialogBuilder.setIcon(R.drawable.ic_place);\n markerDialogBuilder.setTitle(R.string.go_to_a_marker_list);\n\n final MarkerListAdapter arrayAdapter = new MarkerListAdapter(activity, new ArrayList<>(markers));\n\n markerDialogBuilder.setNegativeButton(android.R.string.cancel, null);\n\n markerDialogBuilder.setAdapter(\n arrayAdapter,\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n AbstractMarker m = arrayAdapter.getItem(which);\n if(m == null) return;\n\n Snackbar.make(tileView,\n activity.getString(R.string.something_at_xyz_dim_int,\n m.getNamedBitmapProvider().getBitmapDisplayName(),\n m.x, m.y, m.z, m.dimension.name),\n Snackbar.LENGTH_SHORT)\n .setAction(\"Action\", null).show();\n\n if(m.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(m.dimension.defaultMapType, m.dimension);\n }\n\n frameTo((double) m.x, (double) m.z);\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_MARKER);\n }\n });\n markerDialogBuilder.show();\n }\n\n } catch (Exception e){\n Snackbar.make(view, e.getMessage(), Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n\n /*\n GPS button: moves camera to player position\n */\n FloatingActionButton fabGPSMultiplayer = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_multiplayer);\n assert fabGPSMultiplayer != null;\n fabGPSMultiplayer.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(final View view) {\n\n if (tileView == null){\n Snackbar.make(view, R.string.no_map_available, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n\n Snackbar.make(tileView,\n R.string.searching_for_players,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n\n //this can take some time... ...do it in the background\n (new AsyncTask<Void, Void, String[]>(){\n\n @Override\n protected String[] doInBackground(Void... arg0) {\n try {\n return worldProvider.getWorld().getWorldData().getPlayers();\n } catch (Exception e){\n return null;\n }\n }\n\n protected void onPostExecute(final String[] players) {\n getActivity().runOnUiThread(new Runnable() {\n @Override\n public void run() {\n\n if(players == null){\n Snackbar.make(view, R.string.failed_to_retrieve_player_data, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n\n if(players.length == 0){\n Snackbar.make(view, R.string.no_multiplayer_data_found, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n\n\n\n //NBT tag type spinner\n final Spinner spinner = new Spinner(activity);\n ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(activity,\n android.R.layout.simple_spinner_item, players);\n\n spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(spinnerArrayAdapter);\n\n\n //wrap layout in alert\n new AlertDialog.Builder(activity)\n .setTitle(R.string.go_to_player)\n .setView(spinner)\n .setPositiveButton(R.string.go_loud, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n\n //new tag type\n int spinnerIndex = spinner.getSelectedItemPosition();\n String playerKey = players[spinnerIndex];\n\n try {\n DimensionVector3<Float> playerPos = getMultiPlayerPos(playerKey);\n\n Snackbar.make(tileView,\n getString(R.string.something_at_xyz_dim_float,\n playerKey,\n playerPos.x,\n playerPos.y,\n playerPos.z,\n playerPos.dimension.name),\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_MULTIPLAYER);\n\n if(playerPos.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(playerPos.dimension.defaultMapType, playerPos.dimension);\n }\n\n frameTo((double) playerPos.x, (double) playerPos.z);\n\n } catch (Exception e){\n Snackbar.make(view, e.getMessage(), Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n\n }\n })\n //or alert is cancelled\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n }\n });\n }\n\n }).execute();\n\n }\n });\n\n\n /*\n GPS button: moves camera to player position\n */\n FloatingActionButton fabGPSCoord = (FloatingActionButton) rootView.findViewById(R.id.fab_menu_gps_coord);\n assert fabGPSCoord != null;\n fabGPSCoord.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n if(tileView == null) throw new Exception(\"No map available.\");\n\n View xzForm = LayoutInflater.from(activity).inflate(R.layout.xz_coord_form, null);\n final EditText xInput = (EditText) xzForm.findViewById(R.id.x_input);\n xInput.setText(\"0\");\n final EditText zInput = (EditText) xzForm.findViewById(R.id.z_input);\n zInput.setText(\"0\");\n\n //wrap layout in alert\n new AlertDialog.Builder(activity)\n .setTitle(R.string.go_to_coordinate)\n .setView(xzForm)\n .setPositiveButton(R.string.go_loud, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n int inX, inZ;\n try{\n inX = Integer.parseInt(xInput.getText().toString());\n } catch (NullPointerException | NumberFormatException e){\n Toast.makeText(activity, R.string.invalid_x_coordinate,Toast.LENGTH_LONG).show();\n return;\n }\n try{\n inZ = Integer.parseInt(zInput.getText().toString());\n } catch (NullPointerException | NumberFormatException e){\n Toast.makeText(activity, R.string.invalid_z_coordinate,Toast.LENGTH_LONG).show();\n return;\n }\n\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.GPS_COORD);\n\n frameTo((double) inX, (double) inZ);\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n } catch (Exception e){\n Snackbar.make(view, e.getMessage(), Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n });\n\n\n\n try {\n Entity.loadEntityBitmaps(activity.getAssets());\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n try {\n Block.loadBitmaps(activity.getAssets());\n } catch (IOException e) {\n e.printStackTrace();\n }\n try{\n CustomIcon.loadCustomBitmaps(activity.getAssets());\n } catch (IOException e){\n e.printStackTrace();\n }\n\n\n\n\n /*\n Create tile view\n */\n this.tileView = new TileView(activity) {\n\n @Override\n public void onLongPress(MotionEvent event) {\n\n Dimension dimension = worldProvider.getDimension();\n\n // 1 chunk per tile on scale 1.0\n int pixelsPerBlockW_unscaled = MCTileProvider.TILESIZE / dimension.chunkW;\n int pixelsPerBlockL_unscaled = MCTileProvider.TILESIZE / dimension.chunkL;\n\n float pixelsPerBlockScaledW = pixelsPerBlockW_unscaled * this.getScale();\n float pixelsPerBlockScaledL = pixelsPerBlockL_unscaled * this.getScale();\n\n\n double worldX = ((( this.getScrollX() + event.getX()) / pixelsPerBlockScaledW) - MCTileProvider.HALF_WORLDSIZE) / dimension.dimensionScale;\n double worldZ = ((( this.getScrollY() + event.getY()) / pixelsPerBlockScaledL) - MCTileProvider.HALF_WORLDSIZE) / dimension.dimensionScale;\n\n MapFragment.this.onLongClick(worldX, worldZ);\n }\n };\n\n this.tileView.setId(ViewID.generateViewId());\n\n //set the map-type\n tileView.getDetailLevelManager().setLevelType(worldProvider.getMapType());\n\n /*\n Add tile view to main layout\n */\n\n //add world view to its container in the main layout\n worldContainer.addView(tileView);\n\n\n /*\n Create tile(=bitmap) provider\n */\n this.minecraftTileProvider = new MCTileProvider(worldProvider);\n\n\n\n /*\n Set the bitmap-provider of the tile view\n */\n this.tileView.setBitmapProvider(this.minecraftTileProvider);\n\n\n /*\n Change tile view settings\n */\n\n this.tileView.setBackgroundColor(0xFF494E8E);\n\n // markers should align to the coordinate along the horizontal center and vertical bottom\n tileView.setMarkerAnchorPoints(-0.5f, -1.0f);\n\n this.tileView.defineBounds(\n -1.0,\n -1.0,\n 1.0,\n 1.0\n );\n\n this.tileView.setSize(MCTileProvider.viewSizeW, MCTileProvider.viewSizeL);\n\n for(MapType mapType : MapType.values()){\n this.tileView.addDetailLevel(0.0625f, \"0.0625\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);// 1/(1/16)=16 chunks per tile\n this.tileView.addDetailLevel(0.125f, \"0.125\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);\n this.tileView.addDetailLevel(0.25f, \"0.25\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);\n this.tileView.addDetailLevel(0.5f, \"0.5\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);\n this.tileView.addDetailLevel(1f, \"1\", MCTileProvider.TILESIZE, MCTileProvider.TILESIZE, mapType);// 1/1=1 chunk per tile\n\n }\n\n this.tileView.setScale(0.5f);\n\n\n boolean framedToPlayer = false;\n\n //TODO multi-thread this\n try {\n\n DimensionVector3<Float> playerPos = getPlayerPos();\n float x = playerPos.x, y = playerPos.y, z = playerPos.z;\n Log.d(\"Placed player marker at: \"+x+\";\"+y+\";\"+z+\" [\"+playerPos.dimension.name+\"]\");\n localPlayerMarker = new AbstractMarker((int) x, (int) y, (int) z,\n playerPos.dimension, new CustomNamedBitmapProvider(Entity.PLAYER, \"~local_player\"), false);\n this.staticMarkers.add(localPlayerMarker);\n addMarker(localPlayerMarker);\n\n if(localPlayerMarker.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(localPlayerMarker.dimension.defaultMapType, localPlayerMarker.dimension);\n }\n\n frameTo((double) x, (double) z);\n framedToPlayer = true;\n\n } catch (Exception e){\n e.printStackTrace();\n Log.d(\"Failed to place player marker. \"+e.toString());\n }\n\n\n try {\n DimensionVector3<Integer> spawnPos = getSpawnPos();\n\n spawnMarker = new AbstractMarker(spawnPos.x, spawnPos.y, spawnPos.z, spawnPos.dimension,\n new CustomNamedBitmapProvider(CustomIcon.SPAWN_MARKER, \"Spawn\"), false);\n this.staticMarkers.add(spawnMarker);\n addMarker(spawnMarker);\n\n if(!framedToPlayer){\n\n if(spawnMarker.dimension != worldProvider.getDimension()){\n worldProvider.changeMapType(spawnMarker.dimension.defaultMapType, spawnMarker.dimension);\n }\n\n frameTo((double) spawnPos.x, (double) spawnPos.z);\n }\n\n } catch (Exception e){\n //no spawn defined...\n if(!framedToPlayer) frameTo(0.0, 0.0);\n\n }\n\n\n\n\n\n\n tileView.getMarkerLayout().setMarkerTapListener(new MarkerLayout.MarkerTapListener() {\n @Override\n public void onMarkerTap(View view, int tapX, int tapY) {\n if(!(view instanceof MarkerImageView)){\n Log.d(\"Markertaplistener found a marker that is not a MarkerImageView! \"+view.toString());\n return;\n }\n\n final AbstractMarker marker = ((MarkerImageView) view).getMarkerHook();\n if(marker == null){\n Log.d(\"abstract marker is null! \"+view.toString());\n return;\n }\n\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n builder\n .setTitle(String.format(getString(R.string.marker_info), marker.getNamedBitmapProvider().getBitmapDisplayName(), marker.getNamedBitmapProvider().getBitmapDataName(), marker.x, marker.y, marker.z, marker.dimension))\n .setItems(getMarkerTapOptions(), new DialogInterface.OnClickListener() {\n @SuppressWarnings(\"RedundantCast\")\n @SuppressLint(\"SetTextI18n\")\n public void onClick(DialogInterface dialog, int which) {\n\n final MarkerTapOption chosen = MarkerTapOption.values()[which];\n\n switch (chosen){\n case TELEPORT_LOCAL_PLAYER: {\n try {\n final EditableNBT playerEditable = worldProvider.getEditablePlayer();\n if (playerEditable == null)\n throw new Exception(\"Player is null\");\n\n Iterator playerIter = playerEditable.getTags().iterator();\n if (!playerIter.hasNext())\n throw new Exception(\"Player DB entry is empty!\");\n\n //db entry consists of one compound tag\n final CompoundTag playerTag = (CompoundTag) playerIter.next();\n\n ListTag posVec = (ListTag) playerTag.getChildTagByKey(\"Pos\");\n\n if (posVec == null) throw new Exception(\"No \\\"Pos\\\" specified\");\n\n final List<Tag> playerPos = posVec.getValue();\n if (playerPos == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (playerPos.size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n IntTag dimensionId = (IntTag) playerTag.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n\n\n int newX = marker.x;\n int newY = marker.y;\n int newZ = marker.z;\n Dimension newDimension = marker.dimension;\n\n ((FloatTag) playerPos.get(0)).setValue(((float) newX) + 0.5f);\n ((FloatTag) playerPos.get(1)).setValue(((float) newY) + 0.5f);\n ((FloatTag) playerPos.get(2)).setValue(((float) newZ) + 0.5f);\n dimensionId.setValue(newDimension.id);\n\n\n if(playerEditable.save()){\n\n localPlayerMarker = moveMarker(localPlayerMarker,newX, newY, newZ, newDimension);\n\n //TODO could be improved for translation friendliness\n Snackbar.make(tileView,\n activity.getString(R.string.teleported_player_to_xyz_dimension)+newX+\";\"+newY+\";\"+newZ+\" [\"+newDimension.name+\"] (\"+marker.getNamedBitmapProvider().getBitmapDisplayName()+\")\",\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n\n } else throw new Exception(\"Failed saving player\");\n\n } catch (Exception e){\n Log.w(e.toString());\n\n Snackbar.make(tileView, R.string.failed_teleporting_player,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n return;\n }\n case REMOVE_MARKER: {\n if(marker.isCustom){\n MapFragment.this.removeMarker(marker);\n MarkerManager mng = MapFragment.this.worldProvider.getWorld().getMarkerManager();\n mng.removeMarker(marker, true);\n\n mng.save();\n\n } else {\n //only custom markers are meant to be removable\n Snackbar.make(tileView, R.string.marker_is_not_removable,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n }\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n }\n });\n\n\n\n //do not loop the scale\n tileView.setShouldLoopScale(false);\n\n //prevents flickering\n this.tileView.setTransitionsEnabled(false);\n\n //more responsive rendering\n this.tileView.setShouldRenderWhilePanning(true);\n\n this.tileView.setSaveEnabled(true);\n\n\n\n return rootView;\n }\n\n /**\n * Creates a new marker (looking exactly the same as the old one) on the new position,\n * while removing the old marker.\n * @param marker Marker to be recreated\n * @param x new pos X\n * @param y new pos Y\n * @param z new pos Z\n * @param dimension new pos Dimension\n * @return the newly created marker, which should replace the old one.\n */\n public AbstractMarker moveMarker(AbstractMarker marker, int x, int y, int z, Dimension dimension){\n AbstractMarker newMarker = marker.copy(x, y, z, dimension);\n if(staticMarkers.remove(marker)) staticMarkers.add(newMarker);\n this.removeMarker(marker);\n this.addMarker(newMarker);\n\n if(marker.isCustom){\n MarkerManager mng = this.worldProvider.getWorld().getMarkerManager();\n mng.removeMarker(marker, true);\n mng.addMarker(newMarker, true);\n }\n\n return newMarker;\n }\n\n private final static int MARKER_INTERVAL_CHECK = 50;\n private int proceduralMarkersInterval = 0;\n private volatile AsyncTask shrinkProceduralMarkersTask;\n\n\n /**\n * Calculates viewport of tileview, expressed in blocks.\n * @param marginX horizontal viewport-margin, in pixels\n * @param marginZ vertical viewport-margin, in pixels\n * @return minimum_X, maximum_X, minimum_Z, maximum_Z, dimension. (min and max are expressed in blocks!)\n */\n public Object[] calculateViewPort(int marginX, int marginZ){\n\n Dimension dimension = this.worldProvider.getDimension();\n\n // 1 chunk per tile on scale 1.0\n int pixelsPerBlockW_unscaled = MCTileProvider.TILESIZE / dimension.chunkW;\n int pixelsPerBlockL_unscaled = MCTileProvider.TILESIZE / dimension.chunkL;\n\n float scale = tileView.getScale();\n\n //scale the amount of pixels, less pixels per block if zoomed out\n double pixelsPerBlockW = pixelsPerBlockW_unscaled * scale;\n double pixelsPerBlockL = pixelsPerBlockL_unscaled * scale;\n\n long blockX = Math.round( (tileView.getScrollX() - marginX) / pixelsPerBlockW ) - MCTileProvider.HALF_WORLDSIZE;\n long blockZ = Math.round( (tileView.getScrollY() - marginZ) / pixelsPerBlockL ) - MCTileProvider.HALF_WORLDSIZE;\n long blockW = Math.round( (tileView.getWidth() + marginX + marginX) / pixelsPerBlockW );\n long blockH = Math.round( (tileView.getHeight() + marginZ + marginZ) / pixelsPerBlockL );\n\n return new Object[]{ blockX, blockX + blockW, blockZ, blockH, dimension };\n }\n\n public AsyncTask retainViewPortMarkers(final Runnable callback){\n\n DisplayMetrics displayMetrics = this.getActivity().getResources().getDisplayMetrics();\n return new AsyncTask<Object, AbstractMarker, Void>(){\n @Override\n protected Void doInBackground(Object... params) {\n long minX = (long) params[0],\n maxX = (long) params[1],\n minY = (long) params[2],\n maxY = (long) params[3];\n Dimension reqDim = (Dimension) params[4];\n\n for (AbstractMarker p : MapFragment.this.proceduralMarkers){\n\n // do not remove static markers\n if(MapFragment.this.staticMarkers.contains(p)) continue;\n\n if(p.x < minX || p.x > maxX || p.y < minY || p.y > maxY || p.dimension != reqDim){\n this.publishProgress(p);\n }\n }\n return null;\n }\n\n @Override\n protected void onProgressUpdate(final AbstractMarker... values) {\n for(AbstractMarker v : values) {\n MapFragment.this.removeMarker(v);\n }\n }\n\n @Override\n protected void onPostExecute(Void aVoid) {\n callback.run();\n }\n\n }.execute(this.calculateViewPort(\n displayMetrics.widthPixels / 2,\n displayMetrics.heightPixels / 2)\n );\n }\n\n /**\n * Important: this method should be run from the UI thread.\n * @param marker The marker to remove from the tile view.\n */\n public void removeMarker(AbstractMarker marker){\n staticMarkers.remove(marker);\n proceduralMarkers.remove(marker);\n if(marker.view != null) tileView.removeMarker(marker.view);\n }\n\n /**\n * Important: this method should be run from the UI thread.\n * @param marker The marker to add to the tile view.\n */\n public void addMarker(AbstractMarker marker){\n\n if(proceduralMarkers.contains(marker)) return;\n\n if(shrinkProceduralMarkersTask == null\n && ++proceduralMarkersInterval > MARKER_INTERVAL_CHECK){\n //shrink set of markers to viewport every so often\n shrinkProceduralMarkersTask = retainViewPortMarkers(new Runnable() {\n @Override\n public void run() {\n //reset this to start accepting viewport update requests again.\n shrinkProceduralMarkersTask = null;\n }\n });\n\n proceduralMarkersInterval = 0;\n }\n\n\n proceduralMarkers.add(marker);\n\n\n Activity act = getActivity();\n if (act == null) return;\n MarkerImageView markerView = marker.getView(act);\n\n this.filterMarker(marker);\n\n if(tileView.getMarkerLayout().indexOfChild(markerView) >= 0){\n tileView.getMarkerLayout().removeMarker(markerView);\n }\n\n\n tileView.addMarker(markerView,\n marker.dimension.dimensionScale * (double) marker.x / (double) MCTileProvider.HALF_WORLDSIZE,\n marker.dimension.dimensionScale * (double) marker.z / (double) MCTileProvider.HALF_WORLDSIZE,\n -0.5f, -0.5f);\n }\n\n public void toggleMarkers(){\n int visibility = tileView.getMarkerLayout().getVisibility();\n tileView.getMarkerLayout().setVisibility( visibility == View.VISIBLE ? View.GONE : View.VISIBLE);\n }\n\n\n public enum LongClickOption {\n\n TELEPORT_LOCAL_PLAYER(R.string.teleport_local_player, null),\n CREATE_MARKER(R.string.create_custom_marker, null),\n //TODO TELEPORT_MULTI_PLAYER(\"Teleport other player\", null),\n ENTITY(R.string.open_chunk_entity_nbt, ChunkTag.ENTITY),\n TILE_ENTITY(R.string.open_chunk_tile_entity_nbt, ChunkTag.BLOCK_ENTITY);\n\n public final int stringId;\n public final ChunkTag dataType;\n\n LongClickOption(int id, ChunkTag dataType){\n this.stringId = id;\n this.dataType = dataType;\n }\n\n }\n\n public String[] getLongClickOptions(){\n LongClickOption[] values = LongClickOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n\n public void onLongClick(final double worldX, final double worldZ){\n\n\n final Activity activity = MapFragment.this.getActivity();\n\n\n final Dimension dim = this.worldProvider.getDimension();\n\n double chunkX = worldX / dim.chunkW;\n double chunkZ = worldZ / dim.chunkL;\n\n //negative doubles are rounded up when casting to int; floor them\n final int chunkXint = chunkX < 0 ? (((int) chunkX) - 1) : ((int) chunkX);\n final int chunkZint = chunkZ < 0 ? (((int) chunkZ) - 1) : ((int) chunkZ);\n\n\n\n final View container = activity.findViewById(R.id.world_content);\n if(container == null){\n Log.w(\"CANNOT FIND MAIN CONTAINER, WTF\");\n return;\n }\n\n new AlertDialog.Builder(activity)\n .setTitle(getString(R.string.postion_2D_floats_with_chunkpos, worldX, worldZ, chunkXint, chunkZint, dim.name))\n .setItems(getLongClickOptions(), new DialogInterface.OnClickListener() {\n @SuppressLint(\"SetTextI18n\")\n public void onClick(DialogInterface dialog, int which) {\n\n final LongClickOption chosen = LongClickOption.values()[which];\n\n\n switch (chosen){\n case TELEPORT_LOCAL_PLAYER:{\n try {\n\n final EditableNBT playerEditable = MapFragment.this.worldProvider.getEditablePlayer();\n if(playerEditable == null) throw new Exception(\"Player is null\");\n\n Iterator playerIter = playerEditable.getTags().iterator();\n if(!playerIter.hasNext()) throw new Exception(\"Player DB entry is empty!\");\n\n //db entry consists of one compound tag\n final CompoundTag playerTag = (CompoundTag) playerIter.next();\n\n ListTag posVec = (ListTag) playerTag.getChildTagByKey(\"Pos\");\n\n if (posVec == null) throw new Exception(\"No \\\"Pos\\\" specified\");\n\n final List<Tag> playerPos = posVec.getValue();\n if(playerPos == null)\n throw new Exception(\"No \\\"Pos\\\" specified\");\n if (playerPos.size() != 3)\n throw new Exception(\"\\\"Pos\\\" value is invalid. value: \" + posVec.getValue().toString());\n\n final IntTag dimensionId = (IntTag) playerTag.getChildTagByKey(\"DimensionId\");\n if(dimensionId == null || dimensionId.getValue() == null)\n throw new Exception(\"No \\\"DimensionId\\\" specified\");\n\n\n float playerY = (float) playerPos.get(1).getValue();\n\n\n View yForm = LayoutInflater.from(activity).inflate(R.layout.y_coord_form, null);\n final EditText yInput = (EditText) yForm.findViewById(R.id.y_input);\n yInput.setText(String.valueOf(playerY));\n\n final float newX = (float) worldX;\n final float newZ = (float) worldZ;\n\n new AlertDialog.Builder(activity)\n .setTitle(chosen.stringId)\n .setView(yForm)\n .setPositiveButton(R.string.action_teleport, new DialogInterface.OnClickListener() {\n @SuppressWarnings(\"RedundantCast\")\n @Override\n public void onClick(DialogInterface dialog, int which) {\n\n float newY;\n Editable value = yInput.getText();\n if(value == null) newY = 64f;\n else {\n try {\n newY = (float) Float.parseFloat(value.toString());//removes excessive precision\n } catch (Exception e){\n newY = 64f;\n }\n }\n\n ((FloatTag) playerPos.get(0)).setValue(newX);\n ((FloatTag) playerPos.get(1)).setValue(newY);\n ((FloatTag) playerPos.get(2)).setValue(newZ);\n dimensionId.setValue(dim.id);\n\n if(playerEditable.save()){\n\n MapFragment.this.localPlayerMarker = MapFragment.this.moveMarker(\n MapFragment.this.localPlayerMarker,\n (int) newX, (int) newY, (int) newZ, dim);\n\n Snackbar.make(container,\n String.format(getString(R.string.teleported_player_to_xyz_dim), newX, newY, newZ, dim.name),\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n } else {\n Snackbar.make(container,\n R.string.failed_teleporting_player,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n return;\n\n } catch (Exception e){\n e.printStackTrace();\n Snackbar.make(container, R.string.failed_to_find_or_edit_local_player_data,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n return;\n }\n }\n case CREATE_MARKER:{\n\n View createMarkerForm = LayoutInflater.from(activity).inflate(R.layout.create_marker_form, null);\n\n final EditText markerNameInput = (EditText) createMarkerForm.findViewById(R.id.marker_displayname_input);\n markerNameInput.setText(R.string.default_custom_marker_name);\n final EditText markerIconNameInput = (EditText) createMarkerForm.findViewById(R.id.marker_iconname_input);\n markerIconNameInput.setText(\"blue_marker\");\n final EditText xInput = (EditText) createMarkerForm.findViewById(R.id.x_input);\n xInput.setText(String.valueOf((int) worldX));\n final EditText yInput = (EditText) createMarkerForm.findViewById(R.id.y_input);\n yInput.setText(String.valueOf(64));\n final EditText zInput = (EditText) createMarkerForm.findViewById(R.id.z_input);\n zInput.setText(String.valueOf((int) worldZ));\n\n\n new AlertDialog.Builder(activity)\n .setTitle(chosen.stringId)\n .setView(createMarkerForm)\n .setPositiveButton(\"Create marker\", new DialogInterface.OnClickListener() {\n\n public void failParseSnackbarReport(int msg){\n Snackbar.make(container, msg,\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n\n try {\n String displayName = markerNameInput.getText().toString();\n if (displayName.equals(\"\") || displayName.contains(\"\\\"\")) {\n failParseSnackbarReport(R.string.marker_invalid_name);\n return;\n }\n String iconName = markerIconNameInput.getText().toString();\n if (iconName.equals(\"\") || iconName.contains(\"\\\"\")) {\n failParseSnackbarReport(R.string.invalid_icon_name);\n return;\n }\n\n int xM, yM, zM;\n\n String xStr = xInput.getText().toString();\n try {\n xM = Integer.parseInt(xStr);\n } catch (NumberFormatException e) {\n failParseSnackbarReport(R.string.invalid_x_coordinate);\n return;\n }\n String yStr = yInput.getText().toString();\n try {\n yM = Integer.parseInt(yStr);\n } catch (NumberFormatException e) {\n failParseSnackbarReport(R.string.invalid_y_coordinate);\n return;\n }\n\n String zStr = zInput.getText().toString();\n try {\n zM = Integer.parseInt(zStr);\n } catch (NumberFormatException e) {\n failParseSnackbarReport(R.string.invalid_z_coordinate);\n return;\n }\n\n AbstractMarker marker = MarkerManager.markerFromData(displayName, iconName, xM, yM, zM, dim);\n MarkerManager mng = MapFragment.this.worldProvider.getWorld().getMarkerManager();\n mng.addMarker(marker, true);\n\n MapFragment.this.addMarker(marker);\n\n mng.save();\n\n } catch (Exception e){\n e.printStackTrace();\n failParseSnackbarReport(R.string.failed_to_create_marker);\n }\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n\n\n\n\n return;\n }\n /* TODO multi player teleporting\n case TELEPORT_MULTI_PLAYER:{\n\n break;\n }*/\n case ENTITY:\n case TILE_ENTITY:{\n\n final World world = MapFragment.this.worldProvider.getWorld();\n final ChunkManager chunkManager = new ChunkManager(world.getWorldData(), dim);\n final Chunk chunk = chunkManager.getChunk(chunkXint, chunkZint);\n\n if(!chunkDataNBT(chunk, chosen == LongClickOption.ENTITY)){\n Snackbar.make(container, String.format(getString(R.string.failed_to_load_x), getString(chosen.stringId)),\n Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n\n\n }\n }\n\n\n }\n })\n .setCancelable(true)\n .setNegativeButton(android.R.string.cancel, null)\n .show();\n\n }\n\n /**\n * Opens the chunk data nbt editor.\n *\n * @param chunk the chunk to edit\n * @param entity if it is entity data (True) or block-entity data (False)\n * @return false when the chunk data could not be loaded.\n */\n private boolean chunkDataNBT(Chunk chunk, boolean entity){\n NBTChunkData chunkData;\n try {\n chunkData = entity ? chunk.getEntity() : chunk.getBlockEntity();\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n\n //just open the editor if the data is there for us to edit it\n this.worldProvider.openChunkNBTEditor(chunk.x, chunk.z, chunkData, this.tileView);\n return true;\n }\n\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n\n\n tileView.destroy();\n tileView = null;\n minecraftTileProvider = null;\n\n }\n\n public static class BitmapChoiceListAdapter extends ArrayAdapter<BitmapChoiceListAdapter.NamedBitmapChoice> {\n\n public static class NamedBitmapChoice {\n\n //Using a handle to facilitate bitmap swapping without breaking the filter.\n final NamedBitmapProviderHandle namedBitmap;\n boolean enabledTemp;\n boolean enabled;\n\n public NamedBitmapChoice(NamedBitmapProviderHandle namedBitmap, boolean enabled){\n this.namedBitmap = namedBitmap;\n this.enabled = this.enabledTemp = enabled;\n }\n }\n\n public BitmapChoiceListAdapter(Context context, List<NamedBitmapChoice> objects) {\n super(context, 0, objects);\n }\n\n @NonNull\n @Override\n public View getView(final int position, View v, @NonNull ViewGroup parent) {\n\n final NamedBitmapChoice m = getItem(position);\n if(m == null) return new RelativeLayout(getContext());\n\n if (v == null) v = LayoutInflater\n .from(getContext())\n .inflate(R.layout.img_name_check_list_entry, parent, false);\n\n\n ImageView img = (ImageView) v.findViewById(R.id.entry_img);\n TextView text = (TextView) v.findViewById(R.id.entry_text);\n final CheckBox check = (CheckBox) v.findViewById(R.id.entry_check);\n\n img.setImageBitmap(m.namedBitmap.getNamedBitmapProvider().getBitmap());\n text.setText(m.namedBitmap.getNamedBitmapProvider().getBitmapDisplayName());\n check.setTag(position);\n check.setChecked(m.enabledTemp);\n check.setOnCheckedChangeListener(changeListener);\n\n return v;\n }\n\n private CompoundButton.OnCheckedChangeListener changeListener = new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton compoundButton, boolean b) {\n Object tag = compoundButton.getTag();\n if(tag == null) return;\n int position = (int) tag;\n final NamedBitmapChoice m = getItem(position);\n if(m == null) return;\n m.enabledTemp = b;\n }\n };\n\n }\n\n\n //static, remember choice while app is open.\n static Map<NamedBitmapProvider, BitmapChoiceListAdapter.NamedBitmapChoice> markerFilter = new HashMap<>();\n\n static {\n //entities are enabled by default\n for (Entity v : Entity.values()) {\n //skip things without a bitmap (dropped items etc.)\n //skip entities with placeholder ids (900+)\n if(v.sheetPos < 0 || v.id >= 900) continue;\n markerFilter.put(v.getNamedBitmapProvider(),\n new BitmapChoiceListAdapter.NamedBitmapChoice(v, true));\n }\n //tile-entities are disabled by default\n for (TileEntity v : TileEntity.values()) {\n markerFilter.put(v.getNamedBitmapProvider(),\n new BitmapChoiceListAdapter.NamedBitmapChoice(v, false));\n }\n\n }\n\n public void openMarkerFilter() {\n\n final Activity activity = this.getActivity();\n\n\n final List<BitmapChoiceListAdapter.NamedBitmapChoice> choices = new ArrayList<>();\n choices.addAll(markerFilter.values());\n\n //sort on names, nice for the user.\n Collections.sort(choices, new Comparator<BitmapChoiceListAdapter.NamedBitmapChoice>() {\n @Override\n public int compare(BitmapChoiceListAdapter.NamedBitmapChoice a, BitmapChoiceListAdapter.NamedBitmapChoice b) {\n return a.namedBitmap.getNamedBitmapProvider().getBitmapDisplayName().compareTo(b.namedBitmap.getNamedBitmapProvider().getBitmapDisplayName());\n }\n });\n\n\n\n new AlertDialog.Builder(activity)\n .setTitle(R.string.filter_markers)\n .setAdapter(new BitmapChoiceListAdapter(activity, choices), null)\n .setCancelable(true)\n .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n //save all the temporary states.\n for(BitmapChoiceListAdapter.NamedBitmapChoice choice : choices){\n choice.enabled = choice.enabledTemp;\n }\n MapFragment.this.updateMarkerFilter();\n }\n })\n .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n //reset all the temporary states.\n for(BitmapChoiceListAdapter.NamedBitmapChoice choice : choices){\n choice.enabledTemp = choice.enabled;\n }\n }\n })\n .setOnCancelListener(new DialogInterface.OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialogInterface) {\n //reset all the temporary states.\n for(BitmapChoiceListAdapter.NamedBitmapChoice choice : choices){\n choice.enabledTemp = choice.enabled;\n }\n }\n })\n .show();\n }\n\n public void updateMarkerFilter(){\n for(AbstractMarker marker : this.proceduralMarkers){\n filterMarker(marker);\n }\n }\n\n public void filterMarker(AbstractMarker marker){\n BitmapChoiceListAdapter.NamedBitmapChoice choice = markerFilter.get(marker.getNamedBitmapProvider());\n if(choice != null){\n marker.getView(this.getActivity()).setVisibility(\n (choice.enabled && marker.dimension == worldProvider.getDimension())\n ? View.VISIBLE : View.INVISIBLE);\n } else {\n marker.getView(this.getActivity())\n .setVisibility(marker.dimension == worldProvider.getDimension()\n ? View.VISIBLE : View.INVISIBLE);\n }\n }\n\n public void resetTileView(){\n if(this.tileView != null){\n worldProvider.logFirebaseEvent(WorldActivity.CustomFirebaseEvent.MAPFRAGMENT_RESET);\n\n updateMarkerFilter();\n\n tileView.getDetailLevelManager().setLevelType(worldProvider.getMapType());\n\n invalidateTileView();\n }\n }\n\n public void invalidateTileView(){\n MapType redo = worldProvider.getMapType();\n DetailLevelManager manager = tileView.getDetailLevelManager();\n //just swap mapType twice; it is not rendered, but it invalidates all tiles.\n manager.setLevelType(MapType.CHESS);\n manager.setLevelType(redo);\n //all tiles will now reload as soon as the tileView is drawn (user scrolls -> redraw)\n }\n\n\n\n /**\n * This is a convenience method to scrollToAndCenter after layout (which won't happen if called directly in onCreate\n * see https://github.com/moagrius/TileView/wiki/FAQ\n */\n public void frameTo( final double worldX, final double worldZ ) {\n this.tileView.post(new Runnable() {\n @Override\n public void run() {\n Dimension dimension = worldProvider.getDimension();\n if(tileView != null) tileView.scrollToAndCenter(\n dimension.dimensionScale * worldX / (double) MCTileProvider.HALF_WORLDSIZE,\n dimension.dimensionScale * worldZ / (double) MCTileProvider.HALF_WORLDSIZE);\n }\n });\n }\n\n\n}", "public enum MapType implements DetailLevelManager.LevelType {\n\n //shows that a chunk was present, but couldn't be renderer\n ERROR(new ChessPatternRenderer(0xFF2B0000, 0xFF580000)),\n\n //simple xor pattern renderer\n DEBUG(new DebugRenderer()),\n\n //simple chess pattern renderer\n CHESS(new ChessPatternRenderer(0xFF2B2B2B, 0xFF585858)),\n\n //just the surface of the world, with shading for height diff\n OVERWORLD_SATELLITE(new SatelliteRenderer()),\n\n //cave mapping\n OVERWORLD_CAVE(new CaveRenderer()),\n\n OVERWORLD_SLIME_CHUNK(new SlimeChunkRenderer()),\n\n //render skylight value of highest block\n OVERWORLD_HEIGHTMAP(new HeightmapRenderer()),\n\n //render biome id as biome-unique color\n OVERWORLD_BIOME(new BiomeRenderer()),\n\n //render the voliage colors\n OVERWORLD_GRASS(new GrassRenderer()),\n\n //render only the valuable blocks to mine (diamonds, emeralds, gold, etc.)\n OVERWORLD_XRAY(new XRayRenderer()),\n\n //block-light renderer: from light-sources like torches etc.\n OVERWORLD_BLOCK_LIGHT(new BlockLightRenderer()),\n\n NETHER(new NetherRenderer()),\n\n NETHER_XRAY(new XRayRenderer()),\n\n NETHER_BLOCK_LIGHT(new BlockLightRenderer()),\n\n END_SATELLITE(new SatelliteRenderer()),\n\n END_HEIGHTMAP(new HeightmapRenderer()),\n\n END_BLOCK_LIGHT(new BlockLightRenderer());\n\n //REDSTONE //TODO redstone circuit mapping\n //TRAFFIC //TODO traffic mapping (land = green, water = blue, gravel/stone/etc. = gray, rails = yellow)\n\n\n public final MapRenderer renderer;\n\n MapType(MapRenderer renderer){\n this.renderer = renderer;\n }\n\n}", "public class EditorFragment extends Fragment {\n\n /**\n *\n * TODO:\n *\n * - The onSomethingChanged listeners should start Asynchronous tasks\n * when directly modifying NBT.\n *\n * - This editor should be refactored into parts, it grew too large.\n *\n * - The functions lack documentation. Add it. Ask @protolambda for now...\n *\n */\n\n private EditableNBT nbt;\n\n public void setEditableNBT(EditableNBT nbt){\n this.nbt = nbt;\n }\n\n public static class ChainTag {\n\n public Tag parent, self;\n\n public ChainTag(Tag parent, Tag self){\n this.parent = parent;\n this.self = self;\n }\n }\n\n public static class RootNodeHolder extends TreeNode.BaseNodeViewHolder<EditableNBT>{\n\n\n public RootNodeHolder(Context context) {\n super(context);\n }\n\n @Override\n public View createNodeView(TreeNode node, EditableNBT value) {\n\n final LayoutInflater inflater = LayoutInflater.from(context);\n\n final View tagView = inflater.inflate(R.layout.tag_root_layout, null, false);\n TextView tagName = (TextView) tagView.findViewById(R.id.tag_name);\n tagName.setText(value.getRootTitle());\n\n return tagView;\n }\n\n @Override\n public void toggle(boolean active) {\n }\n\n @Override\n public int getContainerStyle() {\n return R.style.TreeNodeStyleCustomRoot;\n }\n }\n\n\n public static class NBTNodeHolder extends TreeNode.BaseNodeViewHolder<ChainTag> {\n\n private final EditableNBT nbt;\n\n public NBTNodeHolder(EditableNBT nbt, Context context) {\n super(context);\n this.nbt = nbt;\n }\n\n @SuppressLint(\"SetTextI18n\")\n @Override\n public View createNodeView(TreeNode node, final ChainTag chain) {\n\n if(chain == null) return null;\n Tag tag = chain.self;\n if(tag == null) return null;\n\n final LayoutInflater inflater = LayoutInflater.from(context);\n\n int layoutID;\n\n switch (tag.getType()) {\n case COMPOUND: {\n List<Tag> value = ((CompoundTag) tag).getValue();\n if (value != null) {\n for (Tag child : value) {\n node.addChild(new TreeNode(new ChainTag(tag, child)).setViewHolder(new NBTNodeHolder(nbt, context)));\n }\n }\n\n layoutID = R.layout.tag_compound_layout;\n break;\n }\n case LIST: {\n List<Tag> value = ((ListTag) tag).getValue();\n\n if (value != null) {\n for (Tag child : value) {\n node.addChild(new TreeNode(new ChainTag(tag, child)).setViewHolder(new NBTNodeHolder(nbt, context)));\n }\n }\n\n layoutID = R.layout.tag_list_layout;\n break;\n }\n case BYTE_ARRAY: {\n layoutID = R.layout.tag_default_layout;\n break;\n }\n case BYTE: {\n String name = tag.getName().toLowerCase();\n\n //TODO differentiate boolean tags from byte tags better\n if (name.startsWith(\"has\") || name.startsWith(\"is\")) {\n layoutID = R.layout.tag_boolean_layout;\n } else {\n layoutID = R.layout.tag_byte_layout;\n }\n break;\n }\n case SHORT:\n layoutID = R.layout.tag_short_layout;\n break;\n case INT:\n layoutID = R.layout.tag_int_layout;\n break;\n case LONG:\n layoutID = R.layout.tag_long_layout;\n break;\n case FLOAT:\n layoutID = R.layout.tag_float_layout;\n break;\n case DOUBLE:\n layoutID = R.layout.tag_double_layout;\n break;\n case STRING:\n layoutID = R.layout.tag_string_layout;\n break;\n default:\n layoutID = R.layout.tag_default_layout;\n break;\n }\n\n final View tagView = inflater.inflate(layoutID, null, false);\n TextView tagName = (TextView) tagView.findViewById(R.id.tag_name);\n tagName.setText(tag.getName());\n\n switch (layoutID){\n case R.layout.tag_boolean_layout: {\n final CheckBox checkBox = (CheckBox) tagView.findViewById(R.id.checkBox);\n final ByteTag byteTag = (ByteTag) tag;\n checkBox.setChecked(byteTag.getValue() == (byte) 1);\n checkBox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {\n /**\n * Called when the checked state of a compound button has changed.\n *\n * @param buttonView The compound button view whose state has changed.\n * @param isChecked The new checked state of buttonView.\n */\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n byteTag.setValue(isChecked ? (byte) 1 : (byte) 0);\n nbt.setModified();\n }\n });\n break;\n }\n case R.layout.tag_byte_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.byteField);\n final ByteTag byteTag = (ByteTag) tag;\n //parse the byte as an unsigned byte\n editText.setText(\"\"+(((int) byteTag.getValue()) & 0xFF));\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n int value = Integer.parseInt(sValue);\n if(value < 0 || value > 0xff)\n throw new NumberFormatException(\"No unsigned byte.\");\n byteTag.setValue((byte) value);\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_short_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.shortField);\n final ShortTag shortTag = (ShortTag) tag;\n editText.setText(shortTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n shortTag.setValue(Short.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_int_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.intField);\n final IntTag intTag = (IntTag) tag;\n editText.setText(intTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n intTag.setValue(Integer.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_long_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.longField);\n final LongTag longTag = (LongTag) tag;\n editText.setText(longTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n longTag.setValue(Long.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_float_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.floatField);\n final FloatTag floatTag = (FloatTag) tag;\n editText.setText(floatTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n floatTag.setValue(Float.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_double_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.doubleField);\n final DoubleTag doubleTag = (DoubleTag) tag;\n editText.setText(doubleTag.getValue().toString());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n String sValue = s.toString();\n try {\n doubleTag.setValue(Double.valueOf(sValue));\n nbt.setModified();\n } catch (NumberFormatException e){\n editText.setError(String.format(context.getString(R.string.x_is_invalid), sValue));\n }\n }\n });\n break;\n }\n case R.layout.tag_string_layout: {\n final EditText editText = (EditText) tagView.findViewById(R.id.stringField);\n final StringTag stringTag = (StringTag) tag;\n editText.setText(stringTag.getValue());\n editText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) { }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) { }\n\n @Override\n public void afterTextChanged(Editable s) {\n nbt.setModified();\n stringTag.setValue(s.toString());\n }\n });\n break;\n }\n default:\n break;\n\n }\n\n return tagView;\n }\n\n @Override\n public void toggle(boolean active) {\n }\n\n @Override\n public int getContainerStyle() {\n return R.style.TreeNodeStyleCustom;\n }\n\n }\n\n public enum NBTEditOption {\n\n CANCEL(R.string.edit_cancel),\n COPY(R.string.edit_copy),\n PASTE_OVERWRITE(R.string.edit_paste_overwrite),\n PASTE_SUBTAG(R.string.edit_paste_sub_tag),\n DELETE(R.string.edit_delete),\n RENAME(R.string.edit_rename),\n ADD_SUBTAG(R.string.edit_add_sub_tag);\n\n public final int stringId;\n\n NBTEditOption(int stringId){\n this.stringId = stringId;\n }\n }\n\n public String[] getNBTEditOptions(){\n NBTEditOption[] values = NBTEditOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n public enum RootNBTEditOption {\n\n ADD_NBT_TAG(R.string.edit_root_add),\n PASTE_SUB_TAG(R.string.edit_root_paste_sub_tag),\n REMOVE_ALL_TAGS(R.string.edit_root_remove_all);\n\n public final int stringId;\n\n RootNBTEditOption(int stringId){\n this.stringId = stringId;\n }\n\n }\n\n public String[] getRootNBTEditOptions(){\n RootNBTEditOption[] values = RootNBTEditOption.values();\n int len = values.length;\n String[] options = new String[len];\n for(int i = 0; i < len; i++){\n options[i] = getString(values[i].stringId);\n }\n return options;\n }\n\n\n public static Tag clipboard;\n\n\n //returns true if there is a tag in content with a name equals to key.\n boolean checkKeyCollision(String key, List<Tag> content){\n if(content == null || content.isEmpty()) return false;\n if(key == null) key = \"\";\n String tagName;\n for(Tag tag : content) {\n tagName = tag.getName();\n if(tagName == null) tagName = \"\";\n if(tagName.equals(key)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n\n\n if(nbt == null){\n new Exception(\"No NBT data provided\").printStackTrace();\n getActivity().finish();\n\n return null;\n }\n\n final View rootView = inflater.inflate(R.layout.nbt_editor, container, false);\n\n // edit functionality\n // ================================\n\n TreeNode superRoot = TreeNode.root();\n TreeNode root = new TreeNode(nbt);\n superRoot.addChild(root);\n root.setExpanded(true);\n root.setSelectable(false);\n\n\n final Activity activity = getActivity();\n\n root.setViewHolder(new RootNodeHolder(activity));\n\n for(Tag tag : nbt.getTags()){\n root.addChild(new TreeNode(new ChainTag(null, tag)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n }\n\n FrameLayout frame = (FrameLayout) rootView.findViewById(R.id.nbt_editor_frame);\n\n final AndroidTreeView tree = new AndroidTreeView(getActivity(), superRoot);\n tree.setUse2dScroll(true);\n\n final View treeView = tree.getView();\n\n treeView.setScrollContainer(true);\n\n tree.setDefaultNodeLongClickListener(new TreeNode.TreeNodeLongClickListener() {\n @Override\n public boolean onLongClick(final TreeNode node, final Object value) {\n\n Log.d(\"NBT editor: Long click!\");\n\n\n //root tag has nbt as value\n if(value instanceof EditableNBT){\n\n if(!nbt.enableRootModifications){\n Toast.makeText(activity, R.string.cannot_edit_root_NBT_tag, Toast.LENGTH_LONG).show();\n return true;\n }\n\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n\n builder.setTitle(R.string.root_NBT_options)\n .setItems(getRootNBTEditOptions(), new DialogInterface.OnClickListener() {\n\n private void showMsg(int msg){\n Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();\n }\n\n public void onClick(DialogInterface dialog, int which) {\n try {\n RootNBTEditOption option = RootNBTEditOption.values()[which];\n\n switch (option){\n case ADD_NBT_TAG:{\n final EditText nameText = new EditText(activity);\n nameText.setHint(R.string.hint_tag_name_here);\n\n //NBT tag type spinner\n final Spinner spinner = new Spinner(activity);\n ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(\n activity, android.R.layout.simple_spinner_item, NBTConstants.NBTType.editorOptions_asString);\n\n spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(spinnerArrayAdapter);\n\n //wrap editText and spinner in linear layout\n LinearLayout linearLayout = new LinearLayout(activity);\n linearLayout.setOrientation(LinearLayout.VERTICAL);\n linearLayout.setLayoutParams(\n new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT,\n LinearLayout.LayoutParams.WRAP_CONTENT,\n Gravity.BOTTOM));\n linearLayout.addView(nameText);\n linearLayout.addView(spinner);\n\n //wrap layout in alert\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.create_nbt_tag);\n alert.setView(linearLayout);\n\n //alert can create a new tag\n alert.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n //new tag name\n Editable newNameEditable = nameText.getText();\n String newName = (newNameEditable == null || newNameEditable.toString().equals(\"\")) ? null : newNameEditable.toString();\n\n //new tag type\n int spinnerIndex = spinner.getSelectedItemPosition();\n NBTConstants.NBTType nbtType = NBTConstants.NBTType.editorOptions_asType[spinnerIndex];\n\n //create new tag\n Tag newTag = NBTConstants.NBTType.newInstance(newName, nbtType);\n\n //add tag to nbt\n nbt.addRootTag(newTag);\n tree.addNode(node, new TreeNode(new ChainTag(null, newTag)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n\n nbt.setModified();\n\n }\n });\n\n //or alert is cancelled\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"NBT tag creation cancelled\");\n }\n });\n\n alert.show();\n\n return;\n }\n case PASTE_SUB_TAG: {\n if(clipboard == null){\n showMsg(R.string.clipboard_is_empty);\n return;\n }\n\n Tag copy = clipboard.getDeepCopy();\n nbt.addRootTag(copy);\n tree.addNode(node, new TreeNode(new ChainTag(null, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n nbt.setModified();\n\n return;\n }\n case REMOVE_ALL_TAGS:{\n\n //wrap layout in alert\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.confirm_delete_all_nbt_tags);\n\n //alert can create a new tag\n alert.setPositiveButton(R.string.delete_loud, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n\n List<TreeNode> children = new ArrayList<>(node.getChildren());\n //new tag name\n for(TreeNode child : children){\n tree.removeNode(child);\n Object childValue = child.getValue();\n if(childValue != null && childValue instanceof ChainTag)\n nbt.removeRootTag(((ChainTag) childValue).self);\n }\n nbt.setModified();\n }\n\n });\n\n //or alert is cancelled\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"NBT tag creation cancelled\");\n }\n });\n\n alert.show();\n\n break;\n }\n default: {\n Log.d(\"User clicked unknown NBTEditOption! \"+option.name());\n }\n }\n } catch (Exception e){\n showMsg(R.string.failed_to_do_NBT_change);\n }\n }\n\n });\n builder.show();\n return true;\n\n\n } else if(value instanceof ChainTag){\n //other tags have a chain-tag as value\n\n\n AlertDialog.Builder builder = new AlertDialog.Builder(activity);\n\n builder.setTitle(R.string.nbt_tag_options)\n .setItems(getNBTEditOptions(), new DialogInterface.OnClickListener() {\n\n private void showMsg(int msg){\n Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();\n }\n\n @SuppressWarnings(\"unchecked\")\n public void onClick(DialogInterface dialog, int which) {\n try{\n NBTEditOption editOption = NBTEditOption.values()[which];\n\n final Tag parent = ((ChainTag) value).parent;\n final Tag self = ((ChainTag) value).self;\n\n if(self == null) return;//WTF?\n\n if(editOption == null) return;//WTF?\n\n switch (editOption){\n case CANCEL: {\n return;\n }\n case COPY: {\n clipboard = self.getDeepCopy();\n return;\n }\n case PASTE_OVERWRITE: {\n if(clipboard == null){\n showMsg(R.string.clipboard_is_empty);\n return;\n }\n\n if(parent == null){\n //it is one of the children of the root node\n nbt.removeRootTag(self);\n Tag copy = clipboard.getDeepCopy();\n nbt.addRootTag(copy);\n tree.addNode(node.getParent(), new TreeNode(new ChainTag(null, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n tree.removeNode(node);\n nbt.setModified();\n return;\n } else {\n\n ArrayList<Tag> content;\n switch (parent.getType()) {\n case LIST: {\n content = ((ListTag) parent).getValue();\n break;\n }\n case COMPOUND: {\n content = ((CompoundTag) parent).getValue();\n if(checkKeyCollision(clipboard.getName(), content)){\n showMsg(R.string.clipboard_key_exists_in_compound);\n return;\n }\n break;\n }\n default: {\n showMsg(R.string.error_cannot_overwrite_tag_unknow_parent_type);\n return;\n }\n }\n if(content != null){\n content.remove(self);\n Tag copy = clipboard.getDeepCopy();\n content.add(copy);\n tree.addNode(node.getParent(), new TreeNode(new ChainTag(parent, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n tree.removeNode(node);\n nbt.setModified();\n return;\n }\n else showMsg(R.string.error_cannot_overwrite_in_empty_parent);\n return;\n }\n }\n case PASTE_SUBTAG: {\n if(clipboard == null){\n showMsg(R.string.clipboard_is_empty);\n return;\n }\n\n ArrayList<Tag> content;\n switch (self.getType()) {\n case LIST: {\n content = ((ListTag) self).getValue();\n break;\n }\n case COMPOUND: {\n content = ((CompoundTag) self).getValue();\n if(checkKeyCollision(clipboard.getName(), content)){\n showMsg(R.string.clipboard_key_exists_in_compound);\n return;\n }\n break;\n }\n default: {\n showMsg(R.string.error_cannot_paste_as_sub_unknown_parent_type);\n return;\n }\n }\n if(content == null){\n content = new ArrayList<>();\n self.setValue(content);\n }\n\n Tag copy = clipboard.getDeepCopy();\n content.add(copy);\n tree.addNode(node, new TreeNode(new ChainTag(self, copy)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n nbt.setModified();\n\n return;\n }\n case DELETE: {\n if(parent == null){\n //it is one of the children of the root node\n tree.removeNode(node);\n nbt.removeRootTag(self);\n nbt.setModified();\n return;\n }\n\n ArrayList<Tag> content;\n switch (parent.getType()){\n case LIST:{\n content = ((ListTag) parent).getValue();\n break;\n }\n case COMPOUND:{\n content = ((CompoundTag) parent).getValue();\n break;\n }\n default:{\n showMsg(R.string.error_cannot_overwrite_tag_unknow_parent_type);\n return;\n }\n }\n if(content != null){\n content.remove(self);\n tree.removeNode(node);\n nbt.setModified();\n }\n else showMsg(R.string.error_cannot_remove_from_empty_list);\n return;\n }\n case RENAME: {\n final EditText edittext = new EditText(activity);\n edittext.setHint(R.string.hint_tag_name_here);\n\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.rename_nbt_tag);\n\n alert.setView(edittext);\n\n alert.setPositiveButton(R.string.rename, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Editable newNameEditable = edittext.getText();\n String newName = (newNameEditable == null || newNameEditable.toString().equals(\"\")) ? null : newNameEditable.toString();\n\n if(parent != null\n && parent instanceof CompoundTag\n && checkKeyCollision(newName, ((CompoundTag) parent).getValue())){\n showMsg(R.string.error_parent_already_contains_child_with_same_key);\n return;\n }\n\n self.setName(newName);\n\n //refresh view with new TreeNode\n tree.addNode(node.getParent(), new TreeNode(new ChainTag(parent, self)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n tree.removeNode(node);\n\n nbt.setModified();\n }\n });\n\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"Cancelled rename NBT tag\");\n }\n });\n\n alert.show();\n\n return;\n }\n case ADD_SUBTAG: {\n switch (self.getType()){\n case LIST:\n case COMPOUND:{\n final EditText nameText = new EditText(activity);\n nameText.setHint(R.string.hint_tag_name_here);\n\n //NBT tag type spinner\n final Spinner spinner = new Spinner(activity);\n ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(\n activity, android.R.layout.simple_spinner_item, NBTConstants.NBTType.editorOptions_asString);\n\n spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n spinner.setAdapter(spinnerArrayAdapter);\n\n //wrap editText and spinner in linear layout\n LinearLayout linearLayout = new LinearLayout(activity);\n linearLayout.setOrientation(LinearLayout.VERTICAL);\n linearLayout.setLayoutParams(\n new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT,\n LinearLayout.LayoutParams.WRAP_CONTENT,\n Gravity.BOTTOM));\n linearLayout.addView(nameText);\n linearLayout.addView(spinner);\n\n //wrap layout in alert\n AlertDialog.Builder alert = new AlertDialog.Builder(activity);\n alert.setTitle(R.string.create_nbt_tag);\n alert.setView(linearLayout);\n\n //alert can create a new tag\n alert.setPositiveButton(R.string.create, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n\n //new tag name\n Editable newNameEditable = nameText.getText();\n String newName = (newNameEditable == null || newNameEditable.toString().equals(\"\")) ? null : newNameEditable.toString();\n\n //new tag type\n int spinnerIndex = spinner.getSelectedItemPosition();\n NBTConstants.NBTType nbtType = NBTConstants.NBTType.editorOptions_asType[spinnerIndex];\n\n\n ArrayList<Tag> content;\n if(self instanceof CompoundTag) {\n\n content = ((CompoundTag) self).getValue();\n\n if(checkKeyCollision(newName, content)){\n showMsg(R.string.error_key_already_exists_in_compound);\n return;\n }\n }\n else if(self instanceof ListTag){\n content = ((ListTag) self).getValue();\n }\n else return;//WTF?\n\n if(content == null){\n content = new ArrayList<>();\n self.setValue(content);\n }\n\n //create new tag\n Tag newTag = NBTConstants.NBTType.newInstance(newName, nbtType);\n\n //add tag to nbt\n content.add(newTag);\n tree.addNode(node, new TreeNode(new ChainTag(self, newTag)).setViewHolder(new NBTNodeHolder(nbt, activity)));\n\n nbt.setModified();\n\n }\n });\n\n //or alert is cancelled\n alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Log.d(\"NBT tag creation cancelled\");\n }\n });\n\n alert.show();\n\n return;\n\n }\n default:{\n showMsg(R.string.sub_tags_only_add_compound_list);\n return;\n }\n }\n }\n default: {\n Log.d(\"User clicked unknown NBTEditOption! \"+editOption.name());\n }\n\n }\n } catch (Exception e) {\n showMsg(R.string.failed_to_do_NBT_change);\n }\n\n }\n });\n\n builder.show();\n return true;\n }\n return false;\n }\n });\n frame.addView(treeView, 0);\n\n\n\n // save functionality\n // ================================\n\n FloatingActionButton fabSaveNBT = (FloatingActionButton) rootView.findViewById(R.id.fab_save_nbt);\n assert fabSaveNBT != null;\n fabSaveNBT.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(final View view) {\n if(!nbt.isModified()){\n Snackbar.make(view, R.string.no_data_changed_nothing_to_save, Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n } else {\n new AlertDialog.Builder(activity)\n .setTitle(R.string.nbt_editor)\n .setMessage(R.string.confirm_nbt_editor_changes)\n .setIcon(R.drawable.ic_action_save_b)\n .setPositiveButton(android.R.string.yes,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n Snackbar.make(view, \"Saving NBT data...\", Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n if(nbt.save()){\n //nbt is not \"modified\" anymore, in respect to the new saved data\n nbt.modified = false;\n\n Snackbar.make(view, \"Saved NBT data!\", Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n ((WorldActivityInterface) activity).logFirebaseEvent(WorldActivity.CustomFirebaseEvent.NBT_EDITOR_SAVE);\n } else {\n Snackbar.make(view, \"Error: failed to save the NBT data.\", Snackbar.LENGTH_LONG)\n .setAction(\"Action\", null).show();\n }\n }})\n .setNegativeButton(android.R.string.no, null).show();\n }\n\n }\n });\n\n return rootView;\n }\n\n\n @Override\n public void onStart() {\n super.onStart();\n\n getActivity().setTitle(R.string.nbt_editor);\n\n Bundle bundle = new Bundle();\n bundle.putString(\"title\", nbt.getRootTitle());\n\n ((WorldActivityInterface) getActivity()).logFirebaseEvent(WorldActivity.CustomFirebaseEvent.NBT_EDITOR_OPEN, bundle);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n ((WorldActivityInterface) getActivity()).showActionBar();\n\n }\n}", "public class CompoundTag extends Tag<ArrayList<Tag>> {\n\n private static final long serialVersionUID = 4540757946052775740L;\n\n public CompoundTag(String name, ArrayList<Tag> value) {\n super(name, value);\n }\n\n @Override\n public NBTConstants.NBTType getType() {\n return NBTConstants.NBTType.COMPOUND;\n }\n\n\n public Tag getChildTagByKey(String key){\n List<Tag> list = getValue();\n if(list == null) return null;\n for(Tag tag : list){\n if(key.equals(tag.getName())) return tag;\n }\n return null;\n }\n\n public String toString(){\n String name = getName();\n String type = getType().name();\n ArrayList<Tag> value = getValue();\n StringBuilder bldr = new StringBuilder();\n bldr.append(type == null ? \"?\" : (\"TAG_\" + type))\n .append(name == null ? \"(?)\" : (\"(\" + name + \")\"));\n\n if(value != null) {\n bldr.append(\": \")\n .append(value.size())\n .append(\" entries\\n{\\n\");\n for (Tag entry : value) {\n //pad every line of the value\n bldr.append(\" \")\n .append(entry.toString().replaceAll(\"\\n\", \"\\n \"))\n .append(\"\\n\");\n }\n bldr.append(\"}\");\n\n } else bldr.append(\":?\");\n\n return bldr.toString();\n }\n\n @Override\n public CompoundTag getDeepCopy() {\n if(value != null){\n ArrayList<Tag> copy = new ArrayList<>();\n for(Tag tag : value){\n copy.add(tag.getDeepCopy());\n }\n return new CompoundTag(name, copy);\n } else return new CompoundTag(name, null);\n }\n\n}" ]
import android.app.AlertDialog; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.text.Editable; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import com.google.firebase.analytics.FirebaseAnalytics; import com.protolambda.blocktopograph.map.Dimension; import com.protolambda.blocktopograph.map.marker.AbstractMarker; import com.protolambda.blocktopograph.nbt.convert.NBTConstants; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.protolambda.blocktopograph.chunk.NBTChunkData; import com.protolambda.blocktopograph.map.MapFragment; import com.protolambda.blocktopograph.map.renderer.MapType; import com.protolambda.blocktopograph.nbt.EditableNBT; import com.protolambda.blocktopograph.nbt.EditorFragment; import com.protolambda.blocktopograph.nbt.convert.DataConverter; import com.protolambda.blocktopograph.nbt.tags.CompoundTag; import com.protolambda.blocktopograph.nbt.tags.Tag;
package com.protolambda.blocktopograph; public class WorldActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, WorldActivityInterface, MenuHelper.MenuContext { private World world;
private MapFragment mapFragment;
4
googlearchive/android-AutofillFramework
afservice/src/main/java/com/example/android/autofill/service/data/adapter/DatasetAdapter.java
[ "public final class AutofillHints {\n public static final int PARTITION_ALL = -1;\n public static final int PARTITION_OTHER = 0;\n public static final int PARTITION_ADDRESS = 1;\n public static final int PARTITION_EMAIL = 2;\n public static final int PARTITION_CREDIT_CARD = 3;\n public static final int[] PARTITIONS = {\n PARTITION_OTHER, PARTITION_ADDRESS, PARTITION_EMAIL, PARTITION_CREDIT_CARD\n };\n\n private AutofillHints() {\n }\n\n public static FilledAutofillField generateFakeField(\n FieldTypeWithHeuristics fieldTypeWithHeuristics, String packageName, int seed,\n String datasetId) {\n FakeData fakeData = fieldTypeWithHeuristics.fieldType.getFakeData();\n String fieldTypeName = fieldTypeWithHeuristics.fieldType.getTypeName();\n String text = null;\n Long date = null;\n Boolean toggle = null;\n if (fakeData.strictExampleSet != null && fakeData.strictExampleSet.strings != null &&\n fakeData.strictExampleSet.strings.size() > 0 &&\n !fakeData.strictExampleSet.strings.get(0).isEmpty()) {\n List<String> choices = fakeData.strictExampleSet.strings;\n text = choices.get(seed % choices.size());\n } else if (fakeData.textTemplate != null) {\n text = fakeData.textTemplate.replace(\"seed\", \"\" + seed)\n .replace(\"curr_time\", \"\" + Calendar.getInstance().getTimeInMillis());\n } else if (fakeData.dateTemplate != null) {\n if (fakeData.dateTemplate.contains(\"curr_time\")) {\n date = Calendar.getInstance().getTimeInMillis();\n }\n }\n return new FilledAutofillField(datasetId, fieldTypeName, text, date, toggle);\n }\n\n public static String getFieldTypeNameFromAutofillHints(\n HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint,\n @NonNull List<String> hints) {\n return getFieldTypeNameFromAutofillHints(fieldTypesByAutofillHint, hints, PARTITION_ALL);\n }\n\n public static String getFieldTypeNameFromAutofillHints(\n HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint,\n @NonNull List<String> hints, int partition) {\n List<String> fieldTypeNames = removePrefixes(hints)\n .stream()\n .filter(fieldTypesByAutofillHint::containsKey)\n .map(fieldTypesByAutofillHint::get)\n .filter(Objects::nonNull)\n .filter((fieldTypeWithHints) ->\n matchesPartition(fieldTypeWithHints.fieldType.getPartition(), partition))\n .map(FieldTypeWithHeuristics::getFieldType).map(FieldType::getTypeName)\n .collect(toList());\n if (fieldTypeNames != null && fieldTypeNames.size() > 0) {\n return fieldTypeNames.get(0);\n } else {\n return null;\n }\n }\n\n public static boolean matchesPartition(int partition, int otherPartition) {\n return partition == PARTITION_ALL || otherPartition == PARTITION_ALL ||\n partition == otherPartition;\n }\n\n private static List<String> removePrefixes(@NonNull List<String> hints) {\n List<String> hintsWithoutPrefixes = new ArrayList<>();\n String nextHint = null;\n for (int i = 0; i < hints.size(); i++) {\n String hint = hints.get(i);\n if (i < hints.size() - 1) {\n nextHint = hints.get(i + 1);\n }\n // First convert the compound W3C autofill hints\n if (isW3cSectionPrefix(hint) && i < hints.size() - 1) {\n i++;\n hint = hints.get(i);\n logd(\"Hint is a W3C section prefix; using %s instead\", hint);\n if (i < hints.size() - 1) {\n nextHint = hints.get(i + 1);\n }\n }\n if (isW3cTypePrefix(hint) && nextHint != null && isW3cTypeHint(nextHint)) {\n hint = nextHint;\n i++;\n logd(\"Hint is a W3C type prefix; using %s instead\", hint);\n }\n if (isW3cAddressType(hint) && nextHint != null) {\n hint = nextHint;\n i++;\n logd(\"Hint is a W3C address prefix; using %s instead\", hint);\n }\n hintsWithoutPrefixes.add(hint);\n }\n return hintsWithoutPrefixes;\n }\n\n private static boolean isW3cSectionPrefix(@NonNull String hint) {\n return hint.startsWith(W3cHints.PREFIX_SECTION);\n }\n\n private static boolean isW3cAddressType(@NonNull String hint) {\n switch (hint) {\n case W3cHints.SHIPPING:\n case W3cHints.BILLING:\n return true;\n }\n return false;\n }\n\n private static boolean isW3cTypePrefix(@NonNull String hint) {\n switch (hint) {\n case W3cHints.PREFIX_WORK:\n case W3cHints.PREFIX_FAX:\n case W3cHints.PREFIX_HOME:\n case W3cHints.PREFIX_PAGER:\n return true;\n }\n return false;\n }\n\n private static boolean isW3cTypeHint(@NonNull String hint) {\n switch (hint) {\n case W3cHints.TEL:\n case W3cHints.TEL_COUNTRY_CODE:\n case W3cHints.TEL_NATIONAL:\n case W3cHints.TEL_AREA_CODE:\n case W3cHints.TEL_LOCAL:\n case W3cHints.TEL_LOCAL_PREFIX:\n case W3cHints.TEL_LOCAL_SUFFIX:\n case W3cHints.TEL_EXTENSION:\n case W3cHints.EMAIL:\n case W3cHints.IMPP:\n return true;\n }\n logw(\"Invalid W3C type hint: %s\", hint);\n return false;\n }\n}", "public final class ClientParser {\n private final List<AssistStructure> mStructures;\n\n public ClientParser(@NonNull List<AssistStructure> structures) {\n Preconditions.checkNotNull(structures);\n mStructures = structures;\n }\n\n public ClientParser(@NonNull AssistStructure structure) {\n this(ImmutableList.of(structure));\n }\n\n /**\n * Traverses through the {@link AssistStructure} and does something at each {@link ViewNode}.\n *\n * @param processor contains action to be performed on each {@link ViewNode}.\n */\n public void parse(NodeProcessor processor) {\n for (AssistStructure structure : mStructures) {\n int nodes = structure.getWindowNodeCount();\n for (int i = 0; i < nodes; i++) {\n AssistStructure.ViewNode viewNode = structure.getWindowNodeAt(i).getRootViewNode();\n traverseRoot(viewNode, processor);\n }\n }\n }\n\n private void traverseRoot(AssistStructure.ViewNode viewNode, NodeProcessor processor) {\n processor.processNode(viewNode);\n int childrenSize = viewNode.getChildCount();\n if (childrenSize > 0) {\n for (int i = 0; i < childrenSize; i++) {\n traverseRoot(viewNode.getChildAt(i), processor);\n }\n }\n }\n\n public interface NodeProcessor {\n void processNode(ViewNode node);\n }\n}", "public class DatasetWithFilledAutofillFields {\n @Embedded\n public AutofillDataset autofillDataset;\n\n @Relation(parentColumn = \"id\", entityColumn = \"datasetId\", entity = FilledAutofillField.class)\n public List<FilledAutofillField> filledAutofillFields;\n\n public void add(FilledAutofillField filledAutofillField) {\n if (filledAutofillFields == null) {\n this.filledAutofillFields = new ArrayList<>();\n }\n this.filledAutofillFields.add(filledAutofillField);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n DatasetWithFilledAutofillFields that = (DatasetWithFilledAutofillFields) o;\n\n if (autofillDataset != null ? !autofillDataset.equals(that.autofillDataset) :\n that.autofillDataset != null)\n return false;\n return filledAutofillFields != null ?\n filledAutofillFields.equals(that.filledAutofillFields) :\n that.filledAutofillFields == null;\n }\n\n @Override\n public int hashCode() {\n int result = autofillDataset != null ? autofillDataset.hashCode() : 0;\n result = 31 * result + (filledAutofillFields != null ? filledAutofillFields.hashCode() : 0);\n return result;\n }\n}", "@Entity(primaryKeys = {\"typeName\"})\npublic class FieldType {\n @NonNull\n @ColumnInfo(name = \"typeName\")\n private final String mTypeName;\n\n @NonNull\n @ColumnInfo(name = \"autofillTypes\")\n private final IntList mAutofillTypes;\n\n @NonNull\n @ColumnInfo(name = \"saveInfo\")\n private final Integer mSaveInfo;\n\n @NonNull\n @ColumnInfo(name = \"partition\")\n private final Integer mPartition;\n\n @NonNull\n @Embedded\n private final FakeData mFakeData;\n\n public FieldType(@NonNull String typeName, @NonNull IntList autofillTypes,\n @NonNull Integer saveInfo, @NonNull Integer partition, @NonNull FakeData fakeData) {\n mTypeName = typeName;\n mAutofillTypes = autofillTypes;\n mSaveInfo = saveInfo;\n mPartition = partition;\n mFakeData = fakeData;\n }\n\n @NonNull\n public String getTypeName() {\n return mTypeName;\n }\n\n @NonNull\n public IntList getAutofillTypes() {\n return mAutofillTypes;\n }\n\n @NonNull\n public Integer getSaveInfo() {\n return mSaveInfo;\n }\n\n @NonNull\n public Integer getPartition() {\n return mPartition;\n }\n\n @NonNull\n public FakeData getFakeData() {\n return mFakeData;\n }\n}", "public class FieldTypeWithHeuristics {\n @Embedded\n public FieldType fieldType;\n\n @Relation(parentColumn = \"typeName\", entityColumn = \"fieldTypeName\", entity = AutofillHint.class)\n public List<AutofillHint> autofillHints;\n\n @Relation(parentColumn = \"typeName\", entityColumn = \"fieldTypeName\", entity = ResourceIdHeuristic.class)\n public List<ResourceIdHeuristic> resourceIdHeuristics;\n\n public FieldType getFieldType() {\n return fieldType;\n }\n\n public List<AutofillHint> getAutofillHints() {\n return autofillHints;\n }\n\n public List<ResourceIdHeuristic> getResourceIdHeuristics() {\n return resourceIdHeuristics;\n }\n}", "@Entity(primaryKeys = {\"datasetId\", \"fieldTypeName\"}, foreignKeys = {\n @ForeignKey(entity = AutofillDataset.class, parentColumns = \"id\",\n childColumns = \"datasetId\", onDelete = ForeignKey.CASCADE),\n @ForeignKey(entity = FieldType.class, parentColumns = \"typeName\",\n childColumns = \"fieldTypeName\", onDelete = ForeignKey.CASCADE)\n})\npublic class FilledAutofillField {\n\n @NonNull\n @ColumnInfo(name = \"datasetId\")\n private final String mDatasetId;\n\n @Nullable\n @ColumnInfo(name = \"textValue\")\n private final String mTextValue;\n\n @Nullable\n @ColumnInfo(name = \"dateValue\")\n private final Long mDateValue;\n\n @Nullable\n @ColumnInfo(name = \"toggleValue\")\n private final Boolean mToggleValue;\n\n @NonNull\n @ColumnInfo(name = \"fieldTypeName\")\n private final String mFieldTypeName;\n\n public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName,\n @Nullable String textValue, @Nullable Long dateValue,\n @Nullable Boolean toggleValue) {\n mDatasetId = datasetId;\n mFieldTypeName = fieldTypeName;\n mTextValue = textValue;\n mDateValue = dateValue;\n mToggleValue = toggleValue;\n }\n\n @Ignore\n public FilledAutofillField(@NonNull String datasetId,\n @NonNull String fieldTypeName, @Nullable String textValue, @Nullable Long dateValue) {\n this(datasetId, fieldTypeName, textValue, dateValue, null);\n }\n\n @Ignore\n public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName,\n @Nullable String textValue) {\n this(datasetId, fieldTypeName, textValue, null, null);\n }\n\n @Ignore\n public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName,\n @Nullable Long dateValue) {\n this(datasetId, fieldTypeName, null, dateValue, null);\n }\n\n @Ignore\n public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName,\n @Nullable Boolean toggleValue) {\n this(datasetId, fieldTypeName, null, null, toggleValue);\n }\n\n @Ignore\n public FilledAutofillField(@NonNull String datasetId, @NonNull String fieldTypeName) {\n this(datasetId, fieldTypeName, null, null, null);\n }\n\n @NonNull\n public String getDatasetId() {\n return mDatasetId;\n }\n\n @Nullable\n public String getTextValue() {\n return mTextValue;\n }\n\n @Nullable\n public Long getDateValue() {\n return mDateValue;\n }\n\n @Nullable\n public Boolean getToggleValue() {\n return mToggleValue;\n }\n\n @NonNull\n public String getFieldTypeName() {\n return mFieldTypeName;\n }\n\n public boolean isNull() {\n return mTextValue == null && mDateValue == null && mToggleValue == null;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n FilledAutofillField that = (FilledAutofillField) o;\n\n if (mTextValue != null ? !mTextValue.equals(that.mTextValue) : that.mTextValue != null)\n return false;\n if (mDateValue != null ? !mDateValue.equals(that.mDateValue) : that.mDateValue != null)\n return false;\n if (mToggleValue != null ? !mToggleValue.equals(that.mToggleValue) : that.mToggleValue != null)\n return false;\n return mFieldTypeName.equals(that.mFieldTypeName);\n }\n\n @Override\n public int hashCode() {\n int result = mTextValue != null ? mTextValue.hashCode() : 0;\n result = 31 * result + (mDateValue != null ? mDateValue.hashCode() : 0);\n result = 31 * result + (mToggleValue != null ? mToggleValue.hashCode() : 0);\n result = 31 * result + mFieldTypeName.hashCode();\n return result;\n }\n}", "public static int indexOf(@NonNull CharSequence[] array, CharSequence charSequence) {\n int index = -1;\n if (charSequence == null) {\n return index;\n }\n for (int i = 0; i < array.length; i++) {\n if (charSequence.equals(array[i])) {\n index = i;\n break;\n }\n }\n return index;\n}", "public static void logv(String message, Object... params) {\n if (logVerboseEnabled()) {\n Log.v(TAG, String.format(message, params));\n }\n}", "public static void logw(String message, Object... params) {\n Log.w(TAG, String.format(message, params));\n}" ]
import android.app.assist.AssistStructure; import android.content.IntentSender; import android.service.autofill.Dataset; import android.util.MutableBoolean; import android.view.View; import android.view.autofill.AutofillId; import android.view.autofill.AutofillValue; import android.widget.RemoteViews; import com.example.android.autofill.service.AutofillHints; import com.example.android.autofill.service.ClientParser; import com.example.android.autofill.service.model.DatasetWithFilledAutofillFields; import com.example.android.autofill.service.model.FieldType; import com.example.android.autofill.service.model.FieldTypeWithHeuristics; import com.example.android.autofill.service.model.FilledAutofillField; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import static com.example.android.autofill.service.util.Util.indexOf; import static com.example.android.autofill.service.util.Util.logv; import static com.example.android.autofill.service.util.Util.logw; import static java.util.stream.Collectors.toMap;
/* * Copyright (C) 2017 The Android Open Source Project * * 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 com.example.android.autofill.service.data.adapter; public class DatasetAdapter { private final ClientParser mClientParser; public DatasetAdapter(ClientParser clientParser) { mClientParser = clientParser; } /** * Wraps autofill data in a {@link Dataset} object which can then be sent back to the client. */ public Dataset buildDataset(HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, DatasetWithFilledAutofillFields datasetWithFilledAutofillFields, RemoteViews remoteViews) { return buildDataset(fieldTypesByAutofillHint, datasetWithFilledAutofillFields, remoteViews, null); } public Dataset buildDatasetForFocusedNode(FilledAutofillField filledAutofillField, FieldType fieldType, RemoteViews remoteViews) { Dataset.Builder datasetBuilder = new Dataset.Builder(remoteViews); boolean setAtLeastOneValue = bindDatasetToFocusedNode(filledAutofillField, fieldType, datasetBuilder); if (!setAtLeastOneValue) { return null; } return datasetBuilder.build(); } /** * Wraps autofill data in a {@link Dataset} object with an IntentSender, which can then be * sent back to the client. */ public Dataset buildDataset(HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, DatasetWithFilledAutofillFields datasetWithFilledAutofillFields, RemoteViews remoteViews, IntentSender intentSender) { Dataset.Builder datasetBuilder = new Dataset.Builder(remoteViews); if (intentSender != null) { datasetBuilder.setAuthentication(intentSender); } boolean setAtLeastOneValue = bindDataset(fieldTypesByAutofillHint, datasetWithFilledAutofillFields, datasetBuilder); if (!setAtLeastOneValue) { return null; } return datasetBuilder.build(); } /** * Build an autofill {@link Dataset} using saved data and the client's AssistStructure. */ private boolean bindDataset(HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, DatasetWithFilledAutofillFields datasetWithFilledAutofillFields, Dataset.Builder datasetBuilder) { MutableBoolean setValueAtLeastOnce = new MutableBoolean(false); Map<String, FilledAutofillField> filledAutofillFieldsByTypeName = datasetWithFilledAutofillFields.filledAutofillFields.stream() .collect(toMap(FilledAutofillField::getFieldTypeName, Function.identity())); mClientParser.parse((node) -> parseAutofillFields(node, fieldTypesByAutofillHint, filledAutofillFieldsByTypeName, datasetBuilder, setValueAtLeastOnce) ); return setValueAtLeastOnce.value; } private boolean bindDatasetToFocusedNode(FilledAutofillField field, FieldType fieldType, Dataset.Builder builder) { MutableBoolean setValueAtLeastOnce = new MutableBoolean(false); mClientParser.parse((node) -> { if (node.isFocused() && node.getAutofillId() != null) { bindValueToNode(node, field, builder, setValueAtLeastOnce); } }); return setValueAtLeastOnce.value; } private void parseAutofillFields(AssistStructure.ViewNode viewNode, HashMap<String, FieldTypeWithHeuristics> fieldTypesByAutofillHint, Map<String, FilledAutofillField> filledAutofillFieldsByTypeName, Dataset.Builder builder, MutableBoolean setValueAtLeastOnce) { String[] rawHints = viewNode.getAutofillHints(); if (rawHints == null || rawHints.length == 0) { logv("No af hints at ViewNode - %s", viewNode.getIdEntry()); return; } String fieldTypeName = AutofillHints.getFieldTypeNameFromAutofillHints( fieldTypesByAutofillHint, Arrays.asList(rawHints)); if (fieldTypeName == null) { return; } FilledAutofillField field = filledAutofillFieldsByTypeName.get(fieldTypeName); if (field == null) { return; } bindValueToNode(viewNode, field, builder, setValueAtLeastOnce); } void bindValueToNode(AssistStructure.ViewNode viewNode, FilledAutofillField field, Dataset.Builder builder, MutableBoolean setValueAtLeastOnce) { AutofillId autofillId = viewNode.getAutofillId(); if (autofillId == null) {
logw("Autofill ID null for %s", viewNode.toString());
8
DanielThomas/groundhog
proxy/src/main/java/io/groundhog/proxy/ProxyModule.java
[ "@Immutable\npublic enum URIScheme {\n HTTP(\"http\", 80),\n HTTPS(\"https\", 443);\n\n private final String scheme;\n private final int defaultPort;\n\n private URIScheme(String scheme, int defaultPort) {\n this.scheme = scheme;\n this.defaultPort = defaultPort;\n }\n\n public String scheme() {\n return scheme;\n }\n\n public int defaultPort() {\n return defaultPort;\n }\n\n public static URIScheme fromPort(int port) {\n Optional<URIScheme> uriScheme = fromPortInternal(port);\n checkArgument(uriScheme.isPresent(), \"No matching protocol scheme for port \" + port);\n return uriScheme.get();\n }\n\n public static URIScheme fromPortOrDefault(int port, URIScheme defaultScheme) {\n return fromPortInternal(port).or(defaultScheme);\n }\n\n private static Optional<URIScheme> fromPortInternal(int port) {\n checkArgument(port > 0, \"port must be greater than zero\");\n for (URIScheme scheme : values()) {\n if (scheme.defaultPort() == port) {\n return Optional.of(scheme);\n }\n }\n return Optional.absent();\n }\n}", "public interface CaptureController {\n boolean isControlRequest(HttpRequest request);\n\n FullHttpResponse handleControlRequest(HttpRequest request);\n}", "public interface CaptureWriter extends Service {\n /**\n * Write a request asynchronously.\n *\n * @param captureRequest the captured request to be written\n */\n public void writeAsync(CaptureRequest captureRequest);\n\n /**\n * Write a file upload. The write operation may block.\n *\n * @param fileUpload the {@link io.netty.handler.codec.http.multipart.FileUpload}\n * @param startedDateTime the time in milliseconds of the request that this upload is for\n */\n public void writeUpload(FileUpload fileUpload, long startedDateTime) throws IOException;\n}", "public class DefaultCaptureController implements CaptureController {\n private static final Logger LOG = LoggerFactory.getLogger(CaptureController.class);\n\n private final CaptureWriter captureWriter;\n\n @Inject\n public DefaultCaptureController(CaptureWriter captureWriter) {\n this.captureWriter = checkNotNull(captureWriter);\n }\n\n @Override\n public boolean isControlRequest(HttpRequest request) {\n checkNotNull(request);\n return request.getUri().startsWith(\"/groundhog\");\n }\n\n @Override\n public FullHttpResponse handleControlRequest(HttpRequest request) {\n checkNotNull(request);\n checkNotNull(captureWriter);\n\n List<String> parts = Splitter.on('/').limit(3).splitToList(request.getUri());\n if (parts.size() != 3) {\n return statusResponse(Service.State.FAILED, \"No command provided, expected /groundhog/<command>\");\n }\n\n String command = parts.get(2);\n switch (command) {\n case \"start\": {\n if (captureWriter.isRunning()) {\n return statusResponse(Service.State.FAILED, \"Capture is already running\");\n } else if (Service.State.NEW == captureWriter.state()) {\n captureWriter.startAsync();\n captureWriter.awaitRunning();\n return statusResponse(Service.State.RUNNING, \"Started capture\");\n } else {\n return statusResponse(Service.State.FAILED, \"Capture has already completed, and is a one shot service\");\n }\n }\n case \"stop\": {\n if (captureWriter.isRunning()) {\n captureWriter.stopAsync();\n captureWriter.awaitTerminated();\n return statusResponse(Service.State.TERMINATED, \"Stopped capture\");\n } else {\n return statusResponse(Service.State.FAILED, \"Capture is not running\");\n }\n }\n case \"status\": {\n return statusResponse(captureWriter.state(), \"Success\");\n }\n default: {\n return statusResponse(Service.State.FAILED, \"Unknown command: \" + command);\n }\n }\n }\n\n private static FullHttpResponse statusResponse(Service.State state, String message) {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n JsonFactory jsonFactory = new JsonFactory();\n JsonGenerator generator;\n try {\n generator = jsonFactory.createGenerator(outputStream);\n } catch (IOException e) {\n String errorMessage = \"Could not create JSON generator\";\n LOG.error(errorMessage, e);\n return errorResponse(errorMessage);\n }\n\n try {\n generator.writeStartObject();\n generator.writeStringField(\"state\", state.toString());\n generator.writeStringField(\"message\", message);\n generator.writeEndObject();\n generator.close();\n } catch (IOException e) {\n String errorMessage = \"Error writing\";\n LOG.error(errorMessage, e);\n return errorResponse(errorMessage);\n }\n\n ByteBuf content = Unpooled.wrappedBuffer(outputStream.toByteArray());\n FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);\n response.headers().set(HttpHeaders.Names.CONTENT_TYPE, \"text/html\");\n return response;\n }\n\n private static FullHttpResponse errorResponse(String message) {\n ByteBuf content = Unpooled.copiedBuffer(message, Charsets.UTF_8);\n FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, content);\n response.headers().set(HttpHeaders.Names.CONTENT_TYPE, \"text/html\");\n return response;\n }\n}", "public class HarFileCaptureWriter extends AbstractExecutionThreadService implements CaptureWriter {\n private static final Logger LOG = LoggerFactory.getLogger(CaptureWriter.class);\n\n private static final Set<String> MINIMUM_RESPONSE_HEADERS = Sets.newHashSet(HttpHeaders.Names.SET_COOKIE, HttpHeaders.Names.LOCATION);\n\n private final File outputLocation;\n private final BlockingQueue<CaptureRequest> requestQueue;\n private final boolean lightweight;\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final boolean includeContent;\n private final boolean pretty;\n private final boolean gzip;\n private final DateFormat iso8601Format;\n\n private File uploadLocation;\n private JsonGenerator generator;\n\n public HarFileCaptureWriter(File outputLocation, boolean lightweight, boolean includeContent, boolean pretty, boolean gzip) {\n this(outputLocation, lightweight, includeContent, pretty, gzip, new LinkedBlockingQueue<CaptureRequest>());\n }\n\n HarFileCaptureWriter(File outputLocation, boolean lightweight, boolean includeContent, boolean pretty, boolean gzip, BlockingQueue<CaptureRequest> requestQueue) {\n this.outputLocation = checkNotNull(outputLocation);\n this.lightweight = lightweight;\n this.includeContent = includeContent;\n this.pretty = pretty;\n this.gzip = gzip;\n this.requestQueue = checkNotNull(requestQueue);\n\n if (lightweight) {\n checkArgument(!this.includeContent, \"Content cannot be included in lightweight recordings\");\n }\n\n TimeZone tz = TimeZone.getTimeZone(\"UTC\");\n iso8601Format = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\");\n iso8601Format.setTimeZone(tz);\n }\n\n @Override\n protected String serviceName() {\n return getClass().getSimpleName();\n }\n\n @Override\n protected void startUp() throws Exception {\n LOG.info(\"Writer starting up\");\n checkArgument(outputLocation.isDirectory(), \"Output location must be a directory\");\n String hostName = InetAddress.getLocalHost().getHostName();\n File outputDir = new File(outputLocation, hostName + \"-\" + System.currentTimeMillis());\n if (!outputDir.mkdirs()) {\n throw new IOException(\"Could not create directory \" + outputDir);\n }\n uploadLocation = new File(outputDir, \"uploads\");\n File outputFile = new File(outputDir, gzip ? \"capture.har.gz\" : \"capture.har\");\n OutputStream outputStream = gzip ? new GZIPOutputStream(new FileOutputStream(outputFile)) : new FileOutputStream(outputFile);\n JsonFactory jsonFactory = new JsonFactory();\n generator = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);\n if (pretty) {\n generator.setPrettyPrinter(new DefaultPrettyPrinter());\n }\n LOG.info(\"Created JSON generator for {}\", outputFile);\n writeLogStart();\n }\n\n @Override\n protected void shutDown() throws Exception {\n LOG.info(\"Writer shutting down\");\n while (!requestQueue.isEmpty()) {\n LOG.info(\"Waiting for request queue to be drained...\");\n Thread.sleep(1000);\n }\n writeLogEnd();\n generator.close();\n checkState(requestQueue.isEmpty(), \"The request queue should have been drained before shutdown\");\n }\n\n @Override\n public String toString() {\n return super.toString() + \" \" + outputLocation;\n }\n\n @Override\n protected void run() throws InterruptedException, IOException {\n while (isRunning() || !requestQueue.isEmpty()) {\n CaptureRequest request = requestQueue.poll(1, TimeUnit.SECONDS);\n if (null != request) {\n writeEntry(request);\n }\n }\n }\n\n private void writeLogStart() throws IOException {\n generator.writeStartObject();\n generator.writeObjectFieldStart(\"log\");\n generator.writeStringField(\"version\", \"1.2\");\n writeCreator();\n generator.writeArrayFieldStart(\"entries\");\n }\n\n private void writeCreator() throws IOException {\n generator.writeObjectFieldStart(\"creator\");\n generator.writeStringField(\"name\", \"Groundhog Capture\");\n generator.writeStringField(\"version\", Groundhog.getVersion());\n if (lightweight) {\n generator.writeStringField(\"comment\", \"lightweight\");\n }\n generator.writeEndObject();\n }\n\n private void writeLogEnd() throws IOException {\n generator.writeEndArray();\n generator.writeEndObject();\n }\n\n @Override\n public void writeAsync(CaptureRequest captureRequest) {\n checkNotNull(captureRequest);\n if (isRunning()) {\n requestQueue.add(captureRequest);\n }\n }\n\n @Override\n public void writeUpload(FileUpload fileUpload, long startedDateTime) throws IOException {\n checkNotNull(fileUpload);\n if (isRunning()) {\n checkNotNull(uploadLocation, \"Upload location is null\");\n File destDir = new File(uploadLocation, String.valueOf(startedDateTime));\n if (!destDir.mkdirs()) {\n throw new IOException(\"Did not successfully create upload location \" + destDir);\n }\n File destFile = new File(destDir, fileUpload.getFilename());\n fileUpload.renameTo(destFile);\n }\n }\n\n private void writeEntry(CaptureRequest captureRequest) throws IOException {\n generator.writeStartObject();\n String startedDateTime = iso8601Format.format(new Date(captureRequest.getStartedDateTime()));\n generator.writeStringField(\"startedDateTime\", startedDateTime);\n writeRequest(captureRequest);\n writeResponse(captureRequest);\n generator.writeEndObject();\n generator.flush();\n }\n\n private void writeRequest(CaptureRequest captureRequest) throws IOException {\n generator.writeObjectFieldStart(\"request\");\n HttpRequest request = captureRequest.getRequest();\n\n if (lightweight && HttpArchive.DEFAULT_METHOD != request.getMethod()) {\n generator.writeStringField(\"method\", request.getMethod().name());\n }\n generator.writeStringField(\"url\", captureRequest.getRequest().getUri());\n if (lightweight && HttpArchive.DEFAULT_HTTP_VERSION != request.getProtocolVersion()) {\n generator.writeStringField(\"httpVersion\", request.getProtocolVersion().text());\n }\n\n HttpHeaders headers = request.headers();\n writeHeaders(headers, false);\n writeCookies(headers);\n\n if (captureRequest instanceof DefaultCapturePostRequest) {\n DefaultCapturePostRequest proxyPostRequest = (DefaultCapturePostRequest) captureRequest;\n writePostData(proxyPostRequest);\n }\n generator.writeEndObject();\n }\n\n private void writeResponse(CaptureRequest captureRequest) throws IOException {\n generator.writeObjectFieldStart(\"response\");\n HttpResponse response = captureRequest.getResponse();\n HttpHeaders headers = response.headers();\n generator.writeNumberField(\"status\", response.getStatus().code());\n writeHeaders(headers, lightweight);\n writeCookies(headers);\n generator.writeEndObject();\n }\n\n private void writeHeaders(HttpHeaders headers, final boolean minimumOnly) throws IOException {\n Predicate<Map.Entry<String, String>> excludeHeader = new Predicate<Map.Entry<String, String>>() {\n @Override\n public boolean apply(@Nullable Map.Entry<String, String> input) {\n String name = null == input ? \"\" : input.getKey();\n return minimumOnly && !MINIMUM_RESPONSE_HEADERS.contains(name);\n }\n };\n\n Iterator<Map.Entry<String, String>> it = FluentIterable.from(headers).filter(Predicates.not(excludeHeader)).iterator();\n if (it.hasNext()) {\n generator.writeArrayFieldStart(\"headers\");\n while (it.hasNext()) {\n Map.Entry<String, String> entry = it.next();\n generator.writeStartObject();\n generator.writeStringField(\"name\", entry.getKey());\n generator.writeStringField(\"value\", entry.getValue());\n generator.writeEndObject();\n }\n generator.writeEndArray();\n }\n }\n\n private void writeCookies(HttpHeaders headers) throws IOException {\n if (lightweight) {\n return;\n }\n\n if (headers.contains(HttpHeaders.Names.COOKIE)) {\n generator.writeArrayFieldStart(\"cookies\");\n Set<Cookie> cookies = CookieDecoder.decode(headers.get(HttpHeaders.Names.COOKIE));\n for (Cookie cookie : cookies) {\n generator.writeStartObject();\n generator.writeStringField(\"name\", cookie.getName());\n generator.writeStringField(\"value\", cookie.getValue());\n if (null != cookie.getPath()) {\n generator.writeStringField(\"path\", cookie.getPath());\n }\n if (null != cookie.getDomain()) {\n generator.writeStringField(\"domain\", cookie.getDomain());\n }\n if (Long.MIN_VALUE != cookie.getMaxAge()) {\n generator.writeStringField(\"expires\", iso8601Format.format(new Date(cookie.getMaxAge())));\n }\n if (cookie.isHttpOnly()) {\n generator.writeBooleanField(\"httpOnly\", true);\n }\n if (cookie.isSecure()) {\n generator.writeBooleanField(\"secure\", true);\n }\n generator.writeEndObject();\n }\n generator.writeEndArray();\n }\n }\n\n private void writePostData(DefaultCapturePostRequest captureRequest) throws IOException {\n HttpHeaders headers = captureRequest.getRequest().headers();\n generator.writeObjectFieldStart(\"postData\");\n generator.writeStringField(\"mimeType\", headers.get(HttpHeaders.Names.CONTENT_TYPE));\n\n if (!captureRequest.getContent().isEmpty()) {\n generator.writeStringField(\"text\", captureRequest.getContent());\n }\n\n if (!captureRequest.getParams().isEmpty()) {\n generator.writeArrayFieldStart(\"params\");\n List<HttpArchive.Param> params = captureRequest.getParams();\n for (HttpArchive.Param param : params) {\n generator.writeStartObject();\n writeMandatoryStringField(\"name\", param.getName());\n writeOptionalStringField(\"value\", param.getValue());\n writeOptionalStringField(\"fileName\", param.getFileName());\n writeOptionalStringField(\"contentType\", param.getContentType());\n writeOptionalStringField(\"comment\", param.getComment());\n generator.writeEndObject();\n }\n generator.writeEndArray();\n }\n generator.writeEndObject();\n }\n\n private void writeMandatoryStringField(String fieldName, String value) throws IOException {\n checkArgument(!value.isEmpty(), \"A value must be set for field '%s'\", fieldName);\n writeOptionalStringField(fieldName, value);\n }\n\n private void writeOptionalStringField(String fieldName, String value) throws IOException {\n checkNotNull(fieldName);\n checkNotNull(value);\n if (!value.isEmpty()) {\n generator.writeStringField(fieldName, value);\n }\n }\n}" ]
import io.groundhog.base.URIScheme; import io.groundhog.capture.CaptureController; import io.groundhog.capture.CaptureWriter; import io.groundhog.capture.DefaultCaptureController; import io.groundhog.har.HarFileCaptureWriter; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.net.HostAndPort; import com.google.inject.AbstractModule; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.name.Names; import io.netty.channel.ChannelHandler; import org.littleshoot.proxy.HttpFiltersSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Properties; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull;
package io.groundhog.proxy; public class ProxyModule extends AbstractModule { private static final Logger LOG = LoggerFactory.getLogger(ProxyModule.class); private static final int PARENT_LIMIT = 2; private static final String PROPERTIES_FILENAME = "conf/config.properties"; @Override protected void configure() { Properties properties = new Properties(); try { // Depending on the type of distribution, the conf directory can be one or two directories up File parentDir = new File(System.getProperty("user.dir")); Optional<File> configFile = findConfigInParent(parentDir, PARENT_LIMIT); File propertiesFile; if (!configFile.isPresent()) { propertiesFile = new File("src/dist", PROPERTIES_FILENAME); // Gradle application run task if (!propertiesFile.exists()) { propertiesFile = new File("proxy/src/dist", PROPERTIES_FILENAME); // IntelliJ launch } LOG.warn("Could not locate {} in current or parent directories up to {} levels deep. Falling back to developer config {}", PROPERTIES_FILENAME, PARENT_LIMIT, propertiesFile); } else { propertiesFile = configFile.get(); } properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { LOG.error("Failed to load properties file"); Throwables.propagate(e); } for (String addressType : Arrays.asList("target", "listen")) { String host = properties.getProperty(addressType + ".address"); for (URIScheme uriScheme : URIScheme.values()) { String prefix = addressType + "." + uriScheme.scheme(); int port = Integer.valueOf(properties.getProperty(prefix + "_port")); bind(HostAndPort.class).annotatedWith(Names.named(prefix)).toInstance(HostAndPort.fromParts(host, port)); } } File outputLocation = new File(properties.getProperty("output.location")); checkArgument(outputLocation.isDirectory(), "output.location must be a directory and must exist"); String outputCompression = properties.getProperty("output.compression"); CaptureWriter captureWriter = new HarFileCaptureWriter(outputLocation, true, false, false, "gzip".equals(outputCompression)); bind(CaptureWriter.class).toInstance(captureWriter);
bind(CaptureController.class).to(DefaultCaptureController.class);
1
alex73/OSMemory
src/org/alex73/osmemory/geometry/OsmHelper.java
[ "public interface IOsmNode extends IOsmObject {\n public static final double DIVIDER = 0.0000001;\n\n /**\n * Get latitude as int, i.e. multiplied by 10000000.\n */\n int getLat();\n\n /**\n * Get longitude as int, i.e. multiplied by 10000000.\n */\n int getLon();\n\n /**\n * Get latitude as double, like 53.9.\n */\n double getLatitude();\n\n /**\n * Get latitude as double, like 27.566667.\n */\n double getLongitude();\n}", "public interface IOsmObject {\n public static final int TYPE_NODE = 1;\n public static final int TYPE_WAY = 2;\n public static final int TYPE_RELATION = 3;\n\n /**\n * Object type: 1-node, 2-way,3-relation. It should be int instead enum for performance optimization.\n */\n int getType();\n\n boolean isNode();\n\n boolean isWay();\n\n boolean isRelation();\n\n /**\n * Object ID.\n */\n long getId();\n\n /**\n * Object ID as object.\n */\n IOsmObjectID getObjectID();\n\n /**\n * Check if object has tag.\n */\n boolean hasTag(short tagKey);\n\n /**\n * Get tags list.\n */\n short[] getTags();\n\n /**\n * Check if object has tag. This operation is much slower than {@link #hasTag(short)}.\n */\n boolean hasTag(String tagName, MemoryStorage storage);\n\n /**\n * Get tag value.\n */\n String getTag(short tagKey);\n\n /**\n * Get tag value. This operation is much slower than {@link #getTag(short)}.\n */\n String getTag(String tagName, MemoryStorage storage);\n\n Map<String, String> extractTags(MemoryStorage storage);\n\n /**\n * Get object code, like n123, w75, r51.\n */\n String getObjectCode();\n\n /**\n * Get user code.\n */\n short getUser();\n\n /**\n * Get user name.\n */\n String getUser(MemoryStorage storage);\n\n static String getNodeCode(long nodeId) {\n return \"n\" + nodeId;\n }\n\n static String getWayCode(long wayId) {\n return \"w\" + wayId;\n }\n\n static String getRelationCode(long relationId) {\n return \"r\" + relationId;\n }\n}", "public interface IOsmRelation extends IOsmObject {\n /**\n * Get members count.\n */\n int getMembersCount();\n\n /**\n * Get member object by index.\n */\n IOsmObject getMemberObject(MemoryStorage storage, int index);\n\n int getMemberType(int memberIndex);\n\n long getMemberID(int memberIndex);\n\n String getMemberRole(MemoryStorage storage, int memberIndex);\n\n String getMemberCode(int memberIndex);\n}", "public interface IOsmWay extends IOsmObject {\n /**\n * Get nodes IDs.\n */\n long[] getNodeIds();\n}", "public class MemoryStorage {\n static final Pattern RE_OBJECT_CODE = Pattern.compile(\"([nwr])([0-9]+)\");\n\n // notes with tags sorted list\n protected final List<IOsmNode> nodes = new ArrayList<>();\n // ways sorted list\n protected final List<IOsmWay> ways = new ArrayList<>();\n // relations sorted list\n protected final List<IOsmRelation> relations = new ArrayList<>();\n\n // simple nodes, i.e. without tags\n protected long[] simpleNodeIds = new long[4 * 1024 * 1024];\n protected int[] simpleNodeLats = new int[4 * 1024 * 1024];\n protected int[] simpleNodeLons = new int[4 * 1024 * 1024];\n protected int simpleNodeCount;\n\n private final StringPack tagsPack = new StringPack();\n private final StringPack relationRolesPack = new StringPack();\n private final StringPack usersPack = new StringPack();\n\n private long loadingStartTime, loadingFinishTime;\n\n public MemoryStorage() {\n loadingStartTime = System.currentTimeMillis();\n }\n\n /**\n * Must be called after load data for optimization and some internal processing.\n */\n void finishLoading() throws Exception {\n // check ID order\n long prev = 0;\n for (int i = 0; i < simpleNodeCount; i++) {\n long id = simpleNodeIds[i];\n if (id <= prev) {\n throw new Exception(\"Nodes must be ordered by ID\");\n }\n prev = id;\n }\n prev = 0;\n for (int i = 0; i < nodes.size(); i++) {\n long id = nodes.get(i).getId();\n if (id <= prev) {\n throw new Exception(\"Nodes must be ordered by ID\");\n }\n prev = id;\n }\n prev = 0;\n for (int i = 0; i < ways.size(); i++) {\n long id = ways.get(i).getId();\n if (id <= prev) {\n throw new Exception(\"Ways must be ordered by ID\");\n }\n prev = id;\n }\n prev = 0;\n for (int i = 0; i < relations.size(); i++) {\n long id = relations.get(i).getId();\n if (id <= prev) {\n throw new Exception(\"Relations must be ordered by ID\");\n }\n prev = id;\n }\n loadingFinishTime = System.currentTimeMillis();\n }\n\n public StringPack getTagsPack() {\n return tagsPack;\n }\n\n public StringPack getRelationRolesPack() {\n return relationRolesPack;\n }\n\n public StringPack getUsersPack() {\n return usersPack;\n }\n\n private static <T extends IOsmObject> T getById(List<T> en, long id) {\n int i = binarySearch(en, id);\n return i < 0 ? null : en.get(i);\n }\n\n private static <T extends IOsmObject> void remove(List<T> en, long id) {\n int i = binarySearch(en, id);\n if (i >= 0) {\n en.remove(i);\n }\n }\n\n private static <T extends IOsmObject> int binarySearch(List<T> en, long id) {\n int low = 0;\n int high = en.size() - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n long midvalue = en.get(mid).getId();\n\n if (midvalue < id)\n low = mid + 1;\n else if (midvalue > id)\n high = mid - 1;\n else\n return mid;\n }\n return -1;\n }\n\n private static <T extends IOsmObject> int getPositionForInsert(List<T> en, long id) {\n int low = 0;\n int high = en.size() - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n long midvalue = en.get(mid).getId();\n\n if (midvalue < id)\n low = mid + 1;\n else if (midvalue > id)\n high = mid - 1;\n else\n throw new RuntimeException(\"Object already exist\");\n }\n if (low >= en.size()) {\n return en.size();\n }\n long lowValue = en.get(low).getId();\n if (lowValue > id) {\n return low;\n } else {\n return low - 1;\n }\n }\n\n private static <T extends IOsmObject> int getPositionForInsert(long[] ids, int idscount, long id) {\n int low = 0;\n int high = idscount - 1;\n\n while (low <= high) {\n int mid = (low + high) >>> 1;\n long midvalue = ids[mid];\n\n if (midvalue < id)\n low = mid + 1;\n else if (midvalue > id)\n high = mid - 1;\n else\n throw new RuntimeException(\"Object already exist\");\n }\n if (low >= idscount) {\n return idscount;\n }\n long lowValue = ids[low];\n if (lowValue > id) {\n return low;\n } else {\n return low - 1;\n }\n }\n\n public IOsmNode getNodeById(long id) {\n int pos = Arrays.binarySearch(simpleNodeIds, 0, simpleNodeCount, id);\n if (pos >= 0) {\n return new OsmSimpleNode(this, pos);\n } else {\n return getById(nodes, id);\n }\n }\n\n /**\n * Remove node.\n */\n void removeNode(long id) {\n int pos = Arrays.binarySearch(simpleNodeIds, 0, simpleNodeCount, id);\n if (pos >= 0) {\n System.arraycopy(simpleNodeIds, pos + 1, simpleNodeIds, pos, simpleNodeCount - pos - 1);\n System.arraycopy(simpleNodeLats, pos + 1, simpleNodeLats, pos, simpleNodeCount - pos - 1);\n System.arraycopy(simpleNodeLons, pos + 1, simpleNodeLons, pos, simpleNodeCount - pos - 1);\n simpleNodeCount--;\n } else {\n remove(nodes, id);\n }\n }\n\n /**\n * Add or update node.\n */\n void addSimpleNode(long id, int lat, int lon) {\n int pos = Arrays.binarySearch(simpleNodeIds, 0, simpleNodeCount, id);\n if (pos < 0) {\n removeNode(id);\n if (simpleNodeIds.length == simpleNodeCount) {\n // extend simple nodes\n simpleNodeIds = Arrays.copyOf(simpleNodeIds, simpleNodeIds.length + 4096);\n simpleNodeLats = Arrays.copyOf(simpleNodeLats, simpleNodeLats.length + 4096);\n simpleNodeLons = Arrays.copyOf(simpleNodeLons, simpleNodeLons.length + 4096);\n }\n pos = getPositionForInsert(simpleNodeIds, simpleNodeCount, id);\n System.arraycopy(simpleNodeIds, pos, simpleNodeIds, pos + 1, simpleNodeCount - pos);\n System.arraycopy(simpleNodeLats, pos, simpleNodeLats, pos + 1, simpleNodeCount - pos);\n System.arraycopy(simpleNodeLons, pos, simpleNodeLons, pos + 1, simpleNodeCount - pos);\n simpleNodeCount++;\n }\n\n simpleNodeIds[pos] = id;\n simpleNodeLats[pos] = lat;\n simpleNodeLons[pos] = lon;\n }\n\n /**\n * Add or update node.\n */\n void addNode(IOsmNode n) {\n int posComplex = binarySearch(nodes, n.getId());\n if (posComplex >= 0) {\n nodes.set(posComplex, n);\n } else {\n removeNode(n.getId());\n int pos = getPositionForInsert(nodes, n.getId());\n nodes.add(pos, n);\n }\n }\n\n public IOsmWay getWayById(long id) {\n return getById(ways, id);\n }\n\n /**\n * Remove way.\n */\n void removeWay(long id) {\n remove(ways, id);\n }\n\n /**\n * Add or update way.\n */\n void addWay(IOsmWay w) {\n int pos = binarySearch(ways, w.getId());\n if (pos >= 0) {\n ways.set(pos, w);\n } else {\n pos = getPositionForInsert(ways, w.getId());\n ways.add(pos, w);\n }\n }\n\n public IOsmRelation getRelationById(long id) {\n return getById(relations, id);\n }\n\n /**\n * Remove relation.\n */\n void removeRelation(long id) {\n remove(relations, id);\n }\n\n /**\n * Add or update relation.\n */\n void addRelation(IOsmRelation r) {\n int pos = binarySearch(relations, r.getId());\n if (pos >= 0) {\n relations.set(pos, r);\n } else {\n pos = getPositionForInsert(relations, r.getId());\n relations.add(pos, r);\n }\n }\n\n /**\n * Get object by code like n123, w456, r789.\n */\n public IOsmObject getObject(String code) {\n Matcher m = RE_OBJECT_CODE.matcher(code.trim());\n if (!m.matches()) {\n throw new RuntimeException(\"Няправільны фарматы code: \" + code);\n }\n long idl = Long.parseLong(m.group(2));\n switch (m.group(1)) {\n case \"n\":\n return getNodeById(idl);\n case \"w\":\n return getWayById(idl);\n case \"r\":\n return getRelationById(idl);\n default:\n throw new RuntimeException(\"Wrong code format: \" + code);\n }\n }\n\n /**\n * Get object by Object ID.\n */\n public IOsmObject getObject(IOsmObjectID objID) {\n switch (objID.getType()) {\n case IOsmObject.TYPE_NODE:\n return getNodeById(objID.getId());\n case IOsmObject.TYPE_WAY:\n return getWayById(objID.getId());\n case IOsmObject.TYPE_RELATION:\n return getRelationById(objID.getId());\n default:\n throw new RuntimeException(\"Wrong type: \" + objID.getType());\n }\n }\n\n /**\n * Show some loading statistics.\n */\n public void showStat() {\n DecimalFormat f = new DecimalFormat(\",##0\");\n System.out.println(\"Loading time : \" + f.format((loadingFinishTime - loadingStartTime)) + \"ms\");\n System.out.println(\"Simple nodes count : \" + f.format(simpleNodeCount));\n System.out.println(\"Nodes count : \" + f.format(nodes.size()));\n System.out.println(\"Ways count : \" + f.format(ways.size()));\n System.out.println(\"Relations count : \" + f.format(relations.size()));\n System.out.println(\"Tags count : \" + f.format(tagsPack.tagCodes.size()));\n System.out.println(\"RelRoles count : \" + f.format(relationRolesPack.tagCodes.size()));\n System.out.println(\"Users count : \" + f.format(usersPack.tagCodes.size()));\n }\n\n /**\n * Process objects with specific tag.\n */\n public void byTag(String tagName, Predicate<IOsmObject> predicate, Consumer<IOsmObject> consumer) {\n short tagKey = tagsPack.getTagCode(tagName);\n for (int i = 0; i < nodes.size(); i++) {\n IOsmNode n = nodes.get(i);\n if (n.hasTag(tagKey)) {\n if (predicate.test(n)) {\n consumer.accept(n);\n }\n }\n }\n for (int i = 0; i < ways.size(); i++) {\n IOsmWay w = ways.get(i);\n if (w.hasTag(tagKey)) {\n if (predicate.test(w)) {\n consumer.accept(w);\n }\n }\n }\n for (int i = 0; i < relations.size(); i++) {\n IOsmRelation r = relations.get(i);\n if (r.hasTag(tagKey)) {\n if (predicate.test(r)) {\n consumer.accept(r);\n }\n }\n }\n }\n\n /**\n * Process objects with specific tag.\n */\n public void byTag(String tagName, Consumer<IOsmObject> consumer) {\n short tagKey = tagsPack.getTagCode(tagName);\n for (int i = 0; i < nodes.size(); i++) {\n IOsmNode n = nodes.get(i);\n if (n.hasTag(tagKey)) {\n consumer.accept(n);\n }\n }\n for (int i = 0; i < ways.size(); i++) {\n IOsmWay w = ways.get(i);\n if (w.hasTag(tagKey)) {\n consumer.accept(w);\n }\n }\n for (int i = 0; i < relations.size(); i++) {\n IOsmRelation r = relations.get(i);\n if (r.hasTag(tagKey)) {\n consumer.accept(r);\n }\n }\n }\n\n /**\n * Process all objects.\n */\n public void all(Predicate<IOsmObject> predicate, Consumer<IOsmObject> consumer) {\n for (int i = 0; i < nodes.size(); i++) {\n IOsmNode n = nodes.get(i);\n if (predicate.test(n)) {\n consumer.accept(n);\n }\n }\n for (int i = 0; i < ways.size(); i++) {\n IOsmWay w = ways.get(i);\n if (predicate.test(w)) {\n consumer.accept(w);\n }\n }\n for (int i = 0; i < relations.size(); i++) {\n IOsmRelation r = relations.get(i);\n if (predicate.test(r)) {\n consumer.accept(r);\n }\n }\n }\n\n /**\n * Process all objects.\n */\n public void all(Consumer<IOsmObject> consumer) {\n all(new Predicate<IOsmObject>() {\n @Override\n public boolean test(IOsmObject t) {\n return true;\n }\n }, consumer);\n }\n}" ]
import org.alex73.osmemory.IOsmNode; import org.alex73.osmemory.IOsmObject; import org.alex73.osmemory.IOsmRelation; import org.alex73.osmemory.IOsmWay; import org.alex73.osmemory.MemoryStorage; import com.vividsolutions.jts.geom.Geometry;
/************************************************************************** OSMemory library for OSM data processing. Copyright (C) 2014 Aleś Bułojčyk <alex73mail@gmail.com> This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ package org.alex73.osmemory.geometry; /** * Creates area geometry from way or relation. */ public class OsmHelper { public static Geometry areaFromObject(IOsmObject obj, MemoryStorage osm) { if (obj.isWay()) {
return new ExtendedWay((IOsmWay) obj, osm).getArea();
3
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/orgdata/MobileOrgApplication.java
[ "public class SyncService extends Service implements\n\t\tSharedPreferences.OnSharedPreferenceChangeListener {\n\tprivate static final String ACTION = \"action\";\n\tprivate static final String START_ALARM = \"START_ALARM\";\n\tprivate static final String STOP_ALARM = \"STOP_ALARM\";\n\n\tprivate SharedPreferences appSettings;\n\tprivate MobileOrgApplication appInst;\n\n\tprivate AlarmManager alarmManager;\n\tprivate PendingIntent alarmIntent;\n\tprivate boolean alarmScheduled = false;\n\n\tprivate boolean syncRunning;\n\n\tpublic static void stopAlarm(Context context) {\n\t\tIntent intent = new Intent(context, SyncService.class);\n\t\tintent.putExtra(ACTION, SyncService.STOP_ALARM);\n\t\tcontext.startService(intent);\n\t}\n\n\tpublic static void startAlarm(Context context) {\n\t\tIntent intent = new Intent(context, SyncService.class);\n\t\tintent.putExtra(ACTION, SyncService.START_ALARM);\n\t\tcontext.startService(intent);\n\t}\n\t\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\tthis.appSettings = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(getApplicationContext());\n\t\tthis.appSettings.registerOnSharedPreferenceChangeListener(this);\n\t\tthis.appInst = (MobileOrgApplication) this.getApplication();\n\t\tthis.alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tunsetAlarm();\n\t\tthis.appSettings.unregisterOnSharedPreferenceChangeListener(this);\n\t\tsuper.onDestroy();\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif( intent == null ) return 0;\n\t\tString action = intent.getStringExtra(ACTION);\n\t\tif (action != null && action.equals(START_ALARM))\n\t\t\tsetAlarm();\n\t\telse if (action != null && action.equals(STOP_ALARM))\n\t\t\tunsetAlarm();\n\t\telse if(!this.syncRunning) {\n\t\t\tthis.syncRunning = true;\n\t\t\trunSynchronizer();\n\t\t}\n\t\treturn 0;\n\t}\n\n\n\n\tprivate void runSynchronizer() {\n\t\tunsetAlarm();\n\t\tfinal Synchronizer synchronizer = Synchronizer.getInstance();\n\n\t\tThread syncThread = new Thread() {\n\t\t\tpublic void run() {\n\t\t\t\tsynchronizer.runSynchronizer();\n\t\t\t\tSynchronizer.getInstance().postSynchronize();\n\t\t\t\tsyncRunning = false;\n\t\t\t\tsetAlarm();\n\t\t\t}\n\t\t};\n\n\t\tsyncThread.start();\n\t}\n\n\n\tprivate void setAlarm() {\n\t\tboolean doAutoSync = this.appSettings.getBoolean(\"doAutoSync\", false);\n\t\tif (!this.alarmScheduled && doAutoSync) {\n\n\t\t\tint interval = Integer.parseInt(\n\t\t\t\t\tthis.appSettings.getString(\"autoSyncInterval\", \"1800000\"),\n\t\t\t\t\t10);\n\n\t\t\tthis.alarmIntent = PendingIntent.getService(appInst, 0, new Intent(\n\t\t\t\t\tthis, SyncService.class), 0);\n\t\t\talarmManager.setRepeating(AlarmManager.RTC,\n\t\t\t\t\tSystem.currentTimeMillis() + interval, interval,\n\t\t\t\t\talarmIntent);\n\n\t\t\tthis.alarmScheduled = true;\n\t\t}\n\t}\n\n\tprivate void unsetAlarm() {\n\t\tif (this.alarmScheduled) {\n\t\t\tthis.alarmManager.cancel(this.alarmIntent);\n\t\t\tthis.alarmScheduled = false;\n\t\t}\n\t}\n\n\tprivate void resetAlarm() {\n\t\tunsetAlarm();\n\t\tsetAlarm();\n\t}\n\n\n\t@Override\n\tpublic void onSharedPreferenceChanged(SharedPreferences sharedPreferences,\n\t\t\tString key) {\n\t\tif (key.equals(\"doAutoSync\")) {\n\t\t\tif (sharedPreferences.getBoolean(\"doAutoSync\", false)\n\t\t\t\t\t&& !this.alarmScheduled)\n\t\t\t\tsetAlarm();\n\t\t\telse if (!sharedPreferences.getBoolean(\"doAutoSync\", false)\n\t\t\t\t\t&& this.alarmScheduled)\n\t\t\t\tunsetAlarm();\n\t\t} else if (key.equals(\"autoSyncInterval\"))\n\t\t\tresetAlarm();\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn null;\n\t}\n}", "public class DropboxSynchronizer extends Synchronizer {\n\n\tprivate String remoteIndexPath;\n\tprivate String remotePath;\n\n private boolean isLoggedIn = false;\n\t \n\tprivate DropboxAPI<AndroidAuthSession> dropboxApi;\n\tprivate Context context;\n \n public DropboxSynchronizer(Context context) {\n super(context);\n \tthis.context = context;\n\n\t\tSharedPreferences sharedPreferences = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n \t\n\t\tthis.remoteIndexPath = sharedPreferences.getString(\"dropboxPath\", \"\");\n\t\tif (!this.remoteIndexPath.startsWith(\"/\")) {\n\t\t\tthis.remoteIndexPath = \"/\" + this.remoteIndexPath;\n\t\t}\n\n\t\tString dbPath = sharedPreferences.getString(\"dropboxPath\",\"\");\n\t\tthis.remotePath = dbPath.substring(0, dbPath.lastIndexOf(\"/\")+1);\n connect();\n }\n\n private AndroidAuthSession buildSession() {\n AppKeyPair appKeyPair = new AppKeyPair(context.getString(R.string.dropbox_consumer_key),\n context.getString(R.string.dropbox_consumer_secret));\n AndroidAuthSession session;\n\n String[] stored = getKeys();\n if (stored != null) {\n AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);\n session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX, accessToken);\n } else {\n session = new AndroidAuthSession(appKeyPair, AccessType.DROPBOX);\n }\n\n return session;\n }\n\n @Override\n public String getRelativeFilesDir() {\n return null;\n }\n\n public boolean isConfigured() {\n return isLoggedIn && !this.remoteIndexPath.equals(\"\");\n }\n\n \n public void putRemoteFile(String filename, String contents) throws IOException { \n\t\tFileUtils orgFile = new FileUtils(filename, context);\n BufferedWriter writer = orgFile.getWriter();\n writer.write(contents);\n writer.close();\n \n File uploadFile = orgFile.getFile();\n FileInputStream fis = new FileInputStream(uploadFile);\n try {\n this.dropboxApi.putFileOverwrite(this.remotePath + filename, fis, uploadFile.length(), null);\n } catch (DropboxUnlinkedException e) {\n throw new IOException(\"Dropbox Authentication Failed, re-run setup wizard\");\n } catch (DropboxException e) {\n throw new IOException(\"Uploading \" + filename + \" because: \" + e.toString());\n } finally {\n if (fis != null) {\n try {\n fis.close();\n } catch (IOException e) {}\n }\n }\n }\n\n\tpublic BufferedReader getRemoteFile(String filename) throws IOException {\n\t\tString filePath = this.remotePath + filename;\n try {\n DropboxInputStream is = dropboxApi.getFileStream(filePath, null);\n BufferedReader fileReader = new BufferedReader(new InputStreamReader(is));\n return fileReader;\n } catch (DropboxUnlinkedException e) {\n throw new IOException(\"Dropbox Authentication Failed, re-run setup wizard\");\n } catch (DropboxException e) {\n throw new FileNotFoundException(\"Fetching \" + filename + \": \" + e.toString());\n }\n\t}\n\n @Override\n public SyncResult synchronize() {\n\n return null;\n }\n\n\n /**\n * This handles authentication if the user's token & secret\n * are stored locally, so we don't have to store user-name & password\n * and re-send every time.\n */\n private void connect() {\n\n AndroidAuthSession session = buildSession();\n dropboxApi = new DropboxAPI<>(session);\n if (!dropboxApi.getSession().isLinked()) {\n isLoggedIn = false;\n //throw new IOException(\"Dropbox Authentication Failed, re-run setup wizard\");\n }\n else {\n isLoggedIn = true;\n }\n }\n \n /**\n * Shows keeping the access keys returned from Trusted Authenticator in a local\n * store, rather than storing user name & password, and re-authenticating each\n * time (which is not to be done, ever).\n * \n * @return Array of [access_key, access_secret], or null if none stored\n */\n private String[] getKeys() {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(\n this.context.getApplicationContext());\n String key = prefs.getString(\"dbPrivKey\", null);\n String secret = prefs.getString(\"dbPrivSecret\", null);\n if (key != null && secret != null) {\n \tString[] ret = new String[2];\n \tret[0] = key;\n \tret[1] = secret;\n \treturn ret;\n } else {\n \treturn null;\n }\n }\n\n\tprivate void showToast(String msg) {\n\t\tfinal String u_msg = msg;\n\t\tfinal Handler mHandler = new Handler();\n\t\tfinal Runnable mRunPost = new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tToast.makeText(context, u_msg, Toast.LENGTH_LONG).show();\n\t\t\t}\n\t\t};\n\n\t\tnew Thread() {\n\t\t\tpublic void run() {\n\t\t\t\tmHandler.post(mRunPost);\n\t\t\t}\n\t\t}.start();\n\t}\n\n\n\t@Override\n\tpublic void postSynchronize() {\n\t}\n\n @Override\n public void addFile(String filename) {\n\n }\n\n @Override\n public boolean isConnectable() {\n\t\treturn OrgUtils.isNetworkOnline(context);\n\t}\n}", "public class NullSynchronizer extends Synchronizer {\n\n public NullSynchronizer(Context context) {\n super(context);\n }\n\n @Override\n public String getRelativeFilesDir() {\n return null;\n }\n\n public boolean isConfigured() {\n return true;\n }\n\n public void putRemoteFile(String filename, String contents) {\n }\n\n public BufferedReader getRemoteFile(String filename) {\n return null;\n }\n\n @Override\n public SyncResult synchronize() {\n return new SyncResult();\n }\n\n\n @Override\n\tpublic void postSynchronize() {\n }\n\n @Override\n public void addFile(String filename) {\n\n }\n\n @Override\n public boolean isConnectable() {\n\t\treturn true;\n\t}\n}", "public class SDCardSynchronizer extends Synchronizer {\n\n\tprivate String remoteIndexPath;\n\tprivate String remotePath;\n\n public SDCardSynchronizer(Context context) {\n\t\tsuper(context);\n\t\tthis.remoteIndexPath = PreferenceManager.getDefaultSharedPreferences(\n\t\t\t\tcontext).getString(\"indexFilePath\", \"\");\n\t\n\t\tthis.remotePath = new File(remoteIndexPath) + \"/\";\n\t}\n\n\n\t@Override\n\tpublic String getRelativeFilesDir() {\n\t\treturn null;\n\t}\n\n\tpublic boolean isConfigured() {\n\t\treturn !remoteIndexPath.equals(\"\");\n\t}\n\n\tpublic void putRemoteFile(String filename, String contents) throws IOException {\n\t\tString outfilePath = this.remotePath + filename;\n\t\t\n\t\tFile file = new File(outfilePath);\n\t\tBufferedWriter writer = new BufferedWriter(new FileWriter(file, true));\n\t\twriter.write(contents);\n\t\twriter.close();\n\t}\n\n\tpublic BufferedReader getRemoteFile(String filename) throws FileNotFoundException {\n\t\tString filePath = this.remotePath + filename;\n\t\tFile file = new File(filePath);\n\t\tFileInputStream fileIS = new FileInputStream(file);\n\t\treturn new BufferedReader(new InputStreamReader(fileIS));\n\t}\n\n\t@Override\n\tpublic SyncResult synchronize() {\n\n\t\treturn null;\n\t}\n\n\n\t@Override\n\tpublic void postSynchronize() {\n\t}\n\n\t@Override\n\tpublic void addFile(String filename) {\n\n\t}\n\n\n\t@Override\n\tpublic boolean isConnectable() {\n\t\treturn true;\n\t}\n}", "public class SSHSynchronizer extends Synchronizer {\n private final String LT = \"MobileOrg\";\n AuthData authData;\n private Session session;\n\n public SSHSynchronizer(Context context) {\n super(context);\n this.context = context;\n authData = AuthData.getInstance(context);\n }\n\n @Override\n public String getRelativeFilesDir() {\n return JGitWrapper.GIT_DIR;\n }\n\n @Override\n public boolean isConfigured() {\n return !(authData.getPath().equals(\"\")\n || authData.getUser().equals(\"\")\n || authData.getHost().equals(\"\")\n || authData.getPassword().equals(\"\")\n && AuthData.getPublicKey(context).equals(\"\"));\n }\n\n public void connect() {\n try {\n SshSessionFactory sshSessionFactory = new SshSessionFactory(context);\n JSch jSch = sshSessionFactory.createDefaultJSch(FS.detect());\n\n\n session = jSch.getSession(\n authData.getUser(),\n authData.getHost(),\n authData.getPort());\n\n session.setPassword(AuthData.getInstance(context).getPassword());\n\n // TODO: find a way to check for host key\n// jSch.setKnownHosts(\"/storage/sdcard0/Download/known_hosts\");\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n\n session.connect();\n session.disconnect();\n } catch (JSchException e) {\n e.printStackTrace();\n }\n\n }\n\n public SyncResult synchronize(){\n if (isCredentialsRequired()) return new SyncResult();\n SyncResult pullResult = JGitWrapper.pull(context);\n\n new JGitWrapper.PushTask(context).execute();\n return pullResult;\n }\n\n /**\n * Except if authentication by Public Key, the user has to enter his password\n *\n * @return\n */\n public boolean isCredentialsRequired() {\n return false;\n }\n\n @Override\n public void postSynchronize() {\n if (this.session != null)\n this.session.disconnect();\n }\n\n @Override\n public void addFile(String filename) {\n JGitWrapper.add(filename, context);\n }\n\n @Override\n public boolean isConnectable() throws Exception {\n if (!OrgUtils.isNetworkOnline(context)) return false;\n\n this.connect();\n return true;\n }\n\n @Override\n public void clearRepository(Context context) {\n File dir = new File(getAbsoluteFilesDir(context));\n for (File file : dir.listFiles()) {\n if (file.getName().equals(\".git\")) continue;\n file.delete();\n }\n }\n}", "public abstract class Synchronizer {\n public static final String SYNC_UPDATE = \"com.matburt.mobileorg.Synchronizer.action.SYNC_UPDATE\";\n public static final String SYNC_DONE = \"sync_done\";\n public static final String SYNC_START = \"sync_start\";\n public static final String SYNC_PROGRESS_UPDATE = \"progress_update\";\n public static final String SYNC_SHOW_TOAST = \"showToast\";\n private static Synchronizer mSynchronizer = null;\n protected Context context;\n private ContentResolver resolver;\n private SynchronizerNotificationCompat notify;\n\n\n protected Synchronizer(Context context) {\n this.context = context;\n this.resolver = context.getContentResolver();\n\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)\n this.notify = new SynchronizerNotification(context);\n else\n this.notify = new SynchronizerNotificationCompat(context);\n }\n\n public static Synchronizer getInstance() {\n return mSynchronizer;\n }\n\n public static void setInstance(Synchronizer instance) {\n mSynchronizer = instance;\n }\n\n /**\n *\n * @param instance\n */\n static public void updateSynchronizer(Synchronizer instance) {\n\n }\n\n /**\n * Return true if the user has to enter its credentials when the app starts\n * eg. SSHSynchonizer by password returns yes\n * @return\n */\n public boolean isCredentialsRequired() {\n return false;\n }\n\n /**\n * @return List of files that where changed.\n */\n public HashSet<String> runSynchronizer() {\n HashSet<String> result = new HashSet<>();\n if (!isConfigured()) {\n notify.errorNotification(\"Sync not configured\");\n return result;\n }\n\n try {\n announceStartSync();\n\n isConnectable();\n\n SyncResult pulledFiles = synchronize();\n\n for (String filename : pulledFiles.deletedFiles) {\n\n OrgFile orgFile = new OrgFile(filename, resolver);\n orgFile.removeFile(context, true);\n }\n\n for (String filename : pulledFiles.newFiles) {\n OrgFile orgFile = new OrgFile(filename, filename);\n FileReader fileReader = new FileReader(getAbsoluteFilesDir(context) + \"/\" + filename);\n BufferedReader bufferedReader = new BufferedReader(fileReader);\n\n OrgFileParser.parseFile(orgFile, bufferedReader, context);\n }\n\n for (String filename : pulledFiles.changedFiles) {\n OrgFile orgFile = new OrgFile(filename, filename);\n FileReader fileReader = new FileReader(getAbsoluteFilesDir(context) + \"/\" + filename);\n BufferedReader bufferedReader = new BufferedReader(fileReader);\n\n OrgFileParser.parseFile(orgFile, bufferedReader, context);\n }\n\n announceSyncDone();\n return pulledFiles.changedFiles;\n } catch (Exception e) {\n showErrorNotification(e);\n e.printStackTrace();\n }\n return result;\n }\n\n private void announceStartSync() {\n notify.setupNotification();\n OrgUtils.announceSyncStart(context);\n }\n\n private void announceProgressUpdate(int progress, String message) {\n if (message != null && TextUtils.isEmpty(message) == false)\n notify.updateNotification(progress, message);\n else\n notify.updateNotification(progress);\n OrgUtils.announceSyncUpdateProgress(progress, context);\n }\n\n private void announceProgressDownload(String filename, int fileIndex, int totalFiles) {\n int progress = 0;\n if (totalFiles > 0)\n progress = (100 / totalFiles) * fileIndex;\n String message = context.getString(R.string.downloading) + \" \" + filename;\n announceProgressUpdate(progress, message);\n }\n\n private void showErrorNotification(Exception exception) {\n notify.finalizeNotification();\n\n String errorMessage = \"\";\n if (CertificateException.class.isInstance(exception)) {\n errorMessage = \"Certificate Error occured during sync: \"\n + exception.getLocalizedMessage();\n } else {\n errorMessage = \"Error: \" + exception.getLocalizedMessage();\n }\n\n notify.errorNotification(errorMessage);\n }\n\n private void announceSyncDone() {\n announceProgressUpdate(100, \"Done synchronizing\");\n notify.finalizeNotification();\n OrgUtils.announceSyncDone(context);\n }\n\n abstract public String getRelativeFilesDir();\n\n public String getAbsoluteFilesDir(Context context) {\n return context.getFilesDir() + \"/\" + getRelativeFilesDir();\n }\n\n /**\n * Delete all files from the synchronized repository\n * except repository configuration files\n * @param context\n */\n public void clearRepository(Context context) {\n File dir = new File(getAbsoluteFilesDir(context));\n for (File file : dir.listFiles()) {\n file.delete();\n }\n }\n\n\n /**\n * Called before running the synchronizer to ensure that it's configuration\n * is in a valid state.\n */\n abstract boolean isConfigured();\n\n /**\n * Called before running the synchronizer to ensure it can connect.\n */\n abstract public boolean isConnectable() throws Exception;\n\n\n abstract SyncResult synchronize();\n\n\n /**\n * Use this to disconnect from any services and cleanup.\n */\n public abstract void postSynchronize();\n\n /**\n * Synchronize a new file\n *\n * @param filename\n */\n abstract public void addFile(String filename);\n\n\n}", "public class UbuntuOneSynchronizer extends Synchronizer {\n\nprivate static final String BASE_TOKEN_NAME = \"Ubuntu One @ MobileOrg:\";\n\tprivate static final String CONSUMER_KEY = \"consumer_key\";\n\tprivate static final String CONSUMER_SECRET = \"consumer_secret\";\n\tprivate static final String ACCESS_TOKEN = \"token\";\n\tprivate static final String TOKEN_SECRET = \"token_secret\";\n\n private static final String BASE_PATH = \"root_node_path\";\n private static final String BYTES_USED = \"used_bytes\";\n private static final String MAX_BYTES = \"max_bytes\";\n\n\tprivate static final String LOGIN_HOST = \"login.ubuntu.com\";\n\tprivate static final int LOGIN_PORT = 443;\n\tprivate static final String LOGIN_URL = \"https://\" + LOGIN_HOST + \":\"\n\t\t\t+ LOGIN_PORT + \"/api/1.0/authentications\"\n\t\t\t+ \"?ws.op=authenticate&token_name=\";\n private static final String FILES_BASE = \"https://files.one.ubuntu.com\";\n private static final String FILES_URL = \"https://one.ubuntu.com/api/file_storage/v1\";\n\tprivate static final String PING_URL = \"https://one.ubuntu.com/oauth/sso-finished-so-get-tokens/\";\n\tprivate static final String UTF8 = \"UTF-8\";\n\n\tpublic String remoteIndexPath;\n\tpublic String remotePath;\n public String username;\n public String password;\n\n public String consumer_key;\n public String consumer_secret;\n public String access_token;\n public String token_secret;\n\n public String root_path;\n public long bytes_used;\n public long max_bytes;\n\n private CommonsHttpOAuthConsumer consumer;\n\tprivate Context context; \n\n public UbuntuOneSynchronizer(Context context) {\n super(context);\n \tthis.context = context;\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n\t\tthis.remoteIndexPath = sharedPreferences.getString(\"ubuntuOnePath\", \"\");\n //\t\tthis.remotePath = getRootUrl();\n\n\t\tthis.username = sharedPreferences.getString(\"ubuntuOneUser\", \"\");\n\t\tthis.password = \"\"; //we don't store this, it's just set to be populated by wizard\n\n consumer_key = sharedPreferences.getString(\"ubuntuConsumerKey\", \"\");\n consumer_secret = sharedPreferences.getString(\"ubuntuConsumerSecret\", \"\");\n access_token = sharedPreferences.getString(\"ubuntuAccessToken\", \"\");\n token_secret = sharedPreferences.getString(\"ubuntuTokenSecret\", \"\");\n getBaseUser();\n }\n\n public void invalidate() {\n this.consumer = null;\n }\n\n public String testConnection(String user, String pass) {\n return \"\";\n }\n\n @Override\n public String getRelativeFilesDir() {\n return null;\n }\n\n public boolean isConfigured() {\n return !this.consumer_key.equals(\"\");\n }\n\n\tpublic void signRequest(HttpRequest request) {\n\t\tint retries = 3;\n\n\t\tif (consumer == null) {\n\t\t\tbuildConsumer();\n\t\t}\n\n\t\twhile (retries-- > 0) {\n\t\t\ttry {\n\t\t\t\tif (consumer != null) {\n\t\t\t\t\t// We need to remove the previous Authorization header\n\t\t\t\t\t// because signpost fails to sign a second time otherwise. \n\t\t\t\t\trequest.removeHeaders(\"Authorization\");\n\t\t\t\t\tconsumer.sign(request);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (OAuthException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tlogin();\n\t\t}\n\t}\n\n public void putRemoteFile(String filename, String contents) throws IOException {\n try {\n buildConsumer();\n String latterPart = remoteIndexPath + filename;\n latterPart = latterPart.replaceAll(\"/{2,}\", \"/\");\n String files_url = FILES_URL + root_path + latterPart;\n\n URL url = new URL(files_url);\n URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),\n url.getPort(), url.getPath(), url.getQuery(), url.getRef());\n url = uri.toURL();\n\n HttpPut request = new HttpPut(url.toString());\n JSONObject createFile = new JSONObject();\n createFile.put(\"kind\", \"file\");\n StringEntity se = new StringEntity(createFile.toString()); \n //se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, \"application/json\"));\n request.setEntity(se);\n DefaultHttpClient httpClient = new DefaultHttpClient();\n signRequest(request);\n HttpResponse response = httpClient.execute(request);\n verifyResponse(response);\n JSONObject fileData = responseToJson(response);\n\n String content_path = fileData.getString(\"content_path\");\n String content_url = FILES_BASE + content_path;\n\n url = new URL(content_url);\n uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),\n url.getPort(), url.getPath(), url.getQuery(), url.getRef());\n url = uri.toURL();\n\n request = new HttpPut(url.toString());\n request.setEntity(new StringEntity(contents, \"UTF-8\"));\n httpClient = new DefaultHttpClient();\n\n signRequest(request);\n response = httpClient.execute(request);\n verifyResponse(response);\n\n } catch (Exception e) {\n\t\t\tthrow new IOException(\"Uploading: \" + filename + \": \" + e.toString());\n }\n }\n\n public BufferedReader getRemoteFile(String filename) {\n try { \n buildConsumer();\n String latterPart = remoteIndexPath + filename;\n latterPart = latterPart.replaceAll(\"/{2,}\", \"/\");\n String files_url = FILES_URL + root_path + latterPart;\n URL url = new URL(files_url);\n URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),\n url.getPort(), url.getPath(), url.getQuery(), url.getRef());\n url = uri.toURL();\n HttpGet request = new HttpGet(url.toString());\n DefaultHttpClient httpClient = new DefaultHttpClient();\n signRequest(request);\n HttpResponse response = httpClient.execute(request);\n verifyResponse(response);\n JSONObject fileData = responseToJson(response);\n\n String content_path = fileData.getString(\"content_path\");\n String content_url = FILES_BASE + content_path;\n url = new URL(content_url);\n uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),\n url.getPort(), url.getPath(), url.getQuery(), url.getRef());\n url = uri.toURL();\n request = new HttpGet(url.toString());\n httpClient = new DefaultHttpClient();\n signRequest(request);\n response = httpClient.execute(request);\n verifyResponse(response);\n return new BufferedReader(new InputStreamReader(response.getEntity().getContent()));\n } catch (Exception e) {\n }\n return null;\n }\n\n @Override\n public SyncResult synchronize() {\n\n return null;\n }\n\n public ArrayList<String> getDirectoryList(String directory) {\n ArrayList<String> directories = new ArrayList<String>();\n\t\ttry {\n buildConsumer();\n String latterPart = root_path + directory + \"?include_children=true\";\n latterPart = latterPart.replaceAll(\"/{2,}\", \"/\");\n\t\t\tString files_url = FILES_URL + latterPart;\n URL url = new URL(files_url);\n URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),\n url.getPort(), url.getPath(), url.getQuery(), url.getRef());\n url = uri.toURL();\n\t\t\tHttpGet request = new HttpGet(url.toString());\n\t\t\tDefaultHttpClient httpClient = new DefaultHttpClient();\n signRequest(request);\n HttpResponse response = httpClient.execute(request);\n verifyResponse(response);\n JSONObject dirData = responseToJson(response);\n JSONArray jsA = dirData.getJSONArray(\"children\");\n if (jsA != null) { \n for (int i = 0; i < jsA.length(); i++){\n JSONObject node = jsA.getJSONObject(i);\n if (node.getString(\"kind\").equals(\"directory\")) {\n directories.add(node.getString(\"path\"));\n }\n } \n }\n } catch (Exception e) {\n }\n return directories;\n }\n\n public void getBaseUser() {\n\t\ttry {\n buildConsumer();\n\t\t\tString files_url = FILES_URL;\n\t\t\tHttpGet request = new HttpGet(files_url);\n\t\t\tDefaultHttpClient httpClient = new DefaultHttpClient();\n signRequest(request);\n HttpResponse response = httpClient.execute(request);\n verifyResponse(response);\n JSONObject dirData = responseToJson(response);\n root_path = dirData.getString(BASE_PATH);\n max_bytes = dirData.getLong(MAX_BYTES);\n bytes_used = dirData.getLong(BYTES_USED);\n } catch (Exception e) {\n }\n }\n\n @Override\n\tpublic void postSynchronize() {\n }\n\n @Override\n public void addFile(String filename) {\n\n }\n\n public boolean login() {\n invalidate();\n\t\ttry {\n\t\t\tDefaultHttpClient httpClient = new DefaultHttpClient();\n final HttpParams httpParameters = httpClient.getParams();\n HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);\n HttpConnectionParams.setSoTimeout(httpParameters, 60000);\n\t\t\thttpClient.getCredentialsProvider().setCredentials(\n\t\t\t\t\tnew AuthScope(LOGIN_HOST, LOGIN_PORT),\n\t\t\t\t\tnew UsernamePasswordCredentials(this.username, this.password));\n\t\t\tHttpUriRequest request = new HttpGet(buildLoginUrl());\n\t\t\tHttpResponse response = httpClient.execute(request);\n\t\t\tverifyResponse(response);\n\t\t\tJSONObject loginData = responseToJson(response);\n consumer_key = loginData.getString(CONSUMER_KEY);\n consumer_secret = loginData.getString(CONSUMER_SECRET);\n access_token = loginData.getString(ACCESS_TOKEN);\n token_secret = loginData.getString(TOKEN_SECRET);\n\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n Editor edit = sharedPreferences.edit();\n edit.putString(\"ubuntuConsumerKey\", consumer_key);\n edit.putString(\"ubuntuConsumerSecret\", consumer_secret);\n edit.putString(\"ubuntuAccessToken\", access_token);\n edit.putString(\"ubuntuTokenSecret\", token_secret);\n edit.commit();\n\n\t\t\tbuildConsumer();\n ping_u1_url(this.username);\n return true;\n\t\t} catch (ClientProtocolException e) {\n\t\t} catch (IOException e) {\n//\t\t\tLog.e(\"MobileOrg\", \"IO Exception: \" + e.toString());\n\t\t} catch (JSONException e) {\n\t\t}\n return false;\n\t}\n\n\tprivate InputStream getUrl(String url) throws Exception {\n\t\tHttpGet request = new HttpGet(url);\n\t\tHttpResponse response = executeRequest(request);\n\t\tHttpEntity entity = response.getEntity();\n\t\tif (entity != null) {\n\t\t\tInputStream instream = entity.getContent();\n return instream;\n\t\t}\n\t\treturn null;\n\t}\n\n private void putUrl(String url, String data) throws Exception {\n HttpPut put = new HttpPut(url);\n put.setEntity(new StringEntity(data));\n HttpResponse response = executeRequest(put);\n }\n\n\tprotected HttpResponse executeRequest(HttpUriRequest request)\n\t\t\tthrows IOException {\n\t\tDefaultHttpClient httpClient = new DefaultHttpClient();\n final HttpParams httpParameters = httpClient.getParams();\n HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);\n HttpConnectionParams.setSoTimeout(httpParameters, 60000);\n\t\tHttpResponse response = null;\n\t\tint retries = 3;\n\n\t\twhile (retries-- > 0) {\n\t\t\tthis.signRequest(request);\n\t\t\tresponse = httpClient.execute(request);\n\t\t\tint statusCode = response.getStatusLine().getStatusCode();\n\t\t\tif (statusCode == 400 || statusCode == 401) {\n\t\t\t\tinvalidate();\n\t\t\t} else {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t}\n\t\treturn response;\n\t}\n\n\tprivate void buildConsumer() {\n\t\tif (consumer_key != null && consumer_secret != null\n\t\t\t\t&& access_token != null && token_secret != null) {\n\t\t\tconsumer = new CommonsHttpOAuthConsumer(consumer_key, consumer_secret);\n\t\t\tconsumer.setMessageSigner(new HmacSha1MessageSigner());\n\t\t\tconsumer.setTokenWithSecret(access_token, token_secret);\n\t\t}\n\t}\n\n\tprivate void verifyResponse(HttpResponse response) throws IOException {\n\t\tint statusCode = response.getStatusLine().getStatusCode();\n\t\tif (statusCode < 200 || statusCode > 299) {\n\t\t\tthrow new IOException(\"Bad Auth Response: \" + Integer.toString(statusCode));\n\t\t}\n\t}\n\n\tprivate JSONObject responseToJson(HttpResponse response)\n\t\t\tthrows IOException, JSONException {\n\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(\n\t\t\t\tresponse.getEntity().getContent(), \"UTF-8\"));\n\t\tStringBuilder builder = new StringBuilder();\n\t\tfor (String line = null; (line = reader.readLine()) != null;) {\n\t\t\tbuilder.append(line).append(\"\\n\");\n\t\t}\n\t\treturn new JSONObject(builder.toString());\n\t}\n\n\tprivate String buildLoginUrl() {\n\t\tString token_name = BASE_TOKEN_NAME + Build.MODEL;\n\t\tString login_url = LOGIN_URL;\n\t\ttry {\n\t\t\tlogin_url += URLEncoder.encode(token_name, UTF8);\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tlogin_url += \"Android\";\n\t\t}\n\t\treturn login_url;\n\t}\n\n\tprivate void ping_u1_url(String username) {\n\t\ttry {\n\t\t\tString ping_url = PING_URL + username;\n\t\t\tHttpGet request = new HttpGet(ping_url);\n\t\t\tDefaultHttpClient httpClient = new DefaultHttpClient();\n final HttpParams httpParameters = httpClient.getParams();\n HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);\n HttpConnectionParams.setSoTimeout(httpParameters, 60000);\n\t\t\tHttpResponse response = null;\n\t\t\tint retries = 3;\n\n\t\t\twhile (retries-- > 0) {\n\t\t\t\tsignRequest(request);\n\t\t\t\tresponse = httpClient.execute(request);\n\t\t\t\tint statusCode = response.getStatusLine().getStatusCode();\n\t\t\t\tif (statusCode == 400 || statusCode == 401) {\n\t\t\t\t\tinvalidate();\n\t\t\t\t} else {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n } catch (Exception e) {\n }\n\t\t// } catch (UnsupportedEncodingException e) {\n\t\t// \te.printStackTrace();\n\t\t// } catch (ClientProtocolException e) {\n\t\t// \te.printStackTrace();\n\t\t// } catch (IOException e) {\n\t\t// \te.printStackTrace();\n\t\t// }\n\t}\n\n\t@Override\n\tpublic boolean isConnectable() {\n\t\treturn OrgUtils.isNetworkOnline(context);\n\t}\n}", "public class WebDAVSynchronizer extends Synchronizer {\n\n\tprivate String remoteIndexPath;\n\tprivate String remotePath;\n private String username;\n private String password;\n\t\n\tprivate Resources r;\n\tpublic WebDAVSynchronizer(Context context) {\n super(context);\n\t\tthis.r = context.getResources();\n\t\tSharedPreferences sharedPreferences = PreferenceManager\n\t\t\t\t.getDefaultSharedPreferences(context);\n\n\t\tthis.remoteIndexPath = sharedPreferences.getString(\"webUrl\", \"\");\n\t\tthis.remotePath = getRootUrl();\n\n\t\tthis.username = sharedPreferences.getString(\"webUser\", \"\");\n\t\tthis.password = sharedPreferences.getString(\"webPass\", \"\");\n this.handleTrustRelationship(context);\n\t}\n\n public String testConnection(String url, String user, String pass) {\n this.remoteIndexPath = url;\n this.remotePath = getRootUrl();\n this.username = user;\n this.password = pass;\n\n if (!this.isConfigured()) {\n return \"No URL specified\";\n }\n\n try {\n HttpURLConnection dhc = this.createConnection(this.remoteIndexPath);\n if (dhc == null) {\n return \"Connection could not be established\";\n }\n\n InputStream mainFile = null;\n try {\n mainFile = this.getUrlStream(this.remoteIndexPath);\n\n if (mainFile == null) {\n return \"File '\" + this.remoteIndexPath + \"' doesn't appear to exist\";\n }\n\n return null;\n }\n catch (FileNotFoundException e) {\n throw e;\n }\n catch (Exception e) {\n throw e;\n }\n }\n catch (Exception e) {\n return \"Test Exception: \" + e.getMessage();\n }\n }\n\n @Override\n public String getRelativeFilesDir() {\n return null;\n }\n\n @Override\n public boolean isConfigured() {\n\t\tif (this.remoteIndexPath.equals(\"\"))\n\t\t\treturn false;\n\n return true;\n }\n\n private void handleChangedCertificate() {\n Intent i = new Intent(this.context, CertificateConflictActivity.class);\n i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n this.context.startActivity(i);\n }\n\n\tpublic void putRemoteFile(String filename, String contents) throws IOException {\n\t\tString urlActual = this.getRootUrl() + filename;\n\t\tputUrlFile(urlActual, contents);\n\t}\n\n public BufferedReader getRemoteFile(String filename) throws IOException, CertificateException {\n\t\tString orgUrl = this.remotePath + filename;\n InputStream mainFile = null;\n try {\n mainFile = this.getUrlStream(orgUrl);\n\n if (mainFile == null) {\n return null;\n }\n\n return new BufferedReader(new InputStreamReader(mainFile));\n }\n catch (CertificateException e) {\n handleChangedCertificate();\n throw e;\n }\n catch (SSLHandshakeException e) {\n handleChangedCertificate();\n throw e;\n }\n\t}\n\n @Override\n public SyncResult synchronize() {\n\n return null;\n }\n\n /* See: http://stackoverflow.com/questions/1217141/self-signed-ssl-acceptance-android */\n private void handleTrustRelationship(Context c) {\n try {\n HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }});\n SSLContext context = SSLContext.getInstance(\"TLS\");\n context.init(null, new X509TrustManager[]{new IntelligentX509TrustManager(c)}, new SecureRandom());\n HttpsURLConnection.setDefaultSSLSocketFactory(\n context.getSocketFactory());\n } catch (Exception e) { // should never happen\n e.printStackTrace();\n }\n }\n\n\tprivate HttpURLConnection createConnection(String url) {\n URL newUrl = null;\n\t\ttry {\n newUrl = new URL(url);\n\t\t} catch (MalformedURLException e) {\n e.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\n HttpURLConnection con = null;\n try {\n con = (HttpURLConnection) newUrl.openConnection();\n } catch (IOException e) {\n return null;\n }\n con.setReadTimeout(60000);\n con.setConnectTimeout(60000);\n con.addRequestProperty(\"Expect\", \"100-continue\");\n con.addRequestProperty(\"Authorization\",\n \"Basic \"+Base64.encodeToString((this.username + \":\" + this.password).getBytes(),\n Base64.NO_WRAP));\n return con;\n\t}\n\n\tprivate InputStream getUrlStream(String url) throws IOException, CertificateException {\n HttpURLConnection con = this.createConnection(url);\n con.setRequestMethod(\"GET\");\n con.setDoInput(true);\n con.connect();\n\t\tif (con.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {\n\t\t\tthrow new FileNotFoundException(r.getString(\n\t\t\t\t\tR.string.error_url_fetch_detail, url,\n\t\t\t\t\t\"Invalid username or password\"));\n\t\t}\n\t\tif (con.getResponseCode()== HttpURLConnection.HTTP_NOT_FOUND) {\n throw new FileNotFoundException(r.getString(\n R.string.error_url_fetch_detail, url,\n \"File not found: \" + url));\n }\n if (con.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {\n throw new FileNotFoundException(r.getString(\n R.string.error_url_fetch_detail, url,\n \"Server reported 'Forbidden'\"));\n }\n\n\t\tif (con.getResponseCode() < HttpURLConnection.HTTP_OK || con.getResponseCode() > 299) {\n\t\t\tthrow new IOException(r.getString(R.string.error_url_fetch_detail,\n url, con.getResponseMessage()));\n\t\t}\n\t\treturn con.getInputStream();\n\t}\n\n\tprivate void putUrlFile(String url, String content) throws IOException {\n\t\ttry {\n HttpURLConnection con = this.createConnection(url);\n con.setRequestMethod(\"PUT\");\n con.setDoOutput(true);\n OutputStreamWriter out = new OutputStreamWriter(\n con.getOutputStream());\n out.write(content);\n out.flush();\n out.close();\n con.getInputStream();\n if (con.getResponseCode() < HttpURLConnection.HTTP_OK || con.getResponseCode() > 299) {\n throw new IOException(r.getString(R.string.error_url_fetch_detail,\n url, con.getResponseMessage()));\n }\n } catch (UnsupportedEncodingException e) {\n\t\t\tthrow new IOException(r.getString(\n\t\t\t\t\tR.string.error_unsupported_encoding, FileUtils.CAPTURE_FILE));\n\t\t}\n\t}\n\n\tprivate String getRootUrl() {\n\t\tURL manageUrl;\n\t\ttry {\n\t\t\tmanageUrl = new URL(this.remoteIndexPath);\n\t\t} catch (MalformedURLException e) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tString urlPath = manageUrl.getPath();\n\t\tString[] pathElements = urlPath.split(\"/\");\n\t\tString directoryActual = \"/\";\n\n\t\tif (pathElements.length > 1) {\n\t\t\tfor (int i = 0; i < pathElements.length - 1; i++) {\n\t\t\t\tif (pathElements[i].length() > 0) {\n\t\t\t\t\tdirectoryActual += pathElements[i] + \"/\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn manageUrl.getProtocol() + \"://\" + manageUrl.getAuthority()\n\t\t\t\t+ directoryActual;\n\t}\n\n\t@Override\n public void postSynchronize() {\n }\n\n @Override\n public void addFile(String filename) {\n\n }\n\n @Override\n public boolean isConnectable() {\n\t\treturn OrgUtils.isNetworkOnline(context);\n\t}\n\n class IntelligentX509TrustManager implements X509TrustManager {\n Context c;\n\n public IntelligentX509TrustManager(Context c) {\n super();\n this.c = c;\n }\n\n public boolean validateCertificate(int hash, String description) {\n SharedPreferences appSettings =\n PreferenceManager.getDefaultSharedPreferences(this.c);\n Editor edit = appSettings.edit();\n int existingHash = appSettings.getInt(\"webCertHash\", 0);\n if (existingHash == 0) {\n edit.putInt(\"webCertHash\", hash);\n edit.putString(\"webCertDescr\", description);\n edit.commit();\n return true;\n } else if (existingHash != hash) {\n edit.putInt(\"webConflictHash\", hash);\n edit.putString(\"webConflictHashDesc\", description);\n edit.commit();\n return true;\n //WARNING: NOTE: This disables the requirement to validate the certificate.\n // a better way is needed for those certs whose hash changes\n // all the time\n //return false;\n }\n return true;\n }\n\n public void checkClientTrusted(X509Certificate[] chain,\n String authType) throws CertificateException {\n }\n\n public void checkServerTrusted(X509Certificate[] chain,\n String authType) throws CertificateException {\n for (int i = 0; i < chain.length; i++) {\n String descr = chain[i].toString();\n int hash = chain[i].hashCode();\n if (!this.validateCertificate(hash, descr)) {\n throw new CertificateException(\"Conflicting certificate found with hash \" +\n Integer.toString(hash));\n }\n }\n }\n\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n }\n}" ]
import android.app.Application; import android.content.Context; import android.preference.PreferenceManager; import com.matburt.mobileorg.services.SyncService; import com.matburt.mobileorg.synchronizers.DropboxSynchronizer; import com.matburt.mobileorg.synchronizers.NullSynchronizer; import com.matburt.mobileorg.synchronizers.SDCardSynchronizer; import com.matburt.mobileorg.synchronizers.SSHSynchronizer; import com.matburt.mobileorg.synchronizers.Synchronizer; import com.matburt.mobileorg.synchronizers.UbuntuOneSynchronizer; import com.matburt.mobileorg.synchronizers.WebDAVSynchronizer;
package com.matburt.mobileorg.orgdata; public class MobileOrgApplication extends Application { private static MobileOrgApplication instance; public static Context getContext() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this; OrgDatabase.startDB(this); startSynchronizer(); OrgFileParser.startParser(this); SyncService.startAlarm(this); } public void startSynchronizer() { String syncSource = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()) .getString("syncSource", ""); Context c = getApplicationContext(); if (syncSource.equals("webdav")) Synchronizer.setInstance(new WebDAVSynchronizer(c)); else if (syncSource.equals("sdcard")) Synchronizer.setInstance(new SDCardSynchronizer(c)); else if (syncSource.equals("dropbox")) Synchronizer.setInstance(new DropboxSynchronizer(c)); else if (syncSource.equals("ubuntu")) Synchronizer.setInstance(new UbuntuOneSynchronizer(c)); else if (syncSource.equals("scp"))
Synchronizer.setInstance(new SSHSynchronizer(c));
4
Nilhcem/devoxxfr-2016
app/src/main/java/com/nilhcem/devoxxfr/data/database/DbMapper.java
[ "@Singleton\npublic class LocalDateTimeAdapter {\n\n private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm\", Locale.US);\n\n @Inject\n public LocalDateTimeAdapter() {\n }\n\n @ToJson\n public String toText(LocalDateTime dateTime) {\n return dateTime.format(formatter);\n }\n\n @FromJson\n public LocalDateTime fromText(String text) {\n return LocalDateTime.parse(text, formatter);\n }\n}", "public class AppMapper {\n\n @Inject\n public AppMapper() {\n }\n\n public Map<Integer, Speaker> speakersToMap(@NonNull List<Speaker> from) {\n return stream(from).collect(Collectors.toMap(Speaker::getId, speaker -> speaker));\n }\n\n public List<Speaker> toSpeakersList(@Nullable List<Integer> speakerIds, @NonNull Map<Integer, Speaker> speakersMap) {\n if (speakerIds == null) {\n return null;\n }\n return stream(speakerIds).map(speakersMap::get).collect(Collectors.toList());\n }\n\n public List<Integer> toSpeakersIds(@Nullable List<Speaker> speakers) {\n if (speakers == null) {\n return null;\n }\n return stream(speakers).map(Speaker::getId).collect(Collectors.toList());\n }\n\n public Schedule toSchedule(@NonNull List<Session> sessions) {\n // Map and sort Session per start date\n Collections.sort(sessions, (lhs, rhs) -> lhs.getFromTime().compareTo(rhs.getFromTime()));\n\n // Gather Sessions per ScheduleSlot\n List<ScheduleSlot> scheduleSlots = mapToScheduleSlots(sessions);\n\n // Gather ScheduleSlots per ScheduleDays\n return mapToScheduleDays(scheduleSlots);\n }\n\n private List<ScheduleSlot> mapToScheduleSlots(@NonNull List<Session> sortedSessions) {\n List<ScheduleSlot> slots = new ArrayList<>();\n\n LocalDateTime previousTime = null;\n List<Session> previousSessionsList = null;\n\n LocalDateTime currentTime;\n for (Session currentSession : sortedSessions) {\n currentTime = currentSession.getFromTime();\n if (previousSessionsList != null) {\n if (currentTime.equals(previousTime)) {\n previousSessionsList.add(currentSession);\n } else {\n slots.add(new ScheduleSlot(previousTime, previousSessionsList));\n previousSessionsList = null;\n }\n }\n\n if (previousSessionsList == null) {\n previousTime = currentTime;\n previousSessionsList = new ArrayList<>();\n previousSessionsList.add(currentSession);\n }\n }\n\n if (previousSessionsList != null) {\n slots.add(new ScheduleSlot(previousTime, previousSessionsList));\n }\n return slots;\n }\n\n private Schedule mapToScheduleDays(@NonNull List<ScheduleSlot> scheduleSlots) {\n Schedule schedule = new Schedule();\n\n LocalDate previousDay = null;\n List<ScheduleSlot> previousSlotList = null;\n\n LocalDate currentDay;\n for (ScheduleSlot currentSlot : scheduleSlots) {\n currentDay = LocalDate.from(currentSlot.getTime());\n if (previousSlotList != null) {\n if (currentDay.equals(previousDay)) {\n previousSlotList.add(currentSlot);\n } else {\n schedule.add(new ScheduleDay(previousDay, previousSlotList));\n previousSlotList = null;\n }\n }\n\n if (previousSlotList == null) {\n previousDay = currentDay;\n previousSlotList = new ArrayList<>();\n previousSlotList.add(currentSlot);\n }\n }\n\n if (previousSlotList != null) {\n schedule.add(new ScheduleDay(previousDay, previousSlotList));\n }\n return schedule;\n }\n}", "public enum Room {\n\n EXHIBITION_FLOOR(0, \"Exhibition floor\"),\n AMPHI_BLEU(1, \"Amphi Bleu\"),\n MAILLOT(2, \"Maillot\"),\n NEUILLY_251(3, \"Neuilly 251\"),\n NEUILLY_252_AB(4, \"Neuilly 252 AB\"),\n NEUILLY_253_LAB(5, \"Neuilly 253 Lab\"),\n NEUILLY_253(6, \"Neuilly 253\"),\n NEUILLY_212_213M_LAB(7, \"Neuilly 212-213M Lab\"),\n NEUILLY_231_232M_LAB(8, \"Neuilly 231-232M Lab\"),\n NEUILLY_234_234M_LAB(9, \"Neuilly 234_234M Lab\"),\n OPEN_DATA_CAMP(10, \"Open Data Camp\"),\n PARIS_201(11, \"Paris 201\"),\n PARIS_202_203_LAB(12, \"Paris 202-203 Lab\"),\n PARIS_204(13, \"Paris 204\"),\n PARIS_221M_222M_LAB(14, \"Paris 221M-222M Lab\"),\n PARIS_224M_225M_LAB(15, \"Paris 224M-225M Lab\"),\n PARIS_241(16, \"Paris 241\"),\n PARIS_242A(17, \"Paris 242A\"),\n PARIS_242B(18, \"Paris 242B\"),\n PARIS_242AB(19, \"Paris 242-AB\"),\n PARIS_242A_LAB(20, \"Paris 242A Lab\"),\n PARIS_242B_LAB(21, \"Paris 242B Lab\"),\n PARIS_243(22, \"Paris 243\"),\n PARIS_243_T(23, \"Paris 243\");\n\n public final int id;\n public final String name;\n\n Room(int id, String name) {\n this.id = id;\n this.name = name;\n }\n\n public static Room getFromId(int id) {\n for (Room room : Room.values()) {\n if (room.id == id) {\n return room;\n }\n }\n return EXHIBITION_FLOOR;\n }\n\n public static Room getFromName(@NonNull String name) {\n for (Room room : Room.values()) {\n if (name.equals(room.name)) {\n return room;\n }\n }\n return EXHIBITION_FLOOR;\n }\n}", "public class Session {\n\n public static final String TABLE = \"sessions\";\n\n public static final String ID = \"_id\";\n public static final String START_AT = \"start_at\";\n public static final String DURATION = \"duration\";\n public static final String ROOM_ID = \"room_id\";\n public static final String SPEAKERS_IDS = \"speakers_ids\";\n public static final String TITLE = \"title\";\n public static final String DESCRIPTION = \"description\";\n\n public final int id;\n public final String startAt;\n public final int duration;\n public final int roomId;\n public final String speakersIds;\n public final String title;\n public final String description;\n\n public Session(int id, String startAt, int duration, int roomId, String speakersIds, String title, String description) {\n this.id = id;\n this.startAt = startAt;\n this.duration = duration;\n this.roomId = roomId;\n this.speakersIds = speakersIds;\n this.title = title;\n this.description = description;\n }\n\n public static final Func1<Cursor, Session> MAPPER = cursor -> {\n int id = Database.getInt(cursor, ID);\n String startAt = Database.getString(cursor, START_AT);\n int duration = Database.getInt(cursor, DURATION);\n int roomId = Database.getInt(cursor, ROOM_ID);\n String speakersIds = Database.getString(cursor, SPEAKERS_IDS);\n String title = Database.getString(cursor, TITLE);\n String description = Database.getString(cursor, DESCRIPTION);\n return new Session(id, startAt, duration, roomId, speakersIds, title, description);\n };\n\n public static ContentValues createContentValues(Session session) {\n ContentValues values = new ContentValues();\n values.put(ID, session.id);\n values.put(START_AT, session.startAt);\n values.put(DURATION, session.duration);\n values.put(ROOM_ID, session.roomId);\n values.put(SPEAKERS_IDS, session.speakersIds);\n values.put(TITLE, session.title);\n values.put(DESCRIPTION, session.description);\n return values;\n }\n}", "public class Speaker {\n\n public static final String TABLE = \"speakers\";\n\n public static final String ID = \"_id\";\n public static final String NAME = \"name\";\n public static final String TITLE = \"title\";\n public static final String BIO = \"bio\";\n public static final String WEBSITE = \"website\";\n public static final String TWITTER = \"twitter\";\n public static final String GITHUB = \"github\";\n public static final String PHOTO = \"photo\";\n\n public final int id;\n public final String name;\n public final String title;\n public final String bio;\n public final String website;\n public final String twitter;\n public final String github;\n public final String photo;\n\n public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) {\n this.id = id;\n this.name = name;\n this.title = title;\n this.bio = bio;\n this.website = website;\n this.twitter = twitter;\n this.github = github;\n this.photo = photo;\n }\n\n public static final Func1<Cursor, Speaker> MAPPER = cursor -> {\n int id = Database.getInt(cursor, ID);\n String name = Database.getString(cursor, NAME);\n String title = Database.getString(cursor, TITLE);\n String bio = Database.getString(cursor, BIO);\n String website = Database.getString(cursor, WEBSITE);\n String twitter = Database.getString(cursor, TWITTER);\n String github = Database.getString(cursor, GITHUB);\n String photo = Database.getString(cursor, PHOTO);\n return new Speaker(id, name, title, bio, website, twitter, github, photo);\n };\n\n public static ContentValues createContentValues(Speaker speaker) {\n ContentValues values = new ContentValues();\n values.put(ID, speaker.id);\n values.put(NAME, speaker.name);\n values.put(TITLE, speaker.title);\n values.put(BIO, speaker.bio);\n values.put(WEBSITE, speaker.website);\n values.put(TWITTER, speaker.twitter);\n values.put(GITHUB, speaker.github);\n values.put(PHOTO, speaker.photo);\n return values;\n }\n}" ]
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.nilhcem.devoxxfr.core.moshi.LocalDateTimeAdapter; import com.nilhcem.devoxxfr.data.app.AppMapper; import com.nilhcem.devoxxfr.data.app.model.Room; import com.nilhcem.devoxxfr.data.database.model.Session; import com.nilhcem.devoxxfr.data.database.model.Speaker; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import com.squareup.moshi.Types; import org.threeten.bp.LocalDateTime; import org.threeten.bp.temporal.ChronoUnit; import java.io.IOException; import java.util.List; import java.util.Map; import javax.inject.Inject; import java8.util.stream.Collectors; import timber.log.Timber; import static java8.util.stream.StreamSupport.stream;
package com.nilhcem.devoxxfr.data.database; public class DbMapper { private final AppMapper appMapper; private final LocalDateTimeAdapter localDateTimeAdapter; private final JsonAdapter<List<Integer>> intListAdapter; @Inject public DbMapper(Moshi moshi, AppMapper appMapper, LocalDateTimeAdapter localDateTimeAdapter) { this.appMapper = appMapper; this.localDateTimeAdapter = localDateTimeAdapter; this.intListAdapter = moshi.adapter(Types.newParameterizedType(List.class, Integer.class)); }
public List<com.nilhcem.devoxxfr.data.app.model.Session> toAppSessions(@NonNull List<Session> from, @NonNull Map<Integer, com.nilhcem.devoxxfr.data.app.model.Speaker> speakersMap) {
3
DDoS/JICI
src/main/java/ca/sapon/jici/parser/expression/logic/BooleanLogic.java
[ "public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\n private final Map<String, Variable> variables = new LinkedHashMap<>();\n\n static {\n for (String name : ReflectionUtil.JAVA_LANG_CLASSES) {\n try {\n DEFAULT_CLASSES.put(name, Class.forName(\"java.lang.\" + name));\n } catch (ClassNotFoundException e) {\n throw new IllegalStateException(\"class java.lang.\" + name + \" not found\");\n }\n }\n }\n\n public void importClass(Class<?> _class) {\n final String name = _class.getCanonicalName();\n // Validate the type of class\n if (_class.isPrimitive()) {\n throw new UnsupportedOperationException(\"Can't import a primitive type: \" + name);\n }\n if (_class.isArray()) {\n throw new UnsupportedOperationException(\"Can't import an array class: \" + name);\n }\n if (_class.isAnonymousClass()) {\n throw new UnsupportedOperationException(\"Can't import an anonymous class: \" + name);\n }\n // Check for existing import under the same simple name\n final String simpleName = _class.getSimpleName();\n final Class<?> existing = classes.get(simpleName);\n // ignore cases where the classes are the same as redundant imports are allowed\n if (existing != null && _class != existing) {\n throw new UnsupportedOperationException(\"Class \" + name + \" clashes with existing import \" + existing.getCanonicalName());\n }\n // Add the class to the imports\n classes.put(simpleName, _class);\n }\n\n public Class<?> findClass(Identifier name) {\n return classes.get(name.getSource());\n }\n\n public Class<?> getClass(Identifier name) {\n final Class<?> _class = findClass(name);\n if (_class == null) {\n throw new UnsupportedOperationException(\"Class \" + name.getSource() + \" does not exist\");\n }\n return _class;\n }\n\n public Collection<Class<?>> getClasses() {\n return classes.values();\n }\n\n public boolean hasClass(Identifier name) {\n return classes.containsKey(name.getSource());\n }\n\n public boolean hasClass(Class<?> _class) {\n return classes.containsValue(_class);\n }\n\n public void declareVariable(Identifier name, LiteralType type, Value value) {\n if (hasVariable(name)) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" is already declared\");\n }\n variables.put(name.getSource(), new Variable(name, type, value));\n }\n\n public LiteralType getVariableType(Identifier name) {\n return findVariable(name).getType();\n }\n\n public Value getVariable(Identifier name) {\n return findVariable(name).getValue();\n }\n\n public Collection<Variable> getVariables() {\n return variables.values();\n }\n\n public void setVariable(Identifier name, Value value) {\n findVariable(name).setValue(value);\n }\n\n public boolean hasVariable(Identifier name) {\n return variables.containsKey(name.getSource());\n }\n\n private Variable findVariable(Identifier name) {\n final String nameString = name.getSource();\n final Variable variable = variables.get(nameString);\n if (variable == null) {\n throw new UnsupportedOperationException(\"Variable \" + nameString + \" does not exist\");\n }\n return variable;\n }\n\n public static class Variable {\n private final Identifier name;\n private final LiteralType type;\n private Value value;\n\n private Variable(Identifier name, LiteralType type, Value value) {\n this.name = name;\n this.type = type;\n this.value = value;\n }\n\n public Identifier getName() {\n return name;\n }\n\n public LiteralType getType() {\n return type;\n }\n\n public boolean initialized() {\n return value != null;\n }\n\n public Value getValue() {\n if (!initialized()) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" has not been initialized\");\n }\n return value;\n }\n\n private void setValue(Value value) {\n this.value = value;\n }\n }\n}", "public class EvaluatorException extends SourceException {\n private static final long serialVersionUID = 1;\n\n public EvaluatorException(Throwable cause, SourceIndexed indexed) {\n this(\"EvaluatorException\", cause, indexed);\n }\n\n public EvaluatorException(String error, Throwable cause, SourceIndexed indexed) {\n super(getMessage(error, cause), cause, null, indexed.getStart(), indexed.getEnd());\n }\n\n public EvaluatorException(String error, SourceIndexed indexed) {\n this(error, indexed.getStart(), indexed.getEnd());\n }\n\n public EvaluatorException(String error, int start, int end) {\n super(error, null, start, end);\n }\n\n private static String getMessage(String error, Throwable cause) {\n if (cause == null) {\n return error;\n }\n String causeMessage = cause.getMessage();\n if (causeMessage != null) {\n causeMessage = causeMessage.trim();\n if (causeMessage.isEmpty()) {\n causeMessage = null;\n }\n }\n error += \" (\" + cause.getClass().getSimpleName();\n if (causeMessage != null) {\n error += \": \" + causeMessage;\n }\n return getMessage(error, cause.getCause()) + \")\";\n }\n}", "public class PrimitiveType implements LiteralType {\n public static final PrimitiveType THE_BOOLEAN;\n public static final PrimitiveType THE_BYTE;\n public static final PrimitiveType THE_SHORT;\n public static final PrimitiveType THE_CHAR;\n public static final PrimitiveType THE_INT;\n public static final PrimitiveType THE_LONG;\n public static final PrimitiveType THE_FLOAT;\n public static final PrimitiveType THE_DOUBLE;\n private static final Map<Class<?>, PrimitiveType> ALL_TYPES = new HashMap<>();\n private static final Map<Class<?>, Set<Class<?>>> PRIMITIVE_CONVERSIONS = new HashMap<>();\n private static final Map<Class<?>, LiteralReferenceType> BOXING_CONVERSIONS = new HashMap<>();\n private static final Map<Class<?>, RangeChecker> NARROW_CHECKERS = new HashMap<>();\n private static final Set<Class<?>> UNARY_WIDENS_INT = new HashSet<>();\n private static final Map<Class<?>, Widener> BINARY_WIDENERS = new HashMap<>();\n private final Class<?> type;\n private final ValueKind kind;\n\n static {\n THE_BOOLEAN = new PrimitiveType(boolean.class, ValueKind.BOOLEAN);\n THE_BYTE = new PrimitiveType(byte.class, ValueKind.BYTE);\n THE_SHORT = new PrimitiveType(short.class, ValueKind.SHORT);\n THE_CHAR = new PrimitiveType(char.class, ValueKind.CHAR);\n THE_INT = new PrimitiveType(int.class, ValueKind.INT);\n THE_LONG = new PrimitiveType(long.class, ValueKind.LONG);\n THE_FLOAT = new PrimitiveType(float.class, ValueKind.FLOAT);\n THE_DOUBLE = new PrimitiveType(double.class, ValueKind.DOUBLE);\n\n ALL_TYPES.put(boolean.class, THE_BOOLEAN);\n ALL_TYPES.put(byte.class, THE_BYTE);\n ALL_TYPES.put(short.class, THE_SHORT);\n ALL_TYPES.put(char.class, THE_CHAR);\n ALL_TYPES.put(int.class, THE_INT);\n ALL_TYPES.put(long.class, THE_LONG);\n ALL_TYPES.put(float.class, THE_FLOAT);\n ALL_TYPES.put(double.class, THE_DOUBLE);\n\n PRIMITIVE_CONVERSIONS.put(boolean.class, new HashSet<Class<?>>(Collections.singletonList(boolean.class)));\n PRIMITIVE_CONVERSIONS.put(byte.class, new HashSet<Class<?>>(Arrays.asList(byte.class, short.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(short.class, new HashSet<Class<?>>(Arrays.asList(short.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(char.class, new HashSet<Class<?>>(Arrays.asList(char.class, int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(int.class, new HashSet<Class<?>>(Arrays.asList(int.class, long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(long.class, new HashSet<Class<?>>(Arrays.asList(long.class, float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(float.class, new HashSet<Class<?>>(Arrays.asList(float.class, double.class)));\n PRIMITIVE_CONVERSIONS.put(double.class, new HashSet<Class<?>>(Collections.singletonList(double.class)));\n\n BOXING_CONVERSIONS.put(boolean.class, LiteralReferenceType.of(Boolean.class));\n BOXING_CONVERSIONS.put(byte.class, LiteralReferenceType.of(Byte.class));\n BOXING_CONVERSIONS.put(short.class, LiteralReferenceType.of(Short.class));\n BOXING_CONVERSIONS.put(char.class, LiteralReferenceType.of(Character.class));\n BOXING_CONVERSIONS.put(int.class, LiteralReferenceType.of(Integer.class));\n BOXING_CONVERSIONS.put(long.class, LiteralReferenceType.of(Long.class));\n BOXING_CONVERSIONS.put(float.class, LiteralReferenceType.of(Float.class));\n BOXING_CONVERSIONS.put(double.class, LiteralReferenceType.of(Double.class));\n\n NARROW_CHECKERS.put(byte.class, new RangeChecker(-128, 0xFF));\n NARROW_CHECKERS.put(short.class, new RangeChecker(-32768, 0xFFFF));\n NARROW_CHECKERS.put(char.class, new RangeChecker(0, 0xFFFF));\n\n Collections.addAll(UNARY_WIDENS_INT, byte.class, short.class, char.class);\n\n final Widener intWidener = new Widener(int.class, byte.class, short.class, char.class);\n BINARY_WIDENERS.put(byte.class, intWidener);\n BINARY_WIDENERS.put(short.class, intWidener);\n BINARY_WIDENERS.put(char.class, intWidener);\n BINARY_WIDENERS.put(int.class, intWidener);\n BINARY_WIDENERS.put(long.class, new Widener(long.class, byte.class, short.class, char.class, int.class));\n BINARY_WIDENERS.put(float.class, new Widener(float.class, byte.class, short.class, char.class, int.class, long.class));\n BINARY_WIDENERS.put(double.class, new Widener(double.class, byte.class, short.class, char.class, int.class, long.class, float.class));\n }\n\n private PrimitiveType(Class<?> type, ValueKind kind) {\n this.type = type;\n this.kind = kind;\n }\n\n @Override\n public Class<?> getTypeClass() {\n return type;\n }\n\n @Override\n public String getName() {\n return type.getCanonicalName();\n }\n\n @Override\n public ValueKind getKind() {\n return kind;\n }\n\n @Override\n public boolean isVoid() {\n return false;\n }\n\n @Override\n public boolean isNull() {\n return false;\n }\n\n @Override\n public boolean isPrimitive() {\n return true;\n }\n\n @Override\n public boolean isNumeric() {\n return isIntegral() || type == float.class || type == double.class;\n }\n\n @Override\n public boolean isIntegral() {\n return type == byte.class || type == short.class || type == char.class || type == int.class || type == long.class;\n }\n\n @Override\n public boolean isBoolean() {\n return type == boolean.class;\n }\n\n @Override\n public boolean isArray() {\n return false;\n }\n\n @Override\n public boolean isReference() {\n return false;\n }\n\n @Override\n public boolean isReifiable() {\n return true;\n }\n\n @Override\n public LiteralReferenceType asArray(int dimensions) {\n return LiteralReferenceType.of(ReflectionUtil.asArrayType(type, dimensions));\n }\n\n @Override\n public Object newArray(int length) {\n return Array.newInstance(type, length);\n }\n\n @Override\n public Object newArray(int[] lengths) {\n return Array.newInstance(type, lengths);\n }\n\n public SingleReferenceType box() {\n return BOXING_CONVERSIONS.get(type);\n }\n\n public boolean canNarrowFrom(int value) {\n final RangeChecker checker = NARROW_CHECKERS.get(type);\n return checker != null && checker.contains(value);\n }\n\n public PrimitiveType unaryWiden() {\n return of(UNARY_WIDENS_INT.contains(type) ? int.class : type);\n }\n\n public PrimitiveType binaryWiden(PrimitiveType with) {\n return of(BINARY_WIDENERS.get(type).widen(with.getTypeClass()));\n }\n\n @Override\n public boolean convertibleTo(Type to) {\n // Primitive types can be converted to certain primitive types\n // If the target type isn't primitive, box the source and try again\n if (to.isPrimitive()) {\n final PrimitiveType target = (PrimitiveType) to;\n return PRIMITIVE_CONVERSIONS.get(type).contains(target.getTypeClass());\n }\n return box().convertibleTo(to);\n }\n\n @Override\n public PrimitiveType capture() {\n return this;\n }\n\n @Override\n public String toString() {\n return getName();\n }\n\n @Override\n public boolean equals(Object other) {\n return this == other || other instanceof PrimitiveType && this.type == ((PrimitiveType) other).getTypeClass();\n }\n\n @Override\n public int hashCode() {\n return type.getName().hashCode();\n }\n\n public static PrimitiveType of(Class<?> type) {\n return ALL_TYPES.get(type);\n }\n\n private static class RangeChecker {\n private final int minValue;\n private final int invertedMask;\n\n private RangeChecker(int minValue, int mask) {\n this.minValue = minValue;\n invertedMask = ~mask;\n }\n\n private boolean contains(int value) {\n return (value - minValue & invertedMask) == 0;\n }\n }\n\n private static class Widener {\n private final Class<?> wider;\n private final Set<Class<?>> widens = new HashSet<>();\n\n private Widener(Class<?> wider, Class<?>... widens) {\n this.wider = wider;\n Collections.addAll(this.widens, widens);\n }\n\n private Class<?> widen(Class<?> type) {\n return widens.contains(type) ? wider : type;\n }\n }\n}", "public interface Type {\n String getName();\n\n ValueKind getKind();\n\n boolean isVoid();\n\n boolean isNull();\n\n boolean isPrimitive();\n\n boolean isNumeric();\n\n boolean isIntegral();\n\n boolean isBoolean();\n\n boolean isArray();\n\n boolean isReference();\n\n boolean isReifiable();\n\n boolean convertibleTo(Type to);\n\n Type capture();\n\n @Override\n String toString();\n\n @Override\n boolean equals(Object other);\n\n @Override\n int hashCode();\n}", "public class BooleanValue implements Value {\n private static final BooleanValue THE_TRUE = new BooleanValue(true);\n private static final BooleanValue THE_FALSE = new BooleanValue(false);\n private final boolean value;\n\n private BooleanValue(boolean value) {\n this.value = value;\n }\n\n @Override\n public boolean asBoolean() {\n return value;\n }\n\n @Override\n public byte asByte() {\n throw new UnsupportedOperationException(\"Cannot convert a boolean to a byte\");\n }\n\n @Override\n public short asShort() {\n throw new UnsupportedOperationException(\"Cannot convert a boolean to a short\");\n }\n\n @Override\n public char asChar() {\n throw new UnsupportedOperationException(\"Cannot convert a boolean to a char\");\n }\n\n @Override\n public int asInt() {\n throw new UnsupportedOperationException(\"Cannot convert a boolean to an int\");\n }\n\n @Override\n public long asLong() {\n throw new UnsupportedOperationException(\"Cannot convert a boolean to a long\");\n }\n\n @Override\n public float asFloat() {\n throw new UnsupportedOperationException(\"Cannot convert a boolean to a float\");\n }\n\n @Override\n public double asDouble() {\n throw new UnsupportedOperationException(\"Cannot convert a boolean to a double\");\n }\n\n @Override\n public Boolean asObject() {\n return value;\n }\n\n @Override\n public String asString() {\n return Boolean.toString(value);\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n public <T> T as() {\n return (T) asObject();\n }\n\n @Override\n public ValueKind getKind() {\n return ValueKind.BOOLEAN;\n }\n\n @Override\n public boolean isPrimitive() {\n return true;\n }\n\n @Override\n public Class<?> getTypeClass() {\n return boolean.class;\n }\n\n @Override\n public String toString() {\n return asString();\n }\n\n public static BooleanValue of(boolean value) {\n return value ? THE_TRUE : THE_FALSE;\n }\n\n public static BooleanValue defaultValue() {\n return THE_FALSE;\n }\n}", "public interface Value {\n boolean asBoolean();\n\n byte asByte();\n\n short asShort();\n\n char asChar();\n\n int asInt();\n\n long asLong();\n\n float asFloat();\n\n double asDouble();\n\n Object asObject();\n\n String asString();\n\n <T> T as();\n\n ValueKind getKind();\n\n boolean isPrimitive();\n\n Class<?> getTypeClass();\n\n String toString();\n}", "public class Symbol extends Token {\n private static final Map<String, Symbol> SYMBOLS = new HashMap<>();\n private static final Symbol[] CHAR_SYMBOLS = new Symbol[256];\n private final Symbol compoundAssignOperator;\n\n static {\n // punctuation\n add(TokenID.SYMBOL_PERIOD, \".\");\n add(TokenID.SYMBOL_COMMA, \",\");\n add(TokenID.SYMBOL_COLON, \":\");\n add(TokenID.SYMBOL_SEMICOLON, \";\");\n // math\n add(TokenID.SYMBOL_PLUS, \"+\");\n add(TokenID.SYMBOL_MINUS, \"-\");\n add(TokenID.SYMBOL_MULTIPLY, \"*\");\n add(TokenID.SYMBOL_DIVIDE, \"/\");\n add(TokenID.SYMBOL_MODULO, \"%\");\n add(TokenID.SYMBOL_INCREMENT, \"++\", \"+\");\n add(TokenID.SYMBOL_DECREMENT, \"--\", \"-\");\n // bitwise\n add(TokenID.SYMBOL_BITWISE_AND, \"&\");\n add(TokenID.SYMBOL_BITWISE_OR, \"|\");\n add(TokenID.SYMBOL_BITWISE_NOT, \"~\");\n add(TokenID.SYMBOL_BITWISE_XOR, \"^\");\n // shift\n add(TokenID.SYMBOL_LOGICAL_LEFT_SHIFT, \"<<\");\n add(TokenID.SYMBOL_ARITHMETIC_RIGHT_SHIFT, \">>\");\n add(TokenID.SYMBOL_LOGICAL_RIGHT_SHIFT, \">>>\");\n // boolean\n add(TokenID.SYMBOL_BOOLEAN_NOT, \"!\");\n add(TokenID.SYMBOL_BOOLEAN_AND, \"&&\");\n add(TokenID.SYMBOL_BOOLEAN_OR, \"||\");\n // comparison\n add(TokenID.SYMBOL_LESSER, \"<\");\n add(TokenID.SYMBOL_GREATER, \">\");\n add(TokenID.SYMBOL_GREATER_OR_EQUAL, \">=\");\n add(TokenID.SYMBOL_LESSER_OR_EQUAL, \"<=\");\n add(TokenID.SYMBOL_EQUAL, \"==\");\n add(TokenID.SYMBOL_NOT_EQUAL, \"!=\");\n // assignment\n add(TokenID.SYMBOL_ASSIGN, \"=\");\n add(TokenID.SYMBOL_ADD_ASSIGN, \"+=\", \"+\");\n add(TokenID.SYMBOL_SUBTRACT_ASSIGN, \"-=\", \"-\");\n add(TokenID.SYMBOL_MULTIPLY_ASSIGN, \"*=\", \"*\");\n add(TokenID.SYMBOL_DIVIDE_ASSIGN, \"/=\", \"/\");\n add(TokenID.SYMBOL_REMAINDER_ASSIGN, \"%=\", \"%\");\n add(TokenID.SYMBOL_BITWISE_AND_ASSIGN, \"&=\", \"&\");\n add(TokenID.SYMBOL_BITWISE_OR_ASSIGN, \"|=\", \"|\");\n add(TokenID.SYMBOL_BITWISE_XOR_ASSIGN, \"^=\", \"^\");\n add(TokenID.SYMBOL_LOGICAL_LEFT_SHIFT_ASSIGN, \"<<=\", \"<<\");\n add(TokenID.SYMBOL_ARITHMETIC_RIGHT_SHIFT_ASSIGN, \">>=\", \">>\");\n add(TokenID.SYMBOL_LOGICAL_RIGHT_SHIFT_ASSIGN, \">>>=\", \">>>\");\n // enclosing\n add(TokenID.SYMBOL_OPEN_PARENTHESIS, \"(\");\n add(TokenID.SYMBOL_CLOSE_PARENTHESIS, \")\");\n add(TokenID.SYMBOL_OPEN_BRACKET, \"[\");\n add(TokenID.SYMBOL_CLOSE_BRACKET, \"]\");\n add(TokenID.SYMBOL_OPEN_BRACE, \"{\");\n add(TokenID.SYMBOL_CLOSE_BRACE, \"}\");\n // comment\n add(TokenID.SYMBOL_DOUBLE_SLASH, \"//\");\n add(TokenID.SYMBOL_SLASH_STAR, \"/*\");\n add(TokenID.SYMBOL_STAR_SLASH, \"*/\");\n // other\n add(TokenID.SYMBOL_QUESTION_MARK, \"?\");\n add(TokenID.SYMBOL_DOUBLE_PERIOD, \"..\");\n add(TokenID.SYMBOL_TRIPLE_PERIOD, \"...\");\n add(TokenID.SYMBOL_DOUBLE_COLON, \"::\");\n add(TokenID.SYMBOL_ARROW, \"->\");\n add(TokenID.SYMBOL_AT, \"@\");\n }\n\n private Symbol(Symbol token, int index) {\n this(token.getID(), token.getSource(), index, token.getCompoundAssignOperator());\n }\n\n private Symbol(TokenID id, String source, int index, Symbol compoundAssignOperator) {\n super(id, source, index);\n this.compoundAssignOperator = compoundAssignOperator;\n }\n\n public Symbol getCompoundAssignOperator() {\n return compoundAssignOperator;\n }\n\n public static boolean is(char source) {\n return CHAR_SYMBOLS[source] != null;\n }\n\n public static boolean is(String source) {\n if (source.length() == 1) {\n return is(source.charAt(0));\n }\n return SYMBOLS.containsKey(source);\n }\n\n public static Symbol from(char source, int index) {\n final Symbol symbol = CHAR_SYMBOLS[source];\n return symbol == null ? null : new Symbol(symbol, index);\n }\n\n public static Symbol from(String source, int index) {\n if (source.length() == 1) {\n return from(source.charAt(0), index);\n }\n final Symbol symbol = SYMBOLS.get(source);\n return symbol == null ? null : new Symbol(symbol, index);\n }\n\n public static Collection<Symbol> all() {\n return Collections.unmodifiableCollection(SYMBOLS.values());\n }\n\n private static void add(TokenID id, String source) {\n add(id, source, null);\n }\n\n private static void add(TokenID id, String source, String compoundAssignOperator) {\n final Symbol symbol = new Symbol(id, source, 0, SYMBOLS.get(compoundAssignOperator));\n SYMBOLS.put(source, symbol);\n if (source.length() == 1) {\n CHAR_SYMBOLS[source.charAt(0)] = symbol;\n }\n }\n}", "public interface Expression extends SourceIndexed {\n Type getType(Environment environment);\n\n Value getValue(Environment environment);\n\n void setStart(int start);\n\n void setEnd(int end);\n\n String toString();\n}", "public final class TypeUtil {\n private TypeUtil() {\n }\n\n public static <T extends Type> Set<T> removeSubTypes(Collection<T> types) {\n return filterTypes(types, SubTypeFilter.INSTANCE, SuperTypeFilter.INSTANCE);\n }\n\n public static <T extends Type> Set<T> removeSuperTypes(Collection<T> types) {\n return filterTypes(types, SuperTypeFilter.INSTANCE, SubTypeFilter.INSTANCE);\n }\n\n private static <T extends Type> Set<T> filterTypes(Collection<T> types, BiPredicate<Type, Type> potentialFilter, BiPredicate<Type, Type> existingFilter) {\n if (types.isEmpty()) {\n // Fast track trivial cases\n return Collections.emptySet();\n }\n if (types.size() == 1) {\n // Fast track trivial cases\n return Collections.singleton(types.iterator().next());\n }\n // Discard any member that is a super type of another\n final Set<T> filteredTypes = new LinkedHashSet<>();\n potentialCandidates:\n for (T potentialCandidate : types) {\n for (Iterator<T> iterator = filteredTypes.iterator(); iterator.hasNext(); ) {\n final T existingCandidate = iterator.next();\n if (potentialFilter.test(potentialCandidate, existingCandidate)) {\n // potential candidate is filtered for existing one, don't add\n continue potentialCandidates;\n } else if (existingFilter.test(potentialCandidate, existingCandidate)) {\n // existing candidate is filtered for potential one, remove it\n iterator.remove();\n }\n }\n filteredTypes.add(potentialCandidate);\n }\n return filteredTypes;\n }\n\n public static Set<SingleReferenceType> expandIntersectionTypes(Collection<? extends ReferenceType> intersection) {\n final Set<SingleReferenceType> expandedTypes = new LinkedHashSet<>(intersection.size());\n for (ReferenceType type : intersection) {\n if (type instanceof IntersectionType) {\n expandedTypes.addAll(((IntersectionType) type).getTypes());\n } else {\n expandedTypes.add((SingleReferenceType) type);\n }\n }\n return expandedTypes;\n }\n\n public static IntersectionType lowestUpperBound(ReferenceType... types) {\n return lowestUpperBound(Arrays.asList(types));\n }\n\n public static IntersectionType lowestUpperBound(Collection<? extends ReferenceType> types) {\n return lowestUpperBound(expandIntersectionTypes(types));\n }\n\n public static IntersectionType lowestUpperBound(Set<SingleReferenceType> types) {\n return lowestUpperBound(types, new HashMap<Set<SingleReferenceType>, Integer>());\n }\n\n private static IntersectionType lowestUpperBound(Set<SingleReferenceType> types, Map<Set<SingleReferenceType>, Integer> recursions) {\n // Simplify the argument set to standardize it and make things faster\n types = TypeUtil.removeSubTypes(types);\n if (types.isEmpty()) {\n // Fast track trivial cases\n return IntersectionType.NOTHING;\n }\n // Get the number of recursive calls so far with the same arguments\n Integer count = recursions.get(types);\n if (count == null) {\n count = 0;\n }\n if (++count > 2) {\n // Recursive lowest upper bound calls can lead to infinite types, don't compute a bound after two recursions (like javac does)\n return IntersectionType.NOTHING;\n }\n recursions.put(types, count);\n if (types.size() == 1) {\n // Fast track trivial cases\n return IntersectionType.of(types);\n }\n // Get the super type sets ST(U)\n final Map<ReferenceType, Set<LiteralReferenceType>> superTypeSets = new HashMap<>();\n final Collection<Set<LiteralReferenceType>> superTypes = superTypeSets.values();\n for (SingleReferenceType type : types) {\n if (type.convertibleTo(NullType.THE_NULL)) {\n // The null type has a universal set of super types, we can skip it\n continue;\n }\n superTypeSets.put(type, type.getSuperTypes());\n }\n // Intersect the erased super type sets EST(U) to generate the erased candidate set EC\n final Set<LiteralReferenceType> erasedCandidates = new HashSet<>();\n final Iterator<Set<LiteralReferenceType>> superTypesIterator = superTypes.iterator();\n erasedCandidates.addAll(getErasures(superTypesIterator.next()));\n while (superTypesIterator.hasNext()) {\n erasedCandidates.retainAll(getErasures(superTypesIterator.next()));\n }\n // Get the minimal erased candidate set MEC\n final Set<LiteralReferenceType> minimalErasedCandidates = removeSuperTypes(erasedCandidates);\n // For generic candidates (those with relevant invocations) compute the least containing invocation\n final Set<SingleReferenceType> lowestUpperBound = new HashSet<>();\n for (LiteralReferenceType candidate : minimalErasedCandidates) {\n final Set<ParametrizedType> invocations = relevantInvocations(superTypes, candidate);\n if (invocations.isEmpty()) {\n lowestUpperBound.add(candidate);\n } else {\n lowestUpperBound.add(leastContainingInvocation(invocations, recursions));\n }\n }\n return IntersectionType.of(lowestUpperBound);\n }\n\n private static ParametrizedType leastContainingInvocation(Set<ParametrizedType> invocations, Map<Set<SingleReferenceType>, Integer> recursions) {\n final Iterator<ParametrizedType> iterator = invocations.iterator();\n ParametrizedType left = iterator.next();\n if (invocations.size() == 1) {\n // For a single invocation we get the least containing type argument of each invocation argument\n final List<TypeArgument> arguments = left.getArguments();\n final List<TypeArgument> leastArguments = new ArrayList<>(arguments.size());\n for (TypeArgument argument : arguments) {\n leastArguments.add(leastContainingTypeArgument(argument, recursions));\n }\n return ParametrizedType.of(left.getErasure(), leastArguments);\n }\n // For many invocation we reduce pairwise, left with right\n while (iterator.hasNext()) {\n // The least containing type argument is done pairwise on the arguments of the left and right type\n final ParametrizedType right = iterator.next();\n final List<TypeArgument> leftArguments = left.getArguments();\n final List<TypeArgument> rightArguments = right.getArguments();\n final List<TypeArgument> leastArguments = new ArrayList<>(leftArguments.size());\n for (int i = 0; i < leftArguments.size(); i++) {\n leastArguments.add(leastContainingTypeArgument(leftArguments.get(i), rightArguments.get(i), recursions));\n }\n left = ParametrizedType.of(left.getErasure(), leastArguments);\n }\n return left;\n }\n\n private static TypeArgument leastContainingTypeArgument(TypeArgument left, TypeArgument right, Map<Set<SingleReferenceType>, Integer> recursions) {\n // In the case where one argument isn't a wildcard type, ensure the non-wildcard is on the left\n if (!(right instanceof WildcardType)) {\n final TypeArgument swap = left;\n left = right;\n right = swap;\n }\n if (left instanceof WildcardType) {\n // Pair of wildcards\n return leastContainingTypeArgument((WildcardType) left, (WildcardType) right, recursions);\n }\n if (right instanceof WildcardType) {\n // Only one wildcard\n return leastContainingTypeArgument(left, (WildcardType) right, recursions);\n }\n // No wildcards\n final Set<SingleReferenceType> combinedUpperBound = new HashSet<>();\n combinedUpperBound.add((SingleReferenceType) left);\n combinedUpperBound.add((SingleReferenceType) right);\n return left.equals(right) ? left : WildcardType.of(IntersectionType.EVERYTHING, lowestUpperBound(combinedUpperBound, recursions));\n }\n\n private static TypeArgument leastContainingTypeArgument(WildcardType left, WildcardType right, Map<Set<SingleReferenceType>, Integer> recursions) {\n final Set<SingleReferenceType> combinedUpperBound = new HashSet<>(left.getUpperBound().getTypes());\n final Set<SingleReferenceType> combinedLowerBound = new HashSet<>(left.getLowerBound().getTypes());\n combinedUpperBound.addAll(right.getUpperBound().getTypes());\n combinedLowerBound.addAll(right.getLowerBound().getTypes());\n return combinedUpperBound.equals(combinedLowerBound) ? IntersectionType.of(combinedUpperBound)\n : WildcardType.of(IntersectionType.of(combinedLowerBound), lowestUpperBound(combinedUpperBound, recursions));\n }\n\n private static TypeArgument leastContainingTypeArgument(TypeArgument left, WildcardType right, Map<Set<SingleReferenceType>, Integer> recursions) {\n final Set<SingleReferenceType> combinedUpperBound = new HashSet<>(right.getUpperBound().getTypes());\n final Set<SingleReferenceType> combinedLowerBound = new HashSet<>(right.getLowerBound().getTypes());\n combinedUpperBound.add((SingleReferenceType) left);\n combinedLowerBound.add((SingleReferenceType) left);\n return WildcardType.of(IntersectionType.of(combinedLowerBound), lowestUpperBound(combinedUpperBound, recursions));\n }\n\n private static TypeArgument leastContainingTypeArgument(TypeArgument argument, Map<Set<SingleReferenceType>, Integer> recursions) {\n final Set<SingleReferenceType> combinedUpperBound = new HashSet<>();\n final Set<SingleReferenceType> combinedLowerBound = new HashSet<>();\n // Left type is argument\n if (argument instanceof WildcardType) {\n final WildcardType wildcard = (WildcardType) argument;\n combinedUpperBound.addAll(wildcard.getUpperBound().getTypes());\n combinedLowerBound.addAll(wildcard.getLowerBound().getTypes());\n } else {\n combinedUpperBound.add((SingleReferenceType) argument);\n combinedLowerBound.add((SingleReferenceType) argument);\n }\n // Right type is ?\n combinedUpperBound.add(LiteralReferenceType.THE_OBJECT);\n combinedLowerBound.add(NullType.THE_NULL);\n return WildcardType.of(IntersectionType.of(combinedLowerBound), lowestUpperBound(combinedUpperBound, recursions));\n }\n\n private static Set<ParametrizedType> relevantInvocations(Collection<Set<LiteralReferenceType>> superTypeSets, LiteralReferenceType type) {\n // Search for an invocation of the erased type in any of the super type sets\n final Set<ParametrizedType> invocations = new HashSet<>();\n for (Set<LiteralReferenceType> superTypes : superTypeSets) {\n for (LiteralReferenceType superType : superTypes) {\n if (superType instanceof ParametrizedType) {\n final ParametrizedType parametrizedType = (ParametrizedType) superType;\n if (parametrizedType.getErasure().equals(type)) {\n invocations.add(parametrizedType);\n }\n }\n }\n }\n return invocations;\n }\n\n private static Set<LiteralReferenceType> getErasures(Set<LiteralReferenceType> types) {\n final Set<LiteralReferenceType> erased = new HashSet<>();\n for (LiteralReferenceType type : types) {\n erased.add(type.getErasure());\n }\n return erased;\n }\n\n public static PrimitiveType coerceToPrimitive(Environment environment, Expression expression) {\n return coerceToPrimitive(expression, expression.getType(environment));\n }\n\n public static PrimitiveType coerceToPrimitive(Expression expression, Type type) {\n final PrimitiveType primitiveType;\n if (type instanceof PrimitiveType) {\n primitiveType = (PrimitiveType) type;\n } else if (type instanceof LiteralReferenceType && ((LiteralReferenceType) type).isBox()) {\n primitiveType = ((LiteralReferenceType) type).unbox();\n } else {\n throw new EvaluatorException(\"Not a primitive type: \" + type.getName(), expression);\n }\n return primitiveType;\n }\n\n public static boolean isValidReferenceCast(ReferenceType sourceType, ReferenceType targetType) {\n if (sourceType.isNull()) {\n // source type is null, can always cast to anything\n return true;\n }\n if (sourceType instanceof LiteralReferenceType) {\n // source is a literal reference type, which has sub-cases\n final LiteralReferenceType source = (LiteralReferenceType) sourceType;\n if (source.isArray()) {\n // source is an array type, which has sub-cases\n if (targetType instanceof LiteralReferenceType) {\n // target is a literal reference type, which has sub-cases\n final LiteralReferenceType target = (LiteralReferenceType) targetType;\n if (target.isArray()) {\n // target is an array type, allow if same primitive type else apply recursively on components\n final ComponentType sourceComponent = source.getComponentType();\n final ComponentType targetComponent = target.getComponentType();\n return sourceComponent.isPrimitive() && targetComponent.isPrimitive() && sourceComponent.equals(targetComponent)\n || isValidReferenceCast((ReferenceType) sourceComponent, (ReferenceType) targetComponent);\n }\n // target is a class or interface type, only allow object, serializable and cloneable\n return target.equals(LiteralReferenceType.THE_OBJECT) || target.equals(LiteralReferenceType.THE_SERIALIZABLE)\n || target.equals(LiteralReferenceType.THE_CLONEABLE);\n }\n if (targetType instanceof TypeVariable) {\n // target is a type variable, apply recursively to upper bound\n final TypeVariable target = (TypeVariable) targetType;\n return isValidReferenceCast(source, target.getUpperBound());\n }\n // any other target type is undefined\n return false;\n }\n if (source.isInterface()) {\n // source is an interface type, which has sub-cases\n if (targetType instanceof LiteralReferenceType) {\n // target is a literal reference type, which has sub-cases\n final LiteralReferenceType target = (LiteralReferenceType) targetType;\n if (target.isArray()) {\n // target is an array type, source must be serializable or cloneable\n return source.equals(LiteralReferenceType.THE_SERIALIZABLE) || source.equals(LiteralReferenceType.THE_CLONEABLE);\n }\n if (Modifier.isFinal(target.getTypeClass().getModifiers())) {\n // target is final, which has sub-cases\n if (target instanceof ParametrizedType || target.isRaw()) {\n // target is parametrized or raw, target must be an invocation of source generic declaration\n return hasInvocationSuperType(target, source);\n }\n // target is neither parametrized nor raw, target must implement source\n return target.convertibleTo(source);\n }\n // target is not final, generic parents cannot conflict\n return !haveProvablyDistinctInvocationsInSuperTypes(source, target);\n }\n // any other target type is always valid\n return true;\n }\n // source is a class type, which has sub-cases\n if (targetType instanceof LiteralReferenceType) {\n // target is a literal reference type, which has sub-cases\n final LiteralReferenceType target = (LiteralReferenceType) targetType;\n if (target.isArray()) {\n // target is an array type, source must be object\n return source.equals(LiteralReferenceType.THE_OBJECT);\n }\n if (target.isInterface()) {\n // target is an interface type, which has sub-cases\n if (Modifier.isFinal(source.getTypeClass().getModifiers())) {\n // source is final, source must implement target\n return source.convertibleTo(target);\n }\n // source is not final, generic parents cannot conflict\n return !haveProvablyDistinctInvocationsInSuperTypes(source, target);\n }\n // target is a class type, erasures must be super or sub types and generic parents cannot conflict\n final LiteralReferenceType sourceErasure = source.getErasure();\n final LiteralReferenceType targetErasure = target.getErasure();\n return (sourceErasure.convertibleTo(targetErasure) || targetErasure.convertibleTo(targetErasure))\n && !haveProvablyDistinctInvocationsInSuperTypes(source, target);\n }\n if (targetType instanceof TypeVariable) {\n // target is a type variable, apply recursively to upper bound\n final TypeVariable target = (TypeVariable) targetType;\n return isValidReferenceCast(source, target.getUpperBound());\n }\n }\n if (sourceType instanceof TypeVariable) {\n // source is a type variable, apply recursively to upper bound\n final TypeVariable source = (TypeVariable) sourceType;\n return isValidReferenceCast(source.getUpperBound(), targetType);\n }\n if (sourceType instanceof IntersectionType) {\n // source is an intersection type, apply to each member individually\n final IntersectionType source = (IntersectionType) sourceType;\n for (SingleReferenceType type : source.getTypes()) {\n if (!isValidReferenceCast(type, targetType)) {\n return false;\n }\n }\n return true;\n }\n // any other source type is undefined\n return false;\n }\n\n public static boolean haveProvablyDistinctInvocationsInSuperTypes(LiteralReferenceType... types) {\n return haveProvablyDistinctInvocationsInSuperTypes(Arrays.asList(types));\n }\n\n public static boolean haveProvablyDistinctInvocationsInSuperTypes(Collection<LiteralReferenceType> types) {\n return validateInvocationsInSuperTypes(types, ProvablyDistinctFilter.INSTANCE);\n }\n\n public static boolean haveDifferentInvocationsInSuperTypes(LiteralReferenceType... types) {\n return haveDifferentInvocationsInSuperTypes(Arrays.asList(types));\n }\n\n public static boolean haveDifferentInvocationsInSuperTypes(Collection<LiteralReferenceType> types) {\n return validateInvocationsInSuperTypes(types, NotEqualsFilter.<ParametrizedType, ParametrizedType>getInstance());\n }\n\n public static boolean validateInvocationsInSuperTypes(Collection<LiteralReferenceType> types,\n BiPredicate<ParametrizedType, ParametrizedType> test) {\n if (types.size() <= 1) {\n // Fast track trivial cases\n return false;\n }\n // Keep a map of all super types that have the same erasure, excluding non-parametrized types\n final Map<LiteralReferenceType, ParametrizedType> commonErasedSuperTypes = new HashMap<>();\n final Iterator<LiteralReferenceType> iterator = types.iterator();\n // Add all parametrized parents and their erasures for the first type\n for (LiteralReferenceType superType : iterator.next().getSuperTypes()) {\n if (superType instanceof ParametrizedType) {\n commonErasedSuperTypes.put(superType.getErasure(), (ParametrizedType) superType);\n }\n }\n // For the other types, look for an entry in the common set and ensure they have a valid parametrization\n // If not, fail; if so, add to the common set\n do {\n for (LiteralReferenceType superType : iterator.next().getSuperTypes()) {\n if (!(superType instanceof ParametrizedType)) {\n continue;\n }\n final ParametrizedType parametrizedSuperType = (ParametrizedType) superType;\n final LiteralReferenceType erasure = parametrizedSuperType.getErasure();\n final ParametrizedType commonSuperType = commonErasedSuperTypes.get(erasure);\n if (commonSuperType != null) {\n if (test.test(parametrizedSuperType, commonSuperType)) {\n return true;\n }\n } else {\n commonErasedSuperTypes.put(erasure, parametrizedSuperType);\n }\n }\n } while (iterator.hasNext());\n // No conflict found, we're good\n return false;\n }\n\n private static boolean hasInvocationSuperType(LiteralReferenceType type, LiteralReferenceType invocation) {\n // We need an invocation of the same declaration in the super types (that is, same erasures) with the same arguments\n final LiteralReferenceType declaration = invocation.getErasure();\n for (LiteralReferenceType superType : type.getSuperTypes()) {\n if (superType.getErasure().equals(declaration)) {\n return superType.equals(invocation);\n }\n }\n return false;\n }\n\n private interface BiPredicate<S, T> {\n boolean test(S s, T t);\n }\n\n private static class SubTypeFilter implements BiPredicate<Type, Type> {\n private static final SubTypeFilter INSTANCE = new SubTypeFilter();\n\n @Override\n public boolean test(Type left, Type right) {\n return left.convertibleTo(right);\n }\n }\n\n private static class SuperTypeFilter implements BiPredicate<Type, Type> {\n private static final SuperTypeFilter INSTANCE = new SuperTypeFilter();\n\n @Override\n public boolean test(Type left, Type right) {\n return right.convertibleTo(left);\n }\n }\n\n private static class NotEqualsFilter<S, T> implements BiPredicate<S, T> {\n private static final NotEqualsFilter<?, ?> INSTANCE = new NotEqualsFilter<>();\n\n @Override\n public boolean test(S left, T right) {\n return !left.equals(right);\n }\n\n @SuppressWarnings(\"unchecked\")\n private static <S, T> NotEqualsFilter<S, T> getInstance() {\n return (NotEqualsFilter<S, T>) INSTANCE;\n }\n }\n\n private static class ProvablyDistinctFilter implements BiPredicate<ParametrizedType, ParametrizedType> {\n private static final ProvablyDistinctFilter INSTANCE = new ProvablyDistinctFilter();\n\n @Override\n public boolean test(ParametrizedType left, ParametrizedType right) {\n return left.provablyDistinct(right);\n }\n }\n}" ]
import ca.sapon.jici.parser.expression.Expression; import ca.sapon.jici.util.TypeUtil; import ca.sapon.jici.evaluator.Environment; import ca.sapon.jici.evaluator.EvaluatorException; import ca.sapon.jici.evaluator.type.PrimitiveType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.evaluator.value.BooleanValue; import ca.sapon.jici.evaluator.value.Value; import ca.sapon.jici.lexer.Symbol;
/* * This file is part of JICI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package ca.sapon.jici.parser.expression.logic; public class BooleanLogic implements Expression { private final Expression left; private final Expression right;
private final Symbol operator;
6
Kindrat/cassandra-client
src/main/java/com/github/kindrat/cassandra/client/ui/widget/DataExportWidget.java
[ "public interface MessageByLocaleService {\n String getMessage(String id);\n}", "@Value\npublic class CsvTargetMetadata {\n private String table;\n private CSVFormat format;\n private File target;\n}", "@Data\n@ConfigurationProperties(prefix = \"client.ui\")\npublic class UIProperties {\n private Integer aboutBoxHeight = 70;\n private Integer aboutBoxWidth = 300;\n private Integer aboutBoxSpacing = 20;\n\n private Integer newConnectHeight = 175;\n private Integer newConnectWidth = 250;\n private Integer newConnectSpacing = 20;\n\n private Integer credentialsBoxHeight = 93;\n private Integer credentialsBoxSpacing = 20;\n\n private Integer connectionManagerHeight = 400;\n private Integer connectionManagerWidth = 600;\n private Integer connectionManagerRightPaneWidth = 60;\n private Integer connectionManagerButtonWidth = 30;\n private Integer connectionManagerButtonsSpacing = 50;\n\n private Integer tablesPrefHeight = 100;\n private Integer tablesPrefWidth = 250;\n private Double tablesDividerPosition = 0.913;\n\n private Integer tableEditorHeight = 480;\n private Integer tableEditorWidth = 580;\n private Integer tableEditorSpacing = 20;\n\n private Integer exportHeight = 480;\n private Integer exportWidth = 580;\n private Integer exportSpacing = 20;\n}", "public class LabeledComponentColumn extends VBox {\n private final double spacing;\n\n public LabeledComponentColumn(double spacing) {\n this.spacing = spacing;\n setSpacing(spacing);\n }\n\n public void addLabeledElement(String label, Node element) {\n HBox row = new HBox(spacing);\n\n VBox labelColumn = new VBox(spacing);\n labelColumn.setAlignment(Pos.CENTER_LEFT);\n labelColumn.prefWidthProperty().bind(widthProperty().multiply(0.6));\n// UIUtil.setWidth(labelColumn, width * 0.6);\n labelColumn.getChildren().add(new Label(label));\n\n VBox elementColumn = new VBox(spacing);\n elementColumn.setAlignment(Pos.CENTER_LEFT);\n elementColumn.prefWidthProperty().bind(widthProperty().multiply(0.25));\n// UIUtil.setWidth(elementColumn, width * 0.25);\n elementColumn.getChildren().add(element);\n\n row.getChildren().addAll(labelColumn, elementColumn);\n getChildren().add(row);\n }\n}", "@UtilityClass\npublic class UIUtil {\n public static void fillParent(Node node) {\n AnchorPane.setLeftAnchor(node, 0.);\n AnchorPane.setRightAnchor(node, 0.);\n AnchorPane.setTopAnchor(node, 0.);\n AnchorPane.setBottomAnchor(node, 0.);\n }\n\n public static String[] parseWords(String rawString) {\n return StringUtils.split(StringUtils.defaultString(rawString, \"\"));\n }\n\n public static void disable(Node... nodes) {\n for (Node node : nodes) {\n node.setDisable(true);\n }\n }\n\n public static void enable(Node... nodes) {\n for (Node node : nodes) {\n node.setDisable(false);\n }\n }\n\n public static Button buildButton(String text) {\n Button button = new Button(text);\n button.setMnemonicParsing(false);\n button.setMinWidth(USE_PREF_SIZE);\n button.setMaxWidth(USE_PREF_SIZE);\n button.setPrefWidth(30);\n\n button.setMinHeight(USE_PREF_SIZE);\n button.setMaxHeight(USE_PREF_SIZE);\n button.setPrefHeight(25);\n return button;\n }\n\n public static <T extends Region> void setWidth(T node, Number value) {\n setWidth(node, value.doubleValue());\n }\n\n public static <T extends Region> void setWidth(T node, double value) {\n node.setMaxWidth(value);\n node.setMinWidth(value);\n node.setPrefWidth(value);\n }\n\n public static double computeTextContainerWidth(String text, Font font) {\n Text theText = new Text(text);\n theText.setFont(font);\n double width = theText.getBoundsInLocal().getWidth();\n return width * 1.3;\n }\n}", "public static CheckBoxListener create(Runnable onEnabled, Runnable onDisabled) {\n return new CheckBoxListener(onEnabled, onDisabled);\n}", "public static void fillParent(Node node) {\n AnchorPane.setLeftAnchor(node, 0.);\n AnchorPane.setRightAnchor(node, 0.);\n AnchorPane.setTopAnchor(node, 0.);\n AnchorPane.setBottomAnchor(node, 0.);\n}" ]
import com.github.kindrat.cassandra.client.i18n.MessageByLocaleService; import com.github.kindrat.cassandra.client.model.CsvTargetMetadata; import com.github.kindrat.cassandra.client.properties.UIProperties; import com.github.kindrat.cassandra.client.ui.fx.component.LabeledComponentColumn; import com.github.kindrat.cassandra.client.util.UIUtil; import javafx.collections.FXCollections; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.QuoteMode; import org.apache.commons.lang3.StringUtils; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import static com.github.kindrat.cassandra.client.ui.listener.CheckBoxListener.create; import static com.github.kindrat.cassandra.client.util.UIUtil.fillParent;
ComboBox<String> formats = buildFormatBox(200); CheckBox customizeCheckbox = new CheckBox("override format settings"); customizeCheckbox.selectedProperty().addListener(create( () -> { FormatSettingsBox formatSettingsBox = buildFormatSettingsBox(formats); formatSettingsBox.prefWidthProperty().bind(settingsContainer.widthProperty()); settingsContainer.getChildren().add(formatSettingsBox); startButton.setOnAction(event -> { if (customizeCheckbox.isSelected()) { CSVFormat csvFormat = formatSettingsBox.build(); File target = new File(pathField.getText()); metadataProcessor.onNext(new CsvTargetMetadata(table, csvFormat, target)); hide(); } }); }, () -> settingsContainer.getChildren().clear()) ); startButton.setOnAction(event -> { if (!customizeCheckbox.isSelected()) { FormatSettingsBox formatSettingsBox = buildFormatSettingsBox(formats); CSVFormat csvFormat = formatSettingsBox.build(); File target = new File(pathField.getText()); metadataProcessor.onNext(new CsvTargetMetadata(table, csvFormat, target)); hide(); } }); formats.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (!Objects.equals(oldValue, newValue)) { customizeCheckbox.setSelected(!customizeCheckbox.isSelected()); customizeCheckbox.setSelected(!customizeCheckbox.isSelected()); } }); HBox format = new HBox(formatLabel, formats, customizeCheckbox); format.setAlignment(Pos.CENTER); format.setSpacing(properties.getExportSpacing()); pathField.prefWidthProperty().bind(editor.widthProperty().multiply(0.6)); Button destinationButton = new Button("Choose destination"); HBox savePath = new HBox(pathField, destinationButton); savePath.setAlignment(Pos.CENTER); savePath.setSpacing(properties.getExportSpacing()); destinationButton.setOnAction(event -> { FileChooser savePathProvider = new FileChooser(); savePathProvider.setTitle("Save CSV"); savePathProvider.setInitialFileName(table + ".csv"); savePathProvider.setSelectedExtensionFilter(new FileChooser.ExtensionFilter("CSV", "csv")); File file = savePathProvider.showSaveDialog(this); if (file != null) { pathField.setText(file.getAbsolutePath()); } }); editor.getChildren().addAll(format, savePath, settingsContainer, startButton); return new Scene(container, properties.getExportWidth(), properties.getExportHeight()); } private ComboBox<String> buildFormatBox(int width) { ComboBox<String> box = new ComboBox<>(FXCollections.observableList(CSV_FORMATS)); box.getSelectionModel().select(CSVFormat.Predefined.Default.toString()); box.setMinWidth(width - 20); box.setMaxWidth(width - 20); return box; } private FormatSettingsBox buildFormatSettingsBox(ComboBox<String> formatBox) { String selectedFormat = formatBox.getSelectionModel().getSelectedItem(); return new FormatSettingsBox(CSVFormat.valueOf(selectedFormat), properties.getExportSpacing()); } static class FormatSettingsBox extends HBox { private final CSVFormat format; private final TextField delimiter; private final TextField quoteCharacter; private final ComboBox<QuoteMode> quoteModeComboBox; private final TextField commentStart; private final TextField escapeCharacter; private final CheckBox ignoreSurroundingSpaces; private final CheckBox allowMissingColumnNames; private final CheckBox ignoreEmptyLines; private final TextField recordSeparator; private final TextField nullString; private final TextField headerComments; private final TextField headers; private final CheckBox skipHeaderRecord; private final CheckBox ignoreHeaderCase; private final CheckBox trailingDelimiter; private final CheckBox trim; FormatSettingsBox(CSVFormat format, Integer spacing) { this.format = format; delimiter = new TextField(String.valueOf(format.getDelimiter())); quoteCharacter = new TextField(String.valueOf(format.getQuoteCharacter())); quoteModeComboBox = new ComboBox<>(FXCollections.observableList(Arrays.asList(QuoteMode.values()))); quoteModeComboBox.getSelectionModel().select(format.getQuoteMode()); commentStart = new TextField(String.valueOf(format.getCommentMarker())); escapeCharacter = new TextField(String.valueOf(format.getEscapeCharacter())); ignoreSurroundingSpaces = new CheckBox(); ignoreSurroundingSpaces.selectedProperty().setValue(format.getIgnoreSurroundingSpaces()); allowMissingColumnNames = new CheckBox(); allowMissingColumnNames.selectedProperty().setValue(format.getAllowMissingColumnNames()); ignoreEmptyLines = new CheckBox(); ignoreEmptyLines.selectedProperty().setValue(format.getIgnoreEmptyLines()); recordSeparator = new TextField(encloseRecordSeparator(format.getRecordSeparator())); nullString = new TextField(format.getNullString()); headerComments = new TextField(Arrays.toString(format.getHeaderComments())); headers = new TextField(Arrays.toString(format.getHeader())); skipHeaderRecord = new CheckBox(); skipHeaderRecord.selectedProperty().setValue(format.getSkipHeaderRecord()); ignoreHeaderCase = new CheckBox(); ignoreHeaderCase.selectedProperty().setValue(format.getIgnoreHeaderCase()); trailingDelimiter = new CheckBox(); trailingDelimiter.selectedProperty().setValue(format.getTrailingDelimiter()); trim = new CheckBox(); trim.selectedProperty().setValue(format.getTrailingDelimiter());
UIUtil.setWidth(delimiter, 50);
4
Cantara/Java-Auto-Update
src/main/java/no/cantara/jau/coms/CheckForUpdateHelper.java
[ "public class ApplicationProcess {\n private static final Logger log = LoggerFactory.getLogger(ApplicationProcess.class);\n private File workingDirectory;\n private String[] command;\n private Map<String, String> environment;\n private Process runningProcess;\n\n private String clientId;\n private String lastChangedTimestamp;\n private DuplicateProcessHandler duplicateProcessHandler;\n\n public ApplicationProcess(DuplicateProcessHandler duplicateProcessHandler) {\n this.duplicateProcessHandler = duplicateProcessHandler;\n }\n\n public boolean processIsRunning() {\n return runningProcess != null && runningProcess.isAlive();\n }\n\n public void startProcess() {\n ProcessBuilder pb = new ProcessBuilder(command).inheritIO().directory(workingDirectory);\n if (environment != null) {\n pb.environment().putAll(environment);\n }\n\n try {\n runningProcess = pb.start();\n Thread.sleep(1000); // Gives the process time to fail\n if(runningProcess.isAlive()) {\n \tduplicateProcessHandler.findRunningManagedProcessPidAndWriteToFile(runningProcess);\n } else {\n \tlog.warn(\"Failed to start process with command: {}, workingDirectory: {}, clientId: {}, lastChangedTimestamp: {}\", command, workingDirectory, clientId, lastChangedTimestamp);\n }\n } catch (IOException e) {\n throw new RuntimeException(\"IOException while trying to start process with command '\" + String.join(\" \", command) + \"' from directory '\" + workingDirectory + \"'.\", e);\n } catch (InterruptedException e) {\n\t\t\tlog.warn(\"Not allowed to sleep for 1 second\", e);\n\t\t}\n }\n\n public void stopProcess() {\n log.debug(\"Destroying running process\");\n if (!processIsRunning()) {\n log.debug(\"Tried to stop process, but no process was running.\");\n return;\n }\n runningProcess.destroy();\n try {\n runningProcess.waitFor();\n log.debug(\"Successfully destroyed running process\");\n } catch (InterruptedException e) {\n log.debug(\"Interrupted while waiting for process to shut down.\", e);\n }\n }\n\n public void setWorkingDirectory(File workingDirectory) {\n this.workingDirectory = workingDirectory;\n }\n public void setCommand(String[] command) {\n this.command = command;\n }\n public void setEnvironment(Map<String, String> environment) {\n this.environment = environment;\n }\n public void setClientId(String clientId) {\n this.clientId = clientId;\n }\n public void setLastChangedTimestamp(String lastChangedTimestamp) {\n this.lastChangedTimestamp = lastChangedTimestamp;\n }\n\n public File getWorkingDirectory() {\n return workingDirectory;\n }\n public String[] getCommand() {\n return command;\n }\n public String getClientId() {\n return clientId;\n }\n public String getLastChangedTimestamp() {\n return lastChangedTimestamp;\n }\n}", "public class JavaAutoUpdater {\n\n private static final Logger log = LoggerFactory.getLogger(JavaAutoUpdater.class);\n\n private static ScheduledFuture<?> processMonitorHandle;\n private static ScheduledFuture<?> updaterHandle;\n\n private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();\n private final ConfigServiceClient configServiceClient;\n private final ApplicationProcess processHolder;\n private final DuplicateProcessHandler duplicateProcessHandler;\n private final EventExtractorService extractorService;\n\n private RegisterClientHelper registerClientHelper;\n\n public JavaAutoUpdater(ConfigServiceClient configServiceClient, RegisterClientHelper registerClientHelper,\n ApplicationProcess applicationProcess, DuplicateProcessHandler duplicateProcessHandler,\n EventExtractorService extractorService) {\n this.configServiceClient = configServiceClient;\n this.registerClientHelper = registerClientHelper;\n this.processHolder = applicationProcess;\n this.duplicateProcessHandler = duplicateProcessHandler;\n this.extractorService = extractorService;\n\n addShutdownHook();\n }\n\n /**\n * Registers a shutdown hook that attempts to stop the application process when JAU is stopped.\n */\n private void addShutdownHook() {\n if (PropertiesHelper.stopApplicationOnShutdown()) {\n Runtime.getRuntime().addShutdownHook(new Thread() {\n @Override\n public void run() {\n processHolder.stopProcess();\n }\n });\n log.info(\"Registered shutdown hook for stopping application.\");\n }\n }\n\n /**\n * registerClient\n * checkForUpdate\n * if changed\n * Download\n * Stop existing service if running\n * Start new service\n */\n public void start(int updateInterval, int isRunningInterval) {\n // registerClient or fetch applicationState from file\n if (configServiceClient.getApplicationState() == null) {\n ClientConfig clientConfig = registerClient();\n storeClientFiles(clientConfig);\n } else {\n log.debug(\"Client already registered. Skip registerClient and use properties from file.\");\n }\n\n Properties initialApplicationState = configServiceClient.getApplicationState();\n initializeProcessHolder(initialApplicationState);\n extractorService.updateConfigs(configServiceClient.getEventExtractionConfigs());\n\n // checkForUpdate and start process\n while (true) {\n int sleepTime = 10000;\n if (updaterHandle == null || updaterHandle.isCancelled() || updaterHandle.isDone()) {\n updaterHandle = startUpdaterThread(updateInterval);\n }\n\n if (processMonitorHandle == null || processMonitorHandle.isCancelled() || processMonitorHandle.isDone()) {\n String processCommand = configServiceClient.getApplicationState().getProperty(\"command\");\n boolean successKillingProcess = duplicateProcessHandler.killExistingProcessIfRunning(processCommand);\n\n if (!successKillingProcess) {\n boolean forceStartSubProcess = PropertiesHelper.forceStartSubProcess();\n if (forceStartSubProcess) {\n log.warn(\"Problem killing running process. Will start a new managed process as the \" +\n \"flag 'forceStartSubProcess' is set to true. This may lead to duplicate \" +\n \"subprocesses.\");\n } else {\n log.error(\"Problem killing running process! A new managed process will not be started. \" +\n \"Retrying in {} seconds\", sleepTime / 1000);\n }\n } else {\n processMonitorHandle = startProcessMonitorThread(isRunningInterval);\n }\n }\n\n // make sure everything runs, forever\n try {\n Thread.sleep(sleepTime);\n } catch (InterruptedException e) {\n log.warn(\"Thread was interrupted\", e);\n }\n }\n }\n\n private ScheduledFuture<?> startProcessMonitorThread(long interval) {\n log.debug(\"Starting process monitoring scheduler with an update interval of {} seconds.\", interval);\n return scheduler.scheduleAtFixedRate(\n () -> {\n log.debug(\"Checking if process is running...\");\n\n // Restart, whatever the reason the process is not running.\n if (!processHolder.processIsRunning()) {\n log.debug(\"Process is not running - restarting... clientId={}, lastChanged={}, command={}\",\n processHolder.getClientId(), processHolder.getLastChangedTimestamp(), processHolder.getCommand());\n\n processHolder.startProcess();\n }\n },\n 1, interval, SECONDS\n );\n }\n\n private ScheduledFuture<?> startUpdaterThread(long interval) {\n log.debug(\"Starting update scheduler with an update interval of {} seconds.\", interval);\n return scheduler.scheduleWithFixedDelay(\n CheckForUpdateHelper.getCheckForUpdateRunnable(interval, configServiceClient, processHolder,\n processMonitorHandle, extractorService, this),\n 1, interval, SECONDS\n );\n }\n\n public ClientConfig registerClient() {\n return registerClientHelper.registerClient();\n }\n\n public void storeClientFiles(ClientConfig clientConfig) {\n String workingDirectory = processHolder.getWorkingDirectory().getAbsolutePath();\n ApplicationConfig config = clientConfig.config;\n DownloadUtil.downloadAllFiles(config.getDownloadItems(), workingDirectory);\n ConfigurationStoreUtil.toFiles(config.getConfigurationStores(), workingDirectory);\n extractorService.updateConfigs(config.getEventExtractionConfigs());\n }\n\n private void initializeProcessHolder(Properties initialApplicationState) {\n String initialClientId = PropertiesHelper.getStringProperty(initialApplicationState, ConfigServiceClient.CLIENT_ID, null);\n String initialLastChanged = PropertiesHelper.getStringProperty(initialApplicationState, ConfigServiceClient.LAST_CHANGED, null);\n String initialCommand = PropertiesHelper.getStringProperty(initialApplicationState, ConfigServiceClient.COMMAND, null);\n Properties environment = PropertiesHelper.getPropertiesFromConfigFile(PropertiesHelper.APPLICATION_ENV_FILENAME);\n\n processHolder.setCommand(initialCommand.split(\"\\\\s+\"));\n processHolder.setClientId(initialClientId);\n processHolder.setLastChangedTimestamp(initialLastChanged);\n processHolder.setEnvironment(PropertiesHelper.propertiesAsMap(environment));\n }\n\n}", "public class EventExtractorService {\n private static final Logger log = LoggerFactory.getLogger(EventExtractorService.class);\n private final EventRepo repo;\n private final String startPattern;\n private List<EventExtractor> eventExtractors = Collections.emptyList();\n private final ExecutorService executor;\n\n public EventExtractorService(EventRepo repo, String startPattern) {\n this.repo = repo;\n this.startPattern = startPattern;\n this.executor = Executors.newCachedThreadPool();\n }\n\n public void updateConfigs(List<EventExtractionConfig> configs) {\n createEventExtractors(configs);\n }\n\n private List<Future<String>> runEventExtractors() {\n try {\n return executor.invokeAll(eventExtractors);\n } catch (InterruptedException e) {\n log.error(\"Execution of EventExtractor was interrupted!\", e);\n }\n return null;\n }\n\n private void createEventExtractors(List<EventExtractionConfig> configs) {\n log.info(configs.toString());\n eventExtractors = new ArrayList<>();\n for (EventExtractionConfig config : configs) {\n Map<String, List<EventExtractionTag>> tagsByFile = EventExtractionUtil\n .groupExtractionConfigsByFile(config);\n\n for (String filePath : tagsByFile.keySet()) {\n List<EventExtractionTag> eventExtractionTags = tagsByFile.get(filePath);\n EventExtractor extractor = new EventExtractor(repo, eventExtractionTags, filePath, config.groupName, startPattern);\n eventExtractors.add(extractor);\n }\n }\n log.debug(\"Created {} EventExtractors\", eventExtractors.size());\n }\n\n public List<Event> extractEvents() {\n log.debug(\"Extracting events.\");\n runEventExtractors();\n return repo.getEvents();\n }\n\n public void clearRepo() {\n repo.clearEvents();\n }\n}", "public class ClientEnvironmentUtil {\n private static final Logger log = LoggerFactory.getLogger(ClientEnvironmentUtil.class);\n public static final String NETWORKINTERFACE = \"networkinterface_\";\n\n public static SortedMap<String, String> getClientEnvironment(Properties applicationState, String processIsRunning) {\n SortedMap<String, String> clientEnv = new TreeMap<>();\n\n try {\n Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();\n while (nics.hasMoreElements()) {\n NetworkInterface nic = nics.nextElement();\n for (InterfaceAddress interfaceAddress : nic.getInterfaceAddresses()) {\n InetAddress address = interfaceAddress.getAddress();\n if (address.isLoopbackAddress()) {\n continue;\n }\n\n if (address.isSiteLocalAddress()) {\n clientEnv.put(NETWORKINTERFACE + nic.getName(), address.getHostAddress());\n }\n }\n }\n } catch (SocketException e) {\n log.warn(\"getNetworkInterfaces failed. Networkinterface addresses will not be availble.\");\n }\n\n // We mask environment variables that are defined in appliction-env.properties, the assumption is that these are\n // sensitive and we do want to send them as heartbeat data\n Set<String> propertiesToMask = PropertiesHelper.getPropertiesFromConfigFile(PropertiesHelper.APPLICATION_ENV_FILENAME).stringPropertyNames();\n clientEnv.putAll(maskApplicationEnvProperties(System.getenv(), propertiesToMask));\n Map<String, String> mapProperties = new HashMap<String, String>();\n Properties systemProperties = System.getProperties();\n for(Entry<Object, Object> x : systemProperties.entrySet()) {\n mapProperties.put((String)x.getKey(), (String)x.getValue());\n }\n clientEnv.putAll(maskApplicationEnvProperties(mapProperties, propertiesToMask));\n String version = PropertiesHelper.getVersion();\n clientEnv.put(\"jau.version\", version);\n clientEnv.put(\"applicationState\", String.valueOf(applicationState));\n clientEnv.put(\"processIsRunning\", processIsRunning);\n clientEnv.put(\"processIsRunning timestamp\", new Date().toString());\n return clientEnv;\n }\n\n public static SortedMap<String, String> getClientEnvironment() {\n return getClientEnvironment(new Properties(), \"information not available\");\n }\n\n static Map<String, String> maskApplicationEnvProperties(Map<String, String> environmentVariables, Set<String> variablesToMask) {\n HashMap<String, String> masked = new HashMap<>();\n for (String variableKey : environmentVariables.keySet()) {\n if (variablesToMask.contains(variableKey)) {\n masked.put(variableKey, maskEnvironmentVariable(environmentVariables.get(variableKey)));\n } else {\n masked.put(variableKey, environmentVariables.get(variableKey));\n }\n }\n return masked;\n }\n\n private static String maskEnvironmentVariable(String variableValue) {\n if (variableValue == null || variableValue.length() < 5) {\n // We assume short variable values are not sensitive\n return variableValue;\n }\n return variableValue.substring(0, 2) + \"...\" + variableValue.substring(variableValue.length() - 2, variableValue.length());\n }\n}", "public class PropertiesHelper {\n\n private static final Logger log = LoggerFactory.getLogger(PropertiesHelper.class);\n\n public static final String CONFIG_SERVICE_URL_KEY = \"configservice.url\";\n public static final String CLIENT_NAME_PROPERTY_DEFAULT_VALUE = \"Default clientName\";\n public static final String JAU_CONFIG_FILENAME = \"jau.properties\";\n public static final String APPLICATION_ENV_FILENAME = \"application-env.properties\";\n public static final String VERSION_FILENAME = \"version.properties\";\n\n private static final String CLIENT_NAME_PROPERTY_KEY = \"clientName\";\n private static final String CLIENT_ID_PROPERTY_KEY = \"configservice.clientid\";\n private static final String ARTIFACT_ID = \"configservice.artifactid\";\n private static final String CONFIG_SERVICE_USERNAME_KEY = \"configservice.username\";\n private static final String CONFIG_SERVICE_PASSWORD_KEY = \"configservice.password\";\n private static final String START_PATTERN_PROPERTY_KEY = \"startPattern\";\n private static final String VERSION_PROPERTY_KEY = \"jau.version\";\n private static final String IS_RUNNING_INTERVAL_KEY = \"isrunninginterval\";\n private static final String UPDATE_INTERVAL_KEY = \"updateinterval\";\n private static final String STOP_APPLICATION_ON_SHUTDOWN_KEY = \"stopApplicationOnShutdown\";\n private static final String FORCE_START_SUB_PROCESS = \"forceStartSubProcess\";\n\n private static final int DEFAULT_UPDATE_INTERVAL = 60; // seconds\n private static final int DEFAULT_IS_RUNNING_INTERVAL = 40; // seconds\n private static final boolean DEFAULT_STOP_APPLICATION_ON_SHUTDOWN = false;\n private static final boolean DEFAULT_FORCE_START_SUB_PROCESS = false;\n\n public static Properties getPropertiesFromConfigFile(String filename) {\n Properties properties = new Properties();\n try {\n properties.load(PropertiesHelper.class.getClassLoader().getResourceAsStream(filename));\n } catch (NullPointerException | IOException e) {\n log.debug(\"{} not found on classpath.\", filename);\n }\n return properties;\n }\n\n public static Properties loadProperties(File file) {\n Properties properties = new Properties();\n if (file.exists()) {\n try (InputStream input = new FileInputStream(file)) {\n properties.load(input);\n } catch (Exception e) {\n log.warn(\"Failed to load properties from {}\", file, e);\n }\n }\n return properties;\n }\n\n public static boolean saveProperties(Properties properties, File file) {\n try (OutputStream output = new FileOutputStream(file)) {\n properties.store(output, null);\n return true;\n } catch (Exception e) {\n log.warn(\"Failed to save properties to {}\", file, e);\n return false;\n }\n }\n\n public static String getStringProperty(final Properties properties, String propertyKey, String defaultValue) {\n String property = System.getProperty(propertyKey);\n if (property == null) {\n property = AppConfig.getString(propertyKey);\n }\n if (property == null) {\n property = properties.getProperty(propertyKey, defaultValue);\n }\n return property;\n }\n\n public static Integer getIntProperty(final Properties properties, String propertyKey, Integer defaultValue) {\n String property = getStringProperty(properties, propertyKey, null);\n if (property == null) {\n return defaultValue;\n }\n return Integer.valueOf(property);\n }\n\n public static Long getLongProperty(final Properties properties, String propertyKey, Long defaultValue) {\n String property = getStringProperty(properties, propertyKey, null);\n if (property == null) {\n return defaultValue;\n }\n return Long.valueOf(property);\n }\n\n public static void setLongProperty(Properties properties, String propertyKey, long value) {\n properties.setProperty(propertyKey, String.valueOf(value));\n }\n\n public static Boolean getBooleanProperty(final Properties properties, String propertyKey, Boolean defaultValue) {\n String property = getStringProperty(properties, propertyKey, null);\n if (property == null) {\n return defaultValue;\n }\n return Boolean.valueOf(property);\n }\n\n public static Map<String, String> propertiesAsMap(Properties properties) {\n Map<String, String> map = new LinkedHashMap<>();\n properties.forEach((key, value) -> map.put(String.valueOf(key), String.valueOf(value)));\n return map;\n }\n\n public static String getClientId() {\n return getStringProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), CLIENT_ID_PROPERTY_KEY, null);\n }\n\n public static String getClientName() {\n return getStringProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), CLIENT_NAME_PROPERTY_KEY, CLIENT_NAME_PROPERTY_DEFAULT_VALUE);\n }\n\n public static String getArtifactId() {\n return getStringProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), ARTIFACT_ID, null);\n }\n\n public static String getConfigServiceUrl() {\n return getStringProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), CONFIG_SERVICE_URL_KEY, null);\n }\n\n public static String getUsername() {\n return getStringProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), CONFIG_SERVICE_USERNAME_KEY, null);\n }\n\n public static String getPassword() {\n return getStringProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), CONFIG_SERVICE_PASSWORD_KEY, null);\n }\n\n public static int getUpdateInterval() {\n return getIntProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), UPDATE_INTERVAL_KEY, DEFAULT_UPDATE_INTERVAL);\n }\n\n public static int getIsRunningInterval() {\n return getIntProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), IS_RUNNING_INTERVAL_KEY, DEFAULT_IS_RUNNING_INTERVAL);\n }\n\n public static String getVersion() {\n return getStringProperty(getPropertiesFromConfigFile(VERSION_FILENAME), VERSION_PROPERTY_KEY, null);\n }\n\n public static String getStartPattern() {\n return getStringProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), START_PATTERN_PROPERTY_KEY, null);\n }\n\n public static boolean stopApplicationOnShutdown() {\n return getBooleanProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), STOP_APPLICATION_ON_SHUTDOWN_KEY, DEFAULT_STOP_APPLICATION_ON_SHUTDOWN);\n }\n\n public static boolean forceStartSubProcess() {\n return getBooleanProperty(getPropertiesFromConfigFile(JAU_CONFIG_FILENAME), FORCE_START_SUB_PROCESS, DEFAULT_FORCE_START_SUB_PROCESS);\n }\n}" ]
import no.cantara.cs.client.ConfigServiceClient; import no.cantara.cs.client.EventExtractionUtil; import no.cantara.cs.client.HttpException; import no.cantara.cs.dto.CheckForUpdateRequest; import no.cantara.cs.dto.ClientConfig; import no.cantara.cs.dto.event.Event; import no.cantara.cs.dto.event.ExtractedEventsStore; import no.cantara.jau.ApplicationProcess; import no.cantara.jau.JavaAutoUpdater; import no.cantara.jau.eventextraction.EventExtractorService; import no.cantara.jau.util.ClientEnvironmentUtil; import no.cantara.jau.util.PropertiesHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.List; import java.util.Properties; import java.util.SortedMap; import java.util.concurrent.ScheduledFuture;
package no.cantara.jau.coms; /** * Created by jorunfa on 29/10/15. */ public class CheckForUpdateHelper { private static final Logger log = LoggerFactory.getLogger(CheckForUpdateHelper.class); public static Runnable getCheckForUpdateRunnable(long interval, ConfigServiceClient configServiceClient, ApplicationProcess processHolder, ScheduledFuture<?> processMonitorHandle, EventExtractorService extractorService,
JavaAutoUpdater jau
1
bitkylin/BitkyShop
Android/bitkyShop/app/src/main/java/cc/bitky/bitkyshop/fragment/userfragment/loginfragment/SignupActivity.java
[ "public class KyUser extends BmobUser {\n private String pwdResumeQuestion;\n private String pwdResumeAnswer;\n private Boolean haveDetailInfo;\n\n public Boolean getHaveDetailInfo() {\n return haveDetailInfo;\n }\n\n public void setHaveDetailInfo(Boolean haveDetailInfo) {\n this.haveDetailInfo = haveDetailInfo;\n }\n\n public String getPwdResumeQuestion() {\n return pwdResumeQuestion;\n }\n\n public void setPwdResumeQuestion(String pwdResumeQuestion) {\n this.pwdResumeQuestion = pwdResumeQuestion;\n }\n\n public String getPwdResumeAnswer() {\n return pwdResumeAnswer;\n }\n\n public void setPwdResumeAnswer(String pwdResumeAnswer) {\n this.pwdResumeAnswer = pwdResumeAnswer;\n }\n}", "public class KyToolBar extends Toolbar {\n private TextView textView;\n private View view;\n private ImageView kyNavigation;\n private ImageView rightButton;\n private TextView rightTextView;\n private TextView placeHolderTextView;\n private EditText editText;\n private OnSearchListener onSearchListener;\n\n public KyToolBar(Context context) {\n this(context, null);\n }\n\n public KyToolBar(Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public KyToolBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n\n initView();\n final TintTypedArray a =\n TintTypedArray.obtainStyledAttributes(getContext(), attrs, R.styleable.KyToolbar,\n defStyleAttr, 0);\n final boolean enableKyNavigationIcon =\n a.getBoolean(R.styleable.KyToolbar_enableKyNavigationIcon, true);\n final boolean enableKySearch = a.getBoolean(R.styleable.KyToolbar_enableKySearch, false);\n final Drawable navIcon = a.getDrawable(R.styleable.KyToolbar_KyNavigationIcon);\n final Drawable rightButtonIcon = a.getDrawable(R.styleable.KyToolbar_setRightButton);\n final String rightText = a.getString(R.styleable.KyToolbar_setRightText);\n\n setNavigationIcon(navIcon);\n setRightButtonIcon(rightButtonIcon);\n enableKyNavigation(enableKyNavigationIcon);\n setRightTextView(rightText);\n setEnabledSearch(enableKySearch);\n a.recycle();\n }\n\n private void initView() {\n LayoutInflater inflater = LayoutInflater.from(getContext());\n view = inflater.inflate(R.layout.widget_ky_toolbar, this, true);\n textView = (TextView) view.findViewById(R.id.kytoolbar_title);\n editText = (EditText) view.findViewById(R.id.kytoolbar_editText);\n kyNavigation = (ImageView) view.findViewById(R.id.kytoolbar_navigation);\n rightButton = (ImageView) view.findViewById(R.id.kytoolbar_rightButton);\n rightTextView = (TextView) view.findViewById(R.id.kytoolbar_rightTextView);\n placeHolderTextView = (TextView) view.findViewById(R.id.kytoolbar_placeholder);\n }\n\n @Override public void setNavigationOnClickListener(OnClickListener listener) {\n kyNavigation.setOnClickListener(listener);\n }\n\n public void setRightButtonOnClickListener(OnClickListener listener) {\n rightButton.setOnClickListener(listener);\n }\n\n public void setRightTextViewOnClickListener(OnClickListener listener) {\n rightTextView.setOnClickListener(listener);\n }\n\n /**\n * 是否启用kyNavigation\n *\n * @param enableKyNavigationIcon kyNavigation\n */\n private void enableKyNavigation(boolean enableKyNavigationIcon) {\n if (enableKyNavigationIcon) {\n kyNavigation.setVisibility(VISIBLE);\n } else {\n kyNavigation.setVisibility(INVISIBLE);\n }\n }\n\n /**\n * 是否启用 rightButton\n *\n * @param enableRightButton kyNavigation\n */\n private void enableRightButton(boolean enableRightButton) {\n if (enableRightButton) {\n rightButton.setVisibility(VISIBLE);\n } else {\n rightButton.setVisibility(GONE);\n }\n }\n\n /**\n * 是否启用 RightTextView\n *\n * @param enableRightTextView enableRightTextView\n */\n private void enableRightTextView(boolean enableRightTextView) {\n if (enableRightTextView) {\n rightTextView.setVisibility(VISIBLE);\n } else {\n rightTextView.setVisibility(GONE);\n }\n }\n\n /**\n * 设置 navigation 的图标\n *\n * @param icon 图标\n */\n @Override public void setNavigationIcon(@Nullable Drawable icon) {\n if (icon != null) {\n kyNavigation.setImageDrawable(icon);\n enableKyNavigation(true);\n }\n }\n\n /**\n * 设置 RightButton 的图标\n *\n * @param icon 图标\n */\n private void setRightButtonIcon(@Nullable Drawable icon) {\n if (icon != null) {\n rightButton.setImageDrawable(icon);\n enableRightButton(true);\n placeHolderTextView.setVisibility(GONE);\n }\n }\n\n /**\n * 设置 RightTextView 启用\n *\n * @param str 显示的文字\n */\n private void setRightTextView(@Nullable String str) {\n if (str != null) {\n rightTextView.setText(str);\n enableRightTextView(true);\n placeHolderTextView.setVisibility(GONE);\n }\n }\n\n @Override public void setTitle(CharSequence title) {\n super.setTitle(title);\n if (view == null) initView();\n textView.setText(title);\n }\n\n /**\n * 设置是否启用搜索\n */\n public void setEnabledSearch(boolean enabledSearch) {\n if (enabledSearch) {\n textView.setVisibility(GONE);\n editText.setVisibility(VISIBLE);\n editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH && onSearchListener != null) {\n onSearchListener.searchListener(editText.getText().toString().trim());\n return true;\n }\n return false;\n }\n });\n }\n }\n\n public void setOnSearchListener(OnSearchListener onSearchListener) {\n this.onSearchListener = onSearchListener;\n }\n\n public interface OnSearchListener {\n void searchListener(String msg);\n }\n}", "public class ToastUtil {\n private Context mContext;\n private SuperToast mSuperToast;\n int i = 1;\n String msg = \"\";\n\n public ToastUtil(Context context) {\n this(context, null);\n }\n\n public ToastUtil(Context context, Type type) {\n mContext = context;\n if (type == null) assignFlyBlue();\n if (type == Type.FlyBlue) assignFlyBlue();\n }\n\n public ToastUtil assignFlyBlue() {\n if (mSuperToast == null) {\n mSuperToast = SuperActivityToast.create(mContext, new Style(), Style.TYPE_STANDARD)\n .setText(\"New BitkyToast\");\n mSuperToast.setDuration(Style.DURATION_VERY_SHORT)\n .setFrame(Style.FRAME_STANDARD)\n .setAnimations(Style.ANIMATIONS_FLY)\n .setColor(0xcc1e90ff);\n }\n return this;\n }\n\n public void show(String msg) {\n if (mSuperToast == null) {\n KLog.w(\"对象未实例化\");\n } else {\n if (!this.msg.equals(msg)) {\n this.msg = msg;\n mSuperToast.setText(msg).show();\n } else if (!mSuperToast.isShowing()) {\n mSuperToast.setText(msg).show();\n }\n }\n }\n\n enum Type {\n FlyBlue\n }\n}", "public class KyPattern {\n /**\n * 验证手机号码\n *\n * @param phoneNumber 手机号码\n * @return boolean\n */\n public static boolean checkPhoneNumber(String phoneNumber) {\n Pattern pattern = Pattern.compile(\"^1[0-9]{10}$\");\n Matcher matcher = pattern.matcher(phoneNumber);\n return matcher.matches();\n }\n\n /**\n * 验证数字字母和中文字符\n *\n * @param phoneNumber 用户名\n * @return boolean\n */\n public static boolean checkUserName(String phoneNumber) {\n Pattern pattern = Pattern.compile(\"([a-zA-Z0-9\\\\u4e00-\\\\u9fa5]{2,24})\");\n Matcher matcher = pattern.matcher(phoneNumber);\n return matcher.matches();\n }\n\n /**\n * 验证数字字母\n *\n * @param phoneNumber 密码\n * @return boolean\n */\n public static boolean checkNumStr(String phoneNumber) {\n Pattern pattern = Pattern.compile(\"([a-zA-Z0-9]{2,24})\");\n Matcher matcher = pattern.matcher(phoneNumber);\n return matcher.matches();\n }\n}", "public class KySet {\n //请求\n public static final int USER_REQUEST_SIGN_UP = 11;\n public static final int USER_REQUEST_LOG_IN = 12;\n public static final int CART_REQUEST_SUBMIT_ORDER = 13;\n public static final int USER_REQUEST_CREATE_ADDRESS = 14;\n public static final int CART_REQUEST_SELECT_RECEIVE_ADDRESS = 15;\n public static final int USER_REQUEST_HISTORY_ORDER = 16;\n public static final int USER_REQUEST_PHONE_SIGNUP_OR_LOGIN = 18;\n\n //返回结果\n public static final int USER_RESULT_SIGN_UP = 21;\n public static final int USER_RESULT_LOG_IN = 22;\n public static final int CART_RESULT_SUBMIT_ORDER = 23;\n public static final int USER_RESULT_CREATE_ADDRESS = 24;\n public static final int CART_RESULT_SELECT_RECEIVE_ADDRESS = 25;\n public static final int USER_RESULT_REFRESH_ORDER = 27;\n public static final int USER_RESULT_PHONE_SIGNUP_OR_LOGIN = 28;\n\n public static final int RESULT_ERROR = -21;\n}" ]
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import cc.bitky.bitkyshop.R; import cc.bitky.bitkyshop.bean.cart.KyUser; import cc.bitky.bitkyshop.utils.KyToolBar; import cc.bitky.bitkyshop.utils.ToastUtil; import cc.bitky.bitkyshop.utils.tools.KyPattern; import cc.bitky.bitkyshop.utils.tools.KySet; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener; import rx.Subscriber;
package cc.bitky.bitkyshop.fragment.userfragment.loginfragment; public class SignupActivity extends AppCompatActivity implements View.OnClickListener { ToastUtil toastUtil; private EditText confirmPwd; private EditText inputPwd; private EditText pwdResumeAnswer; private EditText pwdResumeQuestion; private EditText userName; private String userNameStr; private String inputPwdStr; private String confirmPwdStr; private String pwdResumeQuestionStr; private String pwdResumeAnswerStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); toastUtil = new ToastUtil(this); KyToolBar kyToolBar = (KyToolBar) findViewById(R.id.signupActivity_toolbar); kyToolBar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); userName = (EditText) findViewById(R.id.signupActivity_editText_userName); inputPwd = (EditText) findViewById(R.id.signupActivity_editText_inputPwd); confirmPwd = (EditText) findViewById(R.id.signupActivity_editText_confirmPwd); pwdResumeQuestion = (EditText) findViewById(R.id.signupActivity_editText_pwdResumeQuestion); pwdResumeAnswer = (EditText) findViewById(R.id.signupActivity_editText_pwdResumeAnswer); Button btnSignup = (Button) findViewById(R.id.signupActivity_btn_signup); btnSignup.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.signupActivity_btn_signup: userNameStr = userName.getText().toString().trim(); inputPwdStr = inputPwd.getText().toString().trim(); confirmPwdStr = confirmPwd.getText().toString().trim(); pwdResumeQuestionStr = pwdResumeQuestion.getText().toString().trim(); pwdResumeAnswerStr = pwdResumeQuestion.getText().toString().trim(); //验证是否填写完整 if (userNameStr.length() == 0 || inputPwdStr.length() == 0 || confirmPwdStr.length() == 0 || pwdResumeQuestionStr.length() == 0 || pwdResumeAnswerStr.length() == 0) { toastUtil.show("请将上面的编辑框填写完整"); break; } //验证密码是否一致 if (!inputPwdStr.equals(confirmPwdStr)) { toastUtil.show("密码框中的密码不一致,请重新输入"); inputPwd.setText(""); confirmPwd.setText(""); break; } //验证语法规则
if (!KyPattern.checkUserName(userNameStr)) {
3
cdancy/artifactory-rest
src/test/java/com/cdancy/artifactory/rest/features/StorageApiMockTest.java
[ "public static void assertFalse(boolean value) {\n assertThat(value).isFalse();\n}", "public static void assertNotNull(Object value) {\n assertThat(value).isNotNull();\n}", "public static void assertNull(Object value) {\n assertThat(value).isNull();\n}", "public static void assertTrue(boolean value) {\n assertThat(value).isTrue();\n}", "@AutoValue\npublic abstract class Artifact {\n\n public abstract String uri();\n\n @Nullable\n public abstract String downloadUri();\n\n @Nullable\n public abstract String repo();\n\n @Nullable\n public abstract String path();\n\n @Nullable\n public abstract String remoteUrl();\n\n @Nullable\n public abstract String created();\n\n @Nullable\n public abstract String createdBy();\n\n public abstract String size();\n\n @Nullable\n public abstract String lastModified();\n\n @Nullable\n public abstract String modifiedBy();\n\n @Nullable\n public abstract String folder();\n\n @Nullable\n public abstract String mimeType();\n\n @Nullable\n public abstract CheckSum checksums();\n\n @Nullable\n public abstract CheckSum originalChecksums();\n\n Artifact() {\n }\n\n @SerializedNames({ \"uri\", \"downloadUri\", \"repo\", \"path\", \"remoteUrl\", \"created\", \"createdBy\",\n \"size\", \"lastModified\", \"modifiedBy\", \"folder\", \"mimeType\", \"checksums\", \"originalChecksums\" })\n public static Artifact create(String uri, String downloadUri, String repo,\n String path, String remoteUrl, String created, String createdBy,\n String size, String lastModified, String modifiedBy, String folder,\n String mimeType, CheckSum checksums, CheckSum originalChecksums) {\n return new AutoValue_Artifact(uri, downloadUri, repo, path, remoteUrl,\n created, createdBy, size, lastModified, modifiedBy,\n folder, mimeType, checksums, originalChecksums);\n }\n}", "@AutoValue\npublic abstract class FileList {\n\n public abstract String uri();\n\n public abstract String created();\n\n public abstract List<Artifact> files();\n\n FileList() {\n }\n\n @SerializedNames({ \"uri\", \"created\", \"files\" })\n public static FileList create(String uri, String created, List<Artifact> files) {\n return new AutoValue_FileList(uri, created,\n files != null ? ImmutableList.copyOf(files) : ImmutableList.<Artifact> of());\n }\n}", "@AutoValue\npublic abstract class StorageInfo {\n\n public abstract BinariesSummary binariesSummary();\n\n public abstract FileStoreSummary fileStoreSummary();\n\n public abstract List<RepositorySummary> repositoriesSummaryList();\n\n StorageInfo() {\n }\n\n @SerializedNames({ \"binariesSummary\", \"fileStoreSummary\", \"repositoriesSummaryList\" })\n public static StorageInfo create(BinariesSummary binariesSummary, FileStoreSummary fileStoreSummary, List<RepositorySummary> repositoriesSummaryList) {\n return new AutoValue_StorageInfo(binariesSummary, fileStoreSummary,\n repositoriesSummaryList != null ? ImmutableList.copyOf(repositoriesSummaryList) : ImmutableList.<RepositorySummary> of());\n }\n}", "public interface ArtifactoryApi extends Closeable {\n\n @Delegate\n ArtifactApi artifactApi();\n\n @Delegate\n BuildApi buildApi();\n\n @Delegate\n DockerApi dockerApi();\n\n @Delegate\n RepositoryApi respositoryApi();\n\n @Delegate\n SearchApi searchApi();\n\n @Delegate\n StorageApi storageApi();\n\n @Delegate\n SystemApi systemApi();\n}", "public class BaseArtifactoryMockTest {\n\n protected String provider;\n\n public BaseArtifactoryMockTest() {\n provider = \"artifactory\";\n }\n\n public ArtifactoryApi api(URL url) {\n final ArtifactoryAuthentication creds = ArtifactoryAuthentication\n .builder()\n .credentials(\"hello:world\")\n .build();\n final ArtifactoryAuthenticationModule credsModule = new ArtifactoryAuthenticationModule(creds);\n return ContextBuilder.newBuilder(provider)\n .endpoint(url.toString())\n .overrides(setupProperties())\n .modules(Lists.newArrayList(credsModule))\n .buildApi(ArtifactoryApi.class);\n }\n\n protected Properties setupProperties() {\n Properties properties = new Properties();\n properties.setProperty(Constants.PROPERTY_MAX_RETRIES, \"0\");\n return properties;\n }\n\n public static MockWebServer mockArtifactoryJavaWebServer() throws IOException {\n MockWebServer server = new MockWebServer();\n server.start();\n return server;\n }\n\n public String randomString() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n }\n\n public String payloadFromResource(String resource) {\n try {\n return new String(toStringAndClose(getClass().getResourceAsStream(resource)).getBytes(Charsets.UTF_8));\n } catch (IOException e) {\n throw Throwables.propagate(e);\n }\n }\n\n protected RecordedRequest assertSent(MockWebServer server, String method, String path, String mediaType) throws InterruptedException {\n RecordedRequest request = server.takeRequest();\n assertThat(request.getMethod()).isEqualTo(method);\n assertThat(request.getPath()).isEqualTo(path);\n assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(mediaType);\n return request;\n }\n}" ]
import com.squareup.okhttp.mockwebserver.MockWebServer; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.cdancy.artifactory.rest.TestUtilities.assertFalse; import static com.cdancy.artifactory.rest.TestUtilities.assertNotNull; import static com.cdancy.artifactory.rest.TestUtilities.assertNull; import static com.cdancy.artifactory.rest.TestUtilities.assertTrue; import com.cdancy.artifactory.rest.domain.artifact.Artifact; import com.cdancy.artifactory.rest.domain.storage.FileList; import com.cdancy.artifactory.rest.domain.storage.StorageInfo; import com.google.common.collect.Lists; import org.testng.annotations.Test; import com.cdancy.artifactory.rest.ArtifactoryApi; import com.cdancy.artifactory.rest.BaseArtifactoryMockTest; import com.squareup.okhttp.mockwebserver.MockResponse;
/* * 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.cdancy.artifactory.rest.features; /** * Mock tests for the {@link com.cdancy.artifactory.rest.features.StorageApi} * class. */ @Test(groups = "unit", testName = "StorageApiMockTest") public class StorageApiMockTest extends BaseArtifactoryMockTest { public void testSetItemProperties() throws Exception { MockWebServer server = mockArtifactoryJavaWebServer(); server.enqueue(new MockResponse().setResponseCode(200));
ArtifactoryApi jcloudsApi = api(server.getUrl("/"));
7
enterprisegeeks/try_java_ee7
try_java_ee7-web/src/main/java/enterprisegeeks/rest/resource/ChatroomResource.java
[ "@Vetoed //CDI対象外\n@Entity\npublic class Chat implements Serializable {\n \n /** id(自動生成) */\n @Id\n @GeneratedValue // ID自動生成 \n private long id;\n \n /** チャットを行ったチャットルーム */\n @ManyToOne // 多対1関連\n private Room room;\n \n /** 発言者 */\n @ManyToOne\n private Account speaker;\n \n /** 内容 */\n @Column(length = 200, nullable = false)\n private String content;\n\n /** 投稿時刻 */\n @Column(nullable = false)\n private Timestamp posted;\n \n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public Room getRoom() {\n return room;\n }\n\n public void setRoom(Room room) {\n this.room = room;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public Account getSpeaker() {\n return speaker;\n }\n\n public void setSpeaker(Account speaker) {\n this.speaker = speaker;\n }\n\n public Timestamp getPosted() {\n return posted;\n }\n\n public void setPosted(Timestamp posted) {\n this.posted = posted;\n }\n \n \n}", "@Vetoed //CDI対象外\n@XmlRootElement\n@Entity\n@NamedQueries(@NamedQuery(name = \"Room.all\", query = \"select r from Room r order by r.id\"))\npublic class Room implements Serializable {\n \n /** id(自動生成) */\n @Id\n @GeneratedValue\n private long id;\n \n /** 部屋名 */\n @Column(nullable = false, length = 40, unique = true)\n private String name;\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n \n \n}", "@RequestScoped\npublic class Authed {\n \n private Account account;\n\n public Account getAccount() {\n return account;\n }\n\n public void setAccount(Account account) {\n this.account = account;\n }\n \n \n}", "public class ChatList {\n public long last;\n \n public List<Chat> chats = new ArrayList<>();\n \n public void addChat(String name, String gravatar, String content) {\n Chat c = new Chat();\n c.name = name;\n c.gravatar = gravatar;\n c.content = content;\n chats.add(c);\n }\n \n public static class Chat{\n public String name;\n public String gravatar;\n public String content;\n \n }\n}", "public class NewChat {\n \n @NotNull(message = \"{required}\")\n public long roomId;\n \n @NotNull(message = \"{required}\")\n @Size(message = \"{required}\", min = 1)\n public String content;\n}", "@Dependent\npublic class ChatNotifier implements Serializable {\n \n @Inject @ChatNotifyEndPoint\n private String wsURI;\n \n @Inject\n private Event<Signal> event;\n \n public void notifyNewChat(){\n System.out.println(\"fire\");\n event.fire(Signal.UPDATE);\n }\n}", "public interface Service{\n \n \n public boolean registerAccount(Account accout);\n \n public Account findAccountByName(String name);\n \n /** ログイン用トークン発行 */\n public String publishToken(Account account);\n \n /** チャットルーム一覧 */\n public List<Room> allRooms();\n \n /** チャットルームのチャット一覧を取得 */\n public List<Chat> findChatByRoom(Room room, Timestamp from);\n \n public void addChat(Chat chat);\n \n public Account getAccountByToken(String token);\n \n \n}" ]
import enterprisegeeks.entity.Chat; import enterprisegeeks.entity.Room; import enterprisegeeks.rest.anotation.WithAuth; import enterprisegeeks.rest.dto.Authed; import enterprisegeeks.rest.dto.ChatList; import enterprisegeeks.rest.dto.NewChat; import enterprisegeeks.service.ChatNotifier; import enterprisegeeks.service.Service; import java.sql.Timestamp; import java.util.List; import javax.ws.rs.Path; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.transaction.Transactional; import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package enterprisegeeks.rest.resource; /** * REST Web Service */ @Path("chatroom") @RequestScoped @Transactional public class ChatroomResource { @Inject private Service service; @Inject private Authed authed; @Inject private ChatNotifier notify; @GET @WithAuth public Viewable init() { return new Viewable("/WEB-INF/jsp/chatroom.jsp", authed.getAccount()); } @GET @Path("rooms") @WithAuth @Produces(MediaType.APPLICATION_JSON) public List<Room> getRooms() { return service.allRooms(); } /** 指定時刻以降のチャット一覧の取得。 */ @GET @Path("chat") @WithAuth @Produces(MediaType.APPLICATION_JSON) public ChatList getChat(@QueryParam("roomId")long roomId, @QueryParam("from")long from) { Room r = new Room(); r.setId(roomId); Timestamp tsFrom = new Timestamp(from);
List<Chat> chatList = service.findChatByRoom(r, tsFrom);
0
cytomine/Cytomine-java-client
src/test/java/client/JobTest.java
[ "public class CytomineException extends Exception {\n\n private static final Logger log = LogManager.getLogger(CytomineException.class);\n\n int httpCode;\n String message = \"\";\n\n public CytomineException(Exception e) {\n super(e);\n this.message = e.getMessage();\n }\n\n public CytomineException(int httpCode, String message) {\n this.httpCode = httpCode;\n this.message = message;\n }\n\n public CytomineException(int httpCode, JSONObject json) {\n this.httpCode = httpCode;\n getMessage(json);\n }\n\n public int getHttpCode() {\n return this.httpCode;\n }\n\n public String getMsg() {\n return this.message;\n }\n\n private String getMessage(JSONObject json) {\n try {\n String msg = \"\";\n if (json != null) {\n Iterator iter = json.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n msg = msg + entry.getValue();\n }\n }\n message = msg;\n } catch (Exception e) {\n log.error(e);\n }\n return message;\n }\n\n public String toString() {\n return httpCode + \" \" + message;\n }\n}", "public class Collection<T extends Model> {\n\n JSONArray list = new JSONArray();\n HashMap<String, String> map = new HashMap<String, String>();\n HashMap<String, String> params = new HashMap<String, String>();\n\n protected int max;\n protected int offset;\n private Class<T> type;\n private T modelInstance;\n\n protected Collection(Class<T> type) {\n this(type, 0,0);\n }\n public Collection(Class<T> type, int max, int offset) {\n this.max = max;\n this.offset = offset;\n this.type = type;\n try {\n modelInstance = type.newInstance();\n } catch (InstantiationException | IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n\n // ####################### URL #######################\n\n public String toURL() throws CytomineException {\n String url = getJSONResourceURL()+\"?\";\n for (Map.Entry<String, String> param : params.entrySet()) {\n url += param.getKey() + \"=\" + param.getValue() + \"&\";\n }\n if(url.charAt(url.length()-1) == '&') url = url.substring(0, url.length() - 1);\n if(url.contains(\"?\") && url.charAt(url.length()-1) == '?') url = url.substring(0, url.length() - 1);\n url += getPaginatorURLParams();\n return url;\n }\n\n protected String getJSONResourceURL() throws CytomineException {\n if(map.size() > 1) {\n throw new CytomineException(400, \"Only one filter is allowed by default\");\n }\n final StringBuilder urlB = new StringBuilder(\"/api\");\n map.forEach((k, v) -> {\n urlB.append(\"/\"+k+\"/\"+v);\n });\n urlB.append(\"/\"+ getDomainName() + \".json\");\n\n return urlB.toString();\n }\n\n private String getPaginatorURLParams() {\n return \"&max=\" + this.max + \"&offset=\" + this.offset;\n }\n\n public String getDomainName() throws CytomineException {\n if(modelInstance == null) throw new CytomineException(400,\"Collection not typed. Not possible to get URL.\");\n return modelInstance.getDomainName();\n }\n\n // ####################### REST METHODS #######################\n\n public static <T extends Model> Collection<T> fetch(Class<T> clazz) throws CytomineException {\n return fetch(clazz,0,0);\n }\n public static <T extends Model> Collection<T> fetch(CytomineConnection connection, Class<T> clazz) throws CytomineException {\n return fetch(connection, clazz,0,0);\n }\n public static <T extends Model> Collection<T> fetch(Class<T> clazz, int offset, int max) throws CytomineException {\n return fetch(Cytomine.getInstance().getDefaultCytomineConnection(), clazz, offset, max);\n }\n public static <T extends Model> Collection<T> fetch(CytomineConnection connection, Class<T> clazz, int offset, int max) throws CytomineException {\n Collection<T> c = new Collection<>(clazz, max, offset);\n return c.fetch(connection);\n }\n public static <T extends Model, U extends Model> Collection<T> fetchWithFilter(Class<T> clazz, Class<U> filter, Long idFilter) throws CytomineException {\n return fetchWithFilter(Cytomine.getInstance().getDefaultCytomineConnection(), clazz, filter, idFilter, 0,0);\n }\n public static <T extends Model, U extends Model> Collection<T> fetchWithFilter(CytomineConnection connection, Class<T> clazz, Class<U> filter, Long idFilter) throws CytomineException {\n return fetchWithFilter(connection, clazz, filter, idFilter, 0,0);\n }\n public static <T extends Model, U extends Model> Collection<T> fetchWithFilter(Class<T> clazz, Class<U> filter, Long idFilter, int offset, int max) throws CytomineException {\n return fetchWithFilter(Cytomine.getInstance().getDefaultCytomineConnection(), clazz, filter, idFilter, offset, max);\n }\n\n public static <T extends Model, U extends Model> Collection<T> fetchWithFilter(CytomineConnection connection, Class<T> clazz, Class<U> filter, Long idFilter, int offset, int max) throws CytomineException {\n Collection<T> c = new Collection<>(clazz, max, offset);\n try {\n c.addFilter(filter.newInstance().getDomainName(), idFilter.toString());\n } catch (InstantiationException | IllegalAccessException e) {\n e.printStackTrace();\n }\n return c.fetch(connection,offset,max);\n }\n protected <U extends Model> Collection<T> fetchWithFilter(CytomineConnection connection, Class<U> filter, Long idFilter, int offset, int max) throws CytomineException {\n try {\n this.addFilter(filter.newInstance().getDomainName(), idFilter.toString());\n } catch (InstantiationException | IllegalAccessException e) {\n e.printStackTrace();\n }\n return this.fetch(connection,offset,max);\n }\n\n\n public Collection<T> fetch() throws CytomineException {\n return this.fetch(Cytomine.getInstance().getDefaultCytomineConnection());\n }\n\n public Collection<T> fetch(CytomineConnection connection) throws CytomineException {\n return this.fetch(connection,this.offset ,this.max );\n }\n\n public Collection<T> fetch(int offset, int max) throws CytomineException {\n return this.fetch(Cytomine.getInstance().getDefaultCytomineConnection(), offset, max);\n }\n\n public Collection<T> fetch(CytomineConnection connection, int offset, int max) throws CytomineException {\n this.offset =offset;\n this.max = max;\n JSONObject json = connection.doGet(this.toURL());\n this.setList((JSONArray) json.get(\"collection\"));\n return this;\n }\n public Collection<T> fetchNextPage() throws CytomineException {\n return this.fetchNextPage(Cytomine.getInstance().getDefaultCytomineConnection());\n }\n public Collection<T> fetchNextPage(CytomineConnection connection) throws CytomineException {\n this.offset = this.offset + max;\n return this.fetch(connection);\n }\n\n // ####################### Getters/Setters #######################\n\n public T get(int i) {\n try {\n T modelInstance = type.newInstance();\n modelInstance.setAttr((JSONObject) list.get(i));\n return modelInstance;\n } catch (InstantiationException | IllegalAccessException ignored) {\n // ignore, would already have failed in constructor\n return null;\n }\n }\n\n public JSONArray getList() {\n return list;\n }\n\n public void setList(JSONArray list) {\n this.list = list;\n }\n\n\n public int size() {\n return list.size();\n }\n\n public boolean isEmpty() {\n return list.isEmpty();\n }\n\n public void add(Object o) {\n list.add(((Model) o).getAttr());\n }\n\n boolean isFilterBy(String name) {\n return map.containsKey(name);\n }\n\n public String getFilter(String name) {\n return map.get(name);\n }\n\n public Map<String, String> getFilters() {\n return map;\n }\n\n\n public void addFilter(String name, String value) {\n map.put(name, value);\n }\n\n public void addParams(String name, String value) {\n params.put(name, value);\n }\n\n public String toString() {\n try {\n return getDomainName() + \" collection (\"+size()+\" elements)\";\n } catch (CytomineException e) {\n return \"collection\";\n }\n }\n}", "public class JobCollection extends Collection<Job> {\n\n public JobCollection() {\n this(0, 0);\n }\n public JobCollection(int offset, int max) {\n super(Job.class, max, offset);\n }\n\n\n public static JobCollection fetchBySoftware(Software software) throws CytomineException {\n return fetchBySoftware(Cytomine.getInstance().getDefaultCytomineConnection(), software);\n }\n public static JobCollection fetchBySoftware(CytomineConnection connection, Software software) throws CytomineException {\n return fetchByDomain(connection, software, 0,0);\n }\n public static JobCollection fetchBySoftware(Software software, int offset, int max) throws CytomineException {\n return fetchByDomain(Cytomine.getInstance().getDefaultCytomineConnection(), software, offset,max);\n }\n\n public static JobCollection fetchByProject(Project project) throws CytomineException {\n return fetchByProject(Cytomine.getInstance().getDefaultCytomineConnection(), project);\n }\n public static JobCollection fetchByProject(CytomineConnection connection, Project project) throws CytomineException {\n return fetchByDomain(connection, project, 0,0);\n }\n public static JobCollection fetchByProject(Project project, int offset, int max) throws CytomineException {\n return fetchByDomain(Cytomine.getInstance().getDefaultCytomineConnection(), project, offset,max);\n }\n\n private static JobCollection fetchByDomain(CytomineConnection connection, Model domain, int offset, int max) throws CytomineException {\n return (JobCollection) new JobCollection(max, offset).fetchWithFilter(connection, domain.getClass(), domain.getId(), offset, max);\n }\n\n public static JobCollection fetchByProjectAndSoftware(Project project, Software software) throws CytomineException {\n return fetchByProjectAndSoftware(Cytomine.getInstance().getDefaultCytomineConnection(), project, software);\n }\n public static JobCollection fetchByProjectAndSoftware(CytomineConnection connection, Project project, Software software) throws CytomineException {\n return fetchByProjectAndSoftware(connection, project, software, 0,0);\n }\n public static JobCollection fetchByProjectAndSoftware(Project project, Software software, int offset, int max) throws CytomineException {\n return fetchByProjectAndSoftware(Cytomine.getInstance().getDefaultCytomineConnection(), project, software, offset,max);\n }\n public static JobCollection fetchByProjectAndSoftware(CytomineConnection connection, Project project, Software software, int offset, int max) throws CytomineException {\n JobCollection sc = new JobCollection(max, offset);\n sc.addFilter(project.getDomainName(), project.getId().toString());\n sc.addFilter(software.getDomainName(), software.getId().toString());\n return (JobCollection)sc.fetch();\n }\n\n\n\n\n //TODO remove when rest url are normalized\n protected String getJSONResourceURL() throws CytomineException {\n final StringBuilder urlB = new StringBuilder(\"/api\");\n urlB.append(\"/\"+ getDomainName() + \".json?\");\n map.forEach((k, v) -> {\n urlB.append(k + \"=\" + v + \"&\");\n });\n\n urlB.deleteCharAt(urlB.length()-1);\n\n return urlB.toString();\n }\n\n\n}", "public class Job extends Model<Job> {\n\n public enum JobStatus{\n NOTLAUNCH (0),\n INQUEUE (1),\n RUNNING (2),\n SUCCESS (3),\n FAILED (4),\n INDETERMINATE (5),\n WAIT (6),\n PREVIEWED (7),\n KILLED (8);\n\n private int valueOfJob;\n\n JobStatus(int value){this.valueOfJob=value;}\n\n public int getValue() {\n return this.valueOfJob;\n }\n\n }\n\n public Job(){}\n public Job(Software software, Project project){\n this(software.getId(), project.getId());\n }\n public Job(Long softwareId, Long projectId){\n set(\"project\", projectId);\n set(\"software\", softwareId);\n }\n\n public void execute() throws CytomineException {\n Cytomine.getInstance().getDefaultCytomineConnection().doPost(\"/api/job/\"+get(\"id\")+\"/execute.json\", \"\");\n }\n\n public Job changeStatus(JobStatus status, int progress) throws CytomineException {\n return changeStatus(status.getValue(), progress);\n }\n public Job changeStatus(JobStatus status, int progress, String comment) throws CytomineException {\n return changeStatus(status.getValue(), progress,comment);\n }\n public Job changeStatus(int status, int progress) throws CytomineException {\n return this.changeStatus(status, progress, null);\n }\n\n public Job changeStatus(int status, int progress, String comment) throws CytomineException {\n this.set(\"progress\", progress);\n this.set(\"status\", status);\n this.set(\"statusComment\", comment);\n return this.update();\n }\n}", "public class Project extends Model<Project> {\n public Project(){}\n public Project(String name, Ontology ontology){\n this(name,ontology.getId());\n }\n public Project(String name, Long idOntology){\n this.set(\"name\", name);\n this.set(\"ontology\", idOntology);\n }\n\n public void addMember(User user) throws CytomineException {\n addMember(user, false);\n }\n public void addMember(User user, boolean admin) throws CytomineException {\n addMember(user.getId(), admin);\n }\n public void addMember(Long userId, boolean admin) throws CytomineException {\n Cytomine.getInstance().getDefaultCytomineConnection().doPost(\"/api/project/\" + this.getId() + \"/user/\" + userId + (admin ? \"/admin\" : \"\") + \".json\", \"\");\n }\n\n public void removeMember(User user) throws CytomineException {\n removeMember(user, false);\n }\n public void removeMember(User user, boolean admin) throws CytomineException {\n removeMember(user.getId(), admin);\n }\n public void removeMember(Long idUser, boolean admin) throws CytomineException {\n Cytomine.getInstance().getDefaultCytomineConnection().doDelete(\"/api/project/\" + this.getId() + \"/user/\" + idUser + (admin ? \"/admin\" : \"\") + \".json\");\n }\n}", "public class Software extends Model<Software> {\n public Software(){}\n public Software(String name, String resultType, String executeCommand, String softwareVersion){\n this.set(\"name\", name);\n this.set(\"resultName\", resultType);\n this.set(\"executeCommand\", executeCommand);\n this.set(\"softwareVersion\", softwareVersion);\n }\n\n public Software(String name, String resultType, String executeCommand, String softwareVersion, Long idSoftwareUserRepository, Long idDefaultProcessingServer){\n this.set(\"name\", name);\n this.set(\"softwareUserRepository\", idSoftwareUserRepository);\n this.set(\"defaultProcessingServer\", idDefaultProcessingServer);\n this.set(\"resultName\", resultType);\n this.set(\"executeCommand\", executeCommand);\n this.set(\"softwareVersion\", softwareVersion);\n }\n\n public Software(String name, String resultType, String executeCommand, String softwareVersion, Long idSoftwareUserRepository, Long idDefaultProcessingServer, String pullingCommand){\n this.set(\"name\", name);\n this.set(\"softwareUserRepository\", idSoftwareUserRepository);\n this.set(\"defaultProcessingServer\", idDefaultProcessingServer);\n this.set(\"resultName\", resultType);\n this.set(\"executeCommand\", executeCommand);\n this.set(\"softwareVersion\", softwareVersion);\n this.set(\"pullingCommand\", pullingCommand);\n }\n\n public Software deprecate() throws CytomineException {\n this.set(\"deprecated\", true);\n return this.update();\n }\n\n public void upload(File file) throws CytomineException {\n upload(Cytomine.getInstance().getDefaultCytomineConnection(), file);\n }\n public void upload(CytomineConnection connection, File file) throws CytomineException {\n String url = \"/api/\"+ getDomainName()+\"/upload\";\n connection.uploadFile(url, file, attr);\n }\n\n public void download(String destPath) throws CytomineException {\n download(new File(destPath));\n }\n public void download(File dest) throws CytomineException {\n download(Cytomine.getInstance().getDefaultCytomineConnection(), dest);\n }\n public void download(CytomineConnection connection, File dest) throws CytomineException {\n String url = \"/api/\"+ getDomainName()+\"/\"+this.getId()+\"/download\";\n connection.downloadFile(url, dest.getPath());\n }\n\n}" ]
import be.cytomine.client.CytomineException; import be.cytomine.client.collections.Collection; import be.cytomine.client.collections.JobCollection; import be.cytomine.client.models.Job; import be.cytomine.client.models.Project; import be.cytomine.client.models.Software; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
package client; /* * Copyright (c) 2009-2020. Authors: see NOTICE file. * * 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. */ public class JobTest { private static final Logger log = LogManager.getLogger(JobTest.class); @BeforeAll static void init() throws CytomineException { Utils.connect(); } @Test void testCreateJob() throws CytomineException { log.info("test create software_parameter"); Software software = Utils.getSoftware();
Project project = Utils.getProject();
4
flutterwireless/ArduinoCodebase
app/src/cc/arduino/packages/uploaders/SerialUploader.java
[ "public abstract class Uploader implements MessageConsumer {\n\n private static final List<String> STRINGS_TO_SUPPRESS;\n private static final List<String> AVRDUDE_PROBLEMS;\n\n static {\n STRINGS_TO_SUPPRESS = Arrays.asList(\"Connecting to programmer:\",\n \"Found programmer: Id = \\\"CATERIN\\\"; type = S\",\n \"Software Version = 1.0; No Hardware Version given.\",\n \"Programmer supports auto addr increment.\",\n \"Programmer supports buffered memory access with buffersize=128 bytes.\",\n \"Programmer supports the following devices:\", \"Device code: 0x44\");\n\n AVRDUDE_PROBLEMS = Arrays.asList(\"Programmer is not responding\",\n \"programmer is not responding\",\n \"protocol error\", \"avrdude: ser_open(): can't open device\",\n \"avrdude: ser_drain(): read error\",\n \"avrdude: ser_send(): write error\",\n \"avrdude: error: buffered memory access not supported.\");\n }\n\n protected final boolean verbose;\n\n private String error;\n protected boolean notFoundError;\n\n protected Uploader() {\n this.error = null;\n this.verbose = Preferences.getBoolean(\"upload.verbose\");\n this.notFoundError = false;\n }\n\n public abstract boolean uploadUsingPreferences(File sourcePath, String buildPath, String className, boolean usingProgrammer, List<String> warningsAccumulator) throws Exception;\n\n public abstract boolean burnBootloader() throws Exception;\n\n public boolean requiresAuthorization() {\n return false;\n }\n\n public String getAuthorizationKey() {\n return null;\n }\n\n protected boolean executeUploadCommand(Collection<String> command) throws Exception {\n return executeUploadCommand(command.toArray(new String[command.size()]));\n }\n\n protected boolean executeUploadCommand(String command[]) throws Exception {\n notFoundError = false;\n int result = -1;\n\n try {\n if (verbose) {\n for (String c : command)\n System.out.print(c + \" \");\n System.out.println();\n }\n Process process = ProcessUtils.exec(command);\n new MessageSiphon(process.getInputStream(), this);\n new MessageSiphon(process.getErrorStream(), this);\n\n // wait for the process to finish.\n result = process.waitFor();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n if (error != null) {\n RunnerException exception = new RunnerException(error);\n exception.hideStackTrace();\n throw exception;\n }\n\n return result == 0;\n }\n\n public void message(String s) {\n // selectively suppress a bunch of avrdude output for AVR109/Caterina that should already be quelled but isn't\n if (!verbose && StringUtils.stringContainsOneOf(s, STRINGS_TO_SUPPRESS)) {\n s = \"\";\n }\n\n System.err.print(s);\n\n // ignore cautions\n if (s.contains(\"Error\")) {\n notFoundError = true;\n return;\n }\n if (notFoundError) {\n error = I18n.format(_(\"the selected serial port {0} does not exist or your board is not connected\"), s);\n return;\n }\n if (s.contains(\"Device is not responding\")) {\n error = _(\"Device is not responding, check the right serial port is selected or RESET the board right before exporting\");\n return;\n }\n if (StringUtils.stringContainsOneOf(s, AVRDUDE_PROBLEMS)) {\n error = _(\"Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.\");\n return;\n }\n if (s.contains(\"Expected signature\")) {\n error = _(\"Wrong microcontroller found. Did you select the right board from the Tools > Board menu?\");\n return;\n }\n }\n}", "public class TargetPlatform {\n\n private String id;\n private File folder;\n private TargetPackage containerPackage;\n\n /**\n * Contains preferences for every defined board\n */\n private Map<String, TargetBoard> boards = new LinkedHashMap<String, TargetBoard>();\n\n /**\n * Contains preferences for every defined programmer\n */\n private Map<String, PreferencesMap> programmers = new LinkedHashMap<String, PreferencesMap>();\n\n /**\n * Contains preferences for platform\n */\n private PreferencesMap preferences = new PreferencesMap();\n\n /**\n * Contains labels for top level menus\n */\n private PreferencesMap customMenus = new PreferencesMap();\n\n public TargetPlatform(String _name, File _folder, TargetPackage parent)\n throws TargetPlatformException {\n\n id = _name;\n folder = _folder;\n containerPackage = parent;\n\n // If there is no boards.txt, this is not a valid 1.5 hardware folder\n File boardsFile = new File(folder, \"boards.txt\");\n if (!boardsFile.exists() || !boardsFile.canRead())\n throw new TargetPlatformException(\n format(_(\"Could not find boards.txt in {0}. Is it pre-1.5?\"),\n boardsFile.getAbsolutePath()));\n\n // Load boards\n try {\n Map<String, PreferencesMap> boardsPreferences = new PreferencesMap(\n boardsFile).firstLevelMap();\n\n // Create custom menus for this platform\n PreferencesMap menus = boardsPreferences.get(\"menu\");\n if (menus != null)\n customMenus = menus.topLevelMap();\n boardsPreferences.remove(\"menu\");\n\n // Create boards\n for (String id : boardsPreferences.keySet()) {\n PreferencesMap preferences = boardsPreferences.get(id);\n TargetBoard board = new TargetBoard(id, preferences, this);\n boards.put(id, board);\n }\n } catch (IOException e) {\n throw new TargetPlatformException(format(_(\"Error loading {0}\"),\n boardsFile.getAbsolutePath()), e);\n }\n\n File platformsFile = new File(folder, \"platform.txt\");\n try {\n if (platformsFile.exists() && platformsFile.canRead()) {\n preferences.load(platformsFile);\n }\n } catch (IOException e) {\n throw new TargetPlatformException(\n format(_(\"Error loading {0}\"), platformsFile.getAbsolutePath()), e);\n }\n\n File progFile = new File(folder, \"programmers.txt\");\n try {\n if (progFile.exists() && progFile.canRead()) {\n PreferencesMap prefs = new PreferencesMap();\n prefs.load(progFile);\n programmers = prefs.firstLevelMap();\n }\n } catch (IOException e) {\n throw new TargetPlatformException(format(_(\"Error loading {0}\"), progFile\n .getAbsolutePath()), e);\n }\n }\n\n public String getId() {\n return id;\n }\n\n public File getFolder() {\n return folder;\n }\n\n public Map<String, TargetBoard> getBoards() {\n return boards;\n }\n\n public PreferencesMap getCustomMenus() {\n return customMenus;\n }\n\n public Set<String> getCustomMenuIds() {\n return customMenus.keySet();\n }\n\n public Map<String, PreferencesMap> getProgrammers() {\n return programmers;\n }\n\n public PreferencesMap getProgrammer(String programmer) {\n return getProgrammers().get(programmer);\n }\n\n public PreferencesMap getTool(String tool) {\n return getPreferences().subTree(\"tools\").subTree(tool);\n }\n\n public PreferencesMap getPreferences() {\n return preferences;\n }\n\n public TargetBoard getBoard(String boardId) {\n return boards.get(boardId);\n }\n\n public TargetPackage getContainerPackage() {\n return containerPackage;\n }\n\n @Override\n public String toString() {\n String res = \"TargetPlatform: name=\" + id + \" boards={\\n\";\n for (String boardId : boards.keySet())\n res += \" \" + boardId + \" = \" + boards.get(boardId) + \"\\n\";\n return res + \"}\";\n }\n}", "@SuppressWarnings(\"serial\")\npublic class PreferencesMap extends LinkedHashMap<String, String> {\n\n public PreferencesMap(Map<String, String> table) {\n super(table);\n }\n\n /**\n * Create a PreferencesMap and load the content of the file passed as\n * argument.\n * \n * Is equivalent to:\n * \n * <pre>\n * PreferencesMap map = new PreferencesMap();\n * map.load(file);\n * </pre>\n * \n * @param file\n * @throws IOException\n */\n public PreferencesMap(File file) throws IOException {\n super();\n load(file);\n }\n\n public PreferencesMap() {\n super();\n }\n\n /**\n * Parse a property list file and put kev/value pairs into the Map\n * \n * @param file\n * @throws FileNotFoundException\n * @throws IOException\n */\n public void load(File file) throws IOException {\n load(new FileInputStream(file));\n }\n\n /**\n * Parse a property list stream and put key/value pairs into the Map\n * \n * @param input\n * @throws IOException\n */\n public void load(InputStream input) throws IOException {\n String[] lines = PApplet.loadStrings(input);\n for (String line : lines) {\n if (line.length() == 0 || line.charAt(0) == '#')\n continue;\n\n int equals = line.indexOf('=');\n if (equals != -1) {\n String key = line.substring(0, equals);\n String value = line.substring(equals + 1);\n put(key.trim(), value.trim());\n }\n }\n\n // This is needed to avoid ConcurrentAccessExceptions\n Set<String> keys = new LinkedHashSet<String>(keySet());\n\n // Override keys that have OS specific versions\n for (String key : keys) {\n boolean replace = false;\n if (Base.isLinux() && key.endsWith(\".linux\"))\n replace = true;\n if (Base.isWindows() && key.endsWith(\".windows\"))\n replace = true;\n if (Base.isMacOS() && key.endsWith(\".macos\"))\n replace = true;\n if (replace) {\n int dot = key.lastIndexOf('.');\n String overridenKey = key.substring(0, dot);\n put(overridenKey, get(key));\n }\n }\n }\n\n /**\n * Create a new PreferenceMap that contains all the top level pairs of the\n * current mapping. E.g. the folowing mapping:<br />\n * \n * <pre>\n * Map (\n * alpha = Alpha\n * alpha.some.keys = v1\n * alpha.other.keys = v2\n * beta = Beta\n * beta.some.keys = v3\n * )\n * </pre>\n * \n * will generate the following result:\n * \n * <pre>\n * Map (\n * alpha = Alpha\n * beta = Beta\n * )\n * </pre>\n * \n * @return\n */\n public PreferencesMap topLevelMap() {\n PreferencesMap res = new PreferencesMap();\n for (String key : keySet()) {\n if (key.contains(\".\"))\n continue;\n res.put(key, get(key));\n }\n return res;\n }\n\n /**\n * Create a new Map<String, PreferenceMap> where keys are the first level of\n * the current mapping. Top level pairs are discarded. E.g. the folowing\n * mapping:<br />\n * \n * <pre>\n * Map (\n * alpha = Alpha\n * alpha.some.keys = v1\n * alpha.other.keys = v2\n * beta = Beta\n * beta.some.keys = v3\n * )\n * </pre>\n * \n * will generate the following result:\n * \n * <pre>\n * alpha = Map(\n * some.keys = v1\n * other.keys = v2\n * )\n * beta = Map(\n * some.keys = v3\n * )\n * </pre>\n * \n * @return\n */\n public Map<String, PreferencesMap> firstLevelMap() {\n Map<String, PreferencesMap> res = new LinkedHashMap<String, PreferencesMap>();\n for (String key : keySet()) {\n int dot = key.indexOf('.');\n if (dot == -1)\n continue;\n\n String parent = key.substring(0, dot);\n String child = key.substring(dot + 1);\n\n if (!res.containsKey(parent))\n res.put(parent, new PreferencesMap());\n res.get(parent).put(child, get(key));\n }\n return res;\n }\n\n /**\n * Create a new PreferenceMap using a subtree of the current mapping. Top\n * level pairs are ignored. E.g. with the following mapping:<br />\n * \n * <pre>\n * Map (\n * alpha = Alpha\n * alpha.some.keys = v1\n * alpha.other.keys = v2\n * beta = Beta\n * beta.some.keys = v3\n * )\n * </pre>\n * \n * a call to createSubTree(\"alpha\") will generate the following result:\n * \n * <pre>\n * Map(\n * some.keys = v1\n * other.keys = v2\n * )\n * </pre>\n * \n * @param parent\n * @return\n */\n public PreferencesMap subTree(String parent) {\n PreferencesMap res = new PreferencesMap();\n parent += \".\";\n int parentLen = parent.length();\n for (String key : keySet()) {\n if (key.startsWith(parent))\n res.put(key.substring(parentLen), get(key));\n }\n return res;\n }\n\n public String toString(String indent) {\n String res = indent + \"{\\n\";\n SortedSet<String> treeSet = new TreeSet<String>(keySet());\n for (String k : treeSet)\n res += indent + k + \" = \" + get(k) + \"\\n\";\n return res;\n }\n\n /**\n * Returns the value to which the specified key is mapped, or throws a\n * PreferencesMapException if not found\n * \n * @param k\n * the key whose associated value is to be returned\n * @return the value to which the specified key is mapped\n * @throws PreferencesMapException\n */\n public String getOrExcept(String k) throws PreferencesMapException {\n String r = get(k);\n if (r == null)\n throw new PreferencesMapException(k);\n return r;\n }\n\n @Override\n public String toString() {\n return toString(\"\");\n }\n}", "public class StringReplacer {\n\n public static String[] formatAndSplit(String src, Map<String, String> dict,\n boolean recursive) throws Exception {\n String res;\n\n // Recursive replace with a max depth of 10 levels.\n for (int i = 0; i < 10; i++) {\n // Do a replace with dictionary\n res = StringReplacer.replaceFromMapping(src, dict);\n if (!recursive)\n break;\n if (res.equals(src))\n break;\n src = res;\n }\n\n // Split the resulting string in arguments\n return quotedSplit(src, \"\\\"'\", false);\n }\n\n public static String[] quotedSplit(String src, String quoteChars,\n boolean acceptEmptyArguments)\n throws Exception {\n List<String> res = new ArrayList<String>();\n String escapedArg = null;\n String escapingChar = null;\n for (String i : src.split(\" \")) {\n if (escapingChar == null) {\n // If the first char is not an escape char..\n String first = null;\n if (i.length() > 0)\n first = i.substring(0, 1);\n if (first == null || !quoteChars.contains(first)) {\n if (i.trim().length() != 0 || acceptEmptyArguments)\n res.add(i);\n continue;\n }\n\n escapingChar = first;\n i = i.substring(1);\n escapedArg = \"\";\n }\n\n if (!i.endsWith(escapingChar)) {\n escapedArg += i + \" \";\n continue;\n }\n\n escapedArg += i.substring(0, i.length() - 1);\n if (escapedArg.trim().length() != 0 || acceptEmptyArguments)\n res.add(escapedArg);\n escapingChar = null;\n }\n if (escapingChar != null)\n throw new Exception(\"Invalid quoting: no closing [\" + escapingChar +\n \"] char found.\");\n return res.toArray(new String[0]);\n }\n\n public static String replaceFromMapping(String src, Map<String, String> map) {\n return replaceFromMapping(src, map, \"{\", \"}\");\n }\n\n public static String replaceFromMapping(String src, Map<String, String> map,\n String leftDelimiter,\n String rightDelimiter) {\n for (String k : map.keySet()) {\n String keyword = leftDelimiter + k + rightDelimiter;\n src = src.replace(keyword, map.get(k));\n }\n return src;\n }\n\n}", "public static String _(String s) {\n String res;\n try {\n res = i18n.getString(s);\n } catch (MissingResourceException e) {\n res = s;\n }\n\n // The single % is the arguments selector in .PO files.\n // We must put double %% inside the translations to avoid\n // getting .PO processing in the way.\n res = res.replace(\"%%\", \"%\");\n\n return res;\n}" ]
import processing.app.debug.RunnerException; import processing.app.debug.TargetPlatform; import processing.app.helpers.PreferencesMap; import processing.app.helpers.StringReplacer; import java.io.File; import java.util.ArrayList; import java.util.List; import static processing.app.I18n._; import cc.arduino.packages.Uploader; import processing.app.*;
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* BasicUploader - generic command line uploader implementation Part of the Arduino project - http://www.arduino.cc/ Copyright (c) 2004-05 Hernando Barragan Copyright (c) 2012 Cristian Maglie <c.maglie@bug.st> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ */ package cc.arduino.packages.uploaders; public class SerialUploader extends Uploader { public boolean uploadUsingPreferences(File sourcePath, String buildPath, String className, boolean usingProgrammer, List<String> warningsAccumulator) throws Exception { // FIXME: Preferences should be reorganized TargetPlatform targetPlatform = Base.getTargetPlatform(); PreferencesMap prefs = Preferences.getMap(); prefs.putAll(Base.getBoardPreferences()); String tool = prefs.getOrExcept("upload.tool"); if (tool.contains(":")) { String[] split = tool.split(":", 2); targetPlatform = Base.getCurrentTargetPlatformFromPackage(split[0]); tool = split[1]; } prefs.putAll(targetPlatform.getTool(tool)); // if no protocol is specified for this board, assume it lacks a // bootloader and upload using the selected programmer. if (usingProgrammer || prefs.get("upload.protocol") == null) { return uploadUsingProgrammer(buildPath, className); } // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. String t = prefs.get("upload.use_1200bps_touch"); boolean doTouch = t != null && t.equals("true"); t = prefs.get("upload.wait_for_upload_port"); boolean waitForUploadPort = (t != null) && t.equals("true"); if (doTouch) { String uploadPort = prefs.getOrExcept("serial.port"); try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose)
System.out.println(_("Forcing reset using 1200bps open/close on port ") + uploadPort);
4
tokuhirom/jtt
src/test/java/me/geso/jtt/tt/TTParserTest.java
[ "public class Source {\n\tprivate final SourceType type;\n\tprivate final String source;\n\n\tenum SourceType {\n\t\tFROM_FILE, FROM_STRING\n\t}\n\n\tpublic Source(SourceType type, String source) {\n\t\tthis.type = type;\n\t\tthis.source = source;\n\t}\n\n\t/**\n\t * Create new source object from string.\n\t * \n\t * @param source\n\t * @return\n\t */\n\tpublic static Source fromString(String source) {\n\t\treturn new Source(SourceType.FROM_STRING, source);\n\t}\n\n\t/**\n\t * Create new Souce object from file Name.\n\t * \n\t * @param fileName\n\t * @return\n\t */\n\tpublic static Source fromFile(String fileName) {\n\t\treturn new Source(SourceType.FROM_FILE, fileName);\n\t}\n\n\tpublic List<String> getSourceLines() throws IOException {\n\t\tif (this.type == SourceType.FROM_FILE) {\n\t\t\treturn Files.readAllLines(new File(this.source).toPath());\n\t\t} else {\n\t\t\tList<String> list = new ArrayList<String>();\n\t\t\tString[] lines = source.split(\"\\r?\\n\");\n\t\t\tfor (String line : lines) {\n\t\t\t\tlist.add(line);\n\t\t\t}\n\t\t\treturn list;\n\t\t}\n\t}\n\t\n\tpublic String getTargetLines(int line) throws IOException {\n\t\tStringBuilder buf = new StringBuilder();\n\t\tList<String> lines = this.getSourceLines();\n\t\tfor (int i=Math.max(0, line-3); i<Math.min(lines.size(), line+3); ++i) {\n\t\t\tbuf.append(i==line-1 ? \"* \" : \" \");\n\t\t\tbuf.append(lines.get(i) + \"\\n\");\n\t\t}\n\t\treturn new String(buf);\n\t}\n\n\tpublic String getFileName() {\n\t\tif (this.type == SourceType.FROM_FILE) {\n\t\t\treturn this.source;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n}", "public interface Syntax {\n\n\tpublic abstract List<Token> tokenize(Source source, String src);\n\n\tpublic abstract Node parse(Source source, List<Token> tokens)\n\t\t\tthrows ParserError;\n\n\tpublic abstract Irep compile(Source source, Node ast) throws ParserError;\n\n}", "public class ParserError extends JTTError {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate Parser parser;\n\n\tpublic ParserError(String msg, Parser parser) {\n\t\tsuper(msg);\n\t\tthis.parser = parser;\n\t}\n\n\tpublic String toString() {\n\t\tint line = parser.getLine();\n\t\tSource src = parser.getSource();\n\t\tString lines;\n\t\ttry {\n\t\t\tlines = src.getTargetLines(line);\n\t\t} catch (IOException e) {\n\t\t\tlines = \"(IOException)\";\n\t\t}\n\n\t\tStringBuilder buf = new StringBuilder();\n\t\tbuf.append(this.getMessage() + \" at \" + parser.getFileName() + \" line \"\n\t\t\t\t+ line);\n\t\tbuf.append(\"\\n==============================================\\n\");\n\t\tbuf.append(lines);\n\t\tbuf.append(\"\\n==============================================\");\n\n\t\treturn buf.toString();\n\t}\n}", "public class Token {\n\tprivate TokenType type;\n\tprivate String string;\n\tprivate int lineNumber;\n\tprivate String fileName;\n\n\tpublic Token(TokenType type, String string, int lineNumber, String fileName) {\n\t\tthis.type = type;\n\t\tthis.string = string;\n\t\tthis.lineNumber = lineNumber;\n\t\tthis.fileName = fileName;\n\t}\n\n\tpublic Token(TokenType type, int lineNumber, String fileName) {\n\t\tthis.type = type;\n\t\tthis.string = null;\n\t\tthis.lineNumber = lineNumber;\n\t\tthis.fileName = fileName;\n\t}\n\n\tpublic TokenType getType() {\n\t\treturn type;\n\t}\n\n\tpublic String getString() {\n\t\treturn string;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Token [type=\" + type + \", string=\" + string + \"]\";\n\t}\n\n\tpublic int getLineNumber() {\n\t\treturn lineNumber;\n\t}\n\n\tpublic String getFileName() {\n\t\treturn fileName;\n\t}\n}", "public class Node {\n\n\tprivate final String text;\n\tprivate final NodeType type;\n\tprivate final List<Node> children;\n\tprivate final int lineNumber;\n\n\tpublic Node(NodeType type, int lineNumber) {\n\t\tthis.type = type;\n\t\tthis.text = null;\n\t\tthis.children = null;\n\t\tthis.lineNumber = lineNumber;\n\t}\n\n\tpublic Node(NodeType type, String text, int lineNumber) {\n\t\tthis.type = type;\n\t\tthis.text = text;\n\t\tthis.children = null;\n\t\tthis.lineNumber = lineNumber;\n\t}\n\n\tpublic Node(NodeType type, Node child, int lineNumber) {\n\t\tthis.type = type;\n\t\tthis.text = null;\n\n\t\tList<Node> children = new ArrayList<>();\n\t\tchildren.add(child);\n\t\tthis.children = children;\n\t\tthis.lineNumber = lineNumber;\n\t}\n\n\tpublic Node(NodeType type, List<Node> children, int lineNumber) {\n\t\tthis.type = type;\n\t\tthis.text = null;\n\t\tthis.children = children;\n\t\tthis.lineNumber = lineNumber;\n\t}\n\n\tpublic Node(NodeType type, Node lhs, Node rhs, int lineNumber) {\n\t\tthis.type = type;\n\t\tthis.text = null;\n\n\t\tList<Node> children = new ArrayList<>();\n\t\tchildren.add(lhs);\n\t\tchildren.add(rhs);\n\t\tthis.children = children;\n\t\tthis.lineNumber = lineNumber;\n\t}\n\n\tpublic String getText() {\n\t\treturn text;\n\t}\n\n\tpublic List<Node> getChildren() {\n\t\treturn children;\n\t}\n\n\tpublic NodeType getType() {\n\t\treturn type;\n\t}\n\n\tpublic int getLineNumber() {\n\t\treturn lineNumber;\n\t}\n\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append('(');\n\t\tbuilder.append(type.toString().toLowerCase());\n\t\tif (children != null) {\n\t\t\tbuilder.append(' ');\n\t\t\tfor (int i = 0; i < children.size(); i++) {\n\t\t\t\tbuilder.append(children.get(i));\n\t\t\t\tif (i != children.size() - 1) {\n\t\t\t\t\tbuilder.append(' ');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (text != null) {\n\t\t\tbuilder.append(' ');\n\t\t\tbuilder.append(text);\n\t\t}\n\t\tbuilder.append(')');\n\t\treturn builder.toString();\n\t}\n\n}", "public enum NodeType {\n\tINTEGER,\n\tSTRING,\n\tRAW_STRING,\n\tEXPRESSION, TEMPLATE, ADD, IDENT, SUBTRACT, MULTIPLY, DIVIDE, DOUBLE, FOREACH, EQUALS, GT, GE, LE, LT, ARRAY, MODULO, IF, TRUE, FALSE, NULL, CONCAT, SET, WHILE, LAST, NEXT, INCLUDE, MAP, ATTRIBUTE, SWITCH, DEFAULT, CASE, RANGE, NOT, FUNCALL, ANDAND, NE, OROR, DOLLARVAR, WRAPPER, LOOP_COUNT, LOOP_HAS_NEXT, LOOP_INDEX\n}", "public class TTSyntax implements Syntax {\n\tprivate final String openTag;\n\tprivate final String closeTag;\n\n\tpublic TTSyntax(String openTag, String closeTag) {\n\t\tthis.openTag = openTag;\n\t\tthis.closeTag = closeTag;\n\t}\n\n\tpublic TTSyntax() {\n\t\tthis.openTag = \"[%\";\n\t\tthis.closeTag = \"%]\";\n\t}\n\n\t/* (non-Javadoc)\n\t * @see me.geso.jtt.tt.Syntax#tokenize(java.lang.String, java.lang.String)\n\t */\n\t@Override\n\tpublic List<Token> tokenize(Source source, String src) {\n\t\tTTLexer lexer = new TTLexer(source, src, openTag, closeTag);\n\t\treturn lexer.lex();\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see me.geso.jtt.tt.Syntax#parse(java.lang.String, java.util.List)\n\t */\n\t@Override\n\tpublic Node parse(Source source, List<Token> tokens) throws ParserError {\n\t\treturn new TTParser(source, tokens).parseTemplate();\n\t}\n\n\t/* (non-Javadoc)\n\t * @see me.geso.jtt.tt.Syntax#compile(me.geso.jtt.parser.Node)\n\t */\n\t@Override\n\tpublic Irep compile(Source source, Node ast) throws ParserError {\n\t\treturn new Compiler().compile(source, ast);\n\t}\n}" ]
import static org.junit.Assert.assertEquals; import java.util.List; import me.geso.jtt.Source; import me.geso.jtt.Syntax; import me.geso.jtt.exception.ParserError; import me.geso.jtt.lexer.Token; import me.geso.jtt.parser.Node; import me.geso.jtt.parser.NodeType; import me.geso.jtt.tt.TTSyntax; import org.junit.Test;
public void testAndAnd() throws ParserError { Node node = parse("[% true && false %]"); assertEquals( "(template (expression (andand (true) (false))))", node.toString()); } // left AND @Test public void testLooseAnd() throws ParserError { assertEquals( "(template (expression (andand (true) (false))))", parse("[% true AND false %]").toString()); assertEquals( "(template (expression (andand (andand (true) (false)) (true))))", parse("[% true AND false AND true %]").toString()); } @Test public void testOrOr() throws ParserError { Node node = parse("[% true || false %]"); assertEquals( "(template (expression (oror (true) (false))))", node.toString()); } @Test public void testLooseOr() throws ParserError { Node node = parse("[% true OR false %]"); assertEquals( "(template (expression (oror (true) (false))))", node.toString()); } @Test public void testNE() throws ParserError { Node node = parse("[% true != false %]"); assertEquals( "(template (expression (ne (true) (false))))", node.toString()); } @Test public void testDollarVar() throws ParserError { Node node = parse("[% list.$var %]"); assertEquals( "(template (expression (attribute (ident list) (dollarvar var))))", node.toString()); } @Test public void testArrayIndex() throws ParserError { assertEquals( "(template (expression (attribute (ident list) (dollarvar var))))", parse("[% list[$var] %]").toString()); assertEquals( "(template (expression (attribute (attribute (ident list) (dollarvar var)) (ident boo))))", parse("[% list[$var][boo] %]").toString()); assertEquals( "(template (expression (attribute (ident list) (ident var))))", parse("[% list[var] %]").toString()); } @Test public void testLoop() throws ParserError { assertEquals( "(template (expression (loop_index)))", parse("[% loop %]").toString()); } @Test public void testLoopIndex() throws ParserError { assertEquals( "(template (expression (loop_index)))", parse("[% loop %]").toString()); } @Test public void testLoopCount() throws ParserError { assertEquals( "(template (expression (loop_count)))", parse("[% loop.count %]").toString()); } @Test public void testLoopHasNext() throws ParserError { assertEquals( "(template (expression (loop_has_next)))", parse("[% loop.has_next %]").toString()); } @Test public void testFile() throws ParserError { assertEquals( "(template (expression (string -)))", parse("[% __FILE__ %]").toString()); } @Test public void testLine() throws ParserError { assertEquals( "(template (expression (integer 1)) (raw_string \n) (expression (integer 2)))", parse("[% __LINE__ %]\n[% __LINE__ %]").toString()); } @Test public void testInclude2() throws ParserError { assertEquals( "(template (include (string hoge.tt) (ident foo) (ident bar)))", parse("[% INCLUDE \"hoge.tt\" WITH foo=bar %]").toString()); } @Test public void testWrapper() throws ParserError { assertEquals( "(template (wrapper (string foo.tt) (template (raw_string ohoho))))", parse("[% WRAPPER \"foo.tt\" %]ohoho[% END %]").toString()); } private Node parse(String sourceString) throws ParserError {
Syntax syntax = new TTSyntax("[%", "%]");
6
52North/SensorPlanningService
52n-sps-api/src/test/java/org/n52/sps/util/nodb/InMemorySensorConfigurationRepositoryTest.java
[ "public abstract class SensorPlugin implements ResultAccessAvailabilityDescriptor, ResultAccessServiceReference {\r\n\r\n protected SensorConfiguration configuration;\r\n\r\n protected SensorTaskService sensorTaskService;\r\n \r\n protected SensorPlugin() {\r\n // allow default constructor for decoration\r\n }\r\n\r\n public SensorPlugin(SensorTaskService sensorTaskService, SensorConfiguration configuration) throws InternalServiceException {\r\n this.configuration = configuration;\r\n this.sensorTaskService = sensorTaskService;\r\n sensorTaskService.setProcedure(this);\r\n }\r\n\r\n public final String getProcedure() {\r\n return configuration.getProcedure();\r\n }\r\n\r\n public SensorTaskService getSensorTaskService() {\r\n return sensorTaskService;\r\n }\r\n\r\n public void setSensorTaskService(SensorTaskService sensorTaskService) {\r\n this.sensorTaskService = sensorTaskService;\r\n }\r\n\r\n /**\r\n * Delegate submit tasking request to sensor instance for execution. The execution can fail for many\r\n * reasons so implementors may consider exception handling by adding each occuring exception to the passed\r\n * {@link OwsExceptionReport} which will be thrown by the SPS framework afterwards.<br>\r\n * <br>\r\n * A {@link SensorTask} instance shall be created by the plugin's {@link SensorTaskService} which takes\r\n * care of storing the task instance into the SPS's {@link SensorTaskRepository}. Once a sensor task is\r\n * created, the task service can be used to continously update the task within the underlying\r\n * {@link SensorTaskRepository}.\r\n * \r\n * @param submit\r\n * the tasking request\r\n * @param owsExceptionReport\r\n * a container collecting {@link OwsException}s to be thrown together as OWS Exception Report\r\n * (according to chapter 8 of [OGC 06-121r3]).\r\n * @return a SensorTask instance as a result of the Submit task\r\n * @throws OwsException\r\n * if an OwsException is thrown without execption reporting intent.\r\n */\r\n public abstract SensorTask submit(SubmitTaskingRequest submit, OwsExceptionReport owsExceptionReport) throws OwsException;\r\n\r\n /*\r\n * Let the SPS manage this kinds of functionality! Extend SensorPlugin interface only with those \r\n * kind of methods a SensorPlugin implementation can provide only!\r\n * \r\n * TODO add abstract getUpdateDescription mehthod\r\n * TODO add abstract cancel mehod\r\n * TODO add abstract feasibility method\r\n * TODO add abstract reservation methods\r\n * TODO add absrtact update methods\r\n */\r\n\r\n /**\r\n * Qualifies sensor's tasking characteristics accordingly. <br>\r\n * <br>\r\n * The SPS has to ask a {@link SensorPlugin} instance for a full qualified data component describing its\r\n * tasking parameters (e.g. AbstractDataComponentType must be qualified to a concrete type implementation\r\n * like DataRecordType). Implementors can make use of\r\n * {@link XMLBeansTools#qualifySubstitutionGroup(org.apache.xmlbeans.XmlObject, javax.xml.namespace.QName)}\r\n * <br>\r\n * <b>Example:</b>\r\n * \r\n * <pre>\r\n * {@code\r\n * public void getQualifiedDataComponent(AbstractDataComponentType componentToQualify) {\r\n * QName qname = new QName(\"http://www.opengis.net/swe/2.0\", \"DataRecord\");\r\n * XMLBeansTools.qualifySubstitutionGroup(componentToQualify, qname);\r\n * }\r\n * </pre>\r\n * \r\n * @param the\r\n * abstract data component to qualify\r\n */\r\n public abstract void qualifyDataComponent(AbstractDataComponentType componentToQualify);\r\n \r\n public abstract Availability getResultAccessibilityFor(SensorTask sensorTask);\r\n\r\n public String getSensorPluginType() {\r\n return configuration.getSensorPluginType();\r\n }\r\n\r\n public SensorConfiguration getSensorConfiguration() {\r\n return configuration;\r\n }\r\n\r\n public ResultAccessDataServiceReference getResultAccessDataServiceReference() {\r\n return configuration.getResultAccessDataService();\r\n }\r\n\r\n public SensorConfiguration mergeSensorConfigurations(SensorConfiguration sensorConfiguration) {\r\n // TODO Auto-generated method stub\r\n throw new UnsupportedOperationException(\"Not yet implemented.\");\r\n }\r\n\r\n @Override\r\n public final int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = prime * result + ( (getProcedure() == null) ? 0 : getProcedure().hashCode());\r\n return result;\r\n }\r\n\r\n @Override\r\n public final boolean equals(Object obj) {\r\n if (this == obj)\r\n return true;\r\n if (obj == null)\r\n return false;\r\n if (getClass() != obj.getClass())\r\n return false;\r\n SensorPlugin other = (SensorPlugin) obj;\r\n if (getProcedure() == null) {\r\n if (other.getProcedure() != null)\r\n return false;\r\n }\r\n else if ( !getProcedure().equals(other.getProcedure()))\r\n return false;\r\n return true;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"SensorPluginType: \").append(configuration.getSensorPluginType()).append(\", \");\r\n sb.append(\"Procedure: \").append(configuration.getProcedure());\r\n return sb.toString();\r\n }\r\n\r\n}\r", "public class SimpleSensorPluginTestInstance extends SensorPlugin {\r\n\r\n private static final Logger LOGGER = LoggerFactory.getLogger(SimpleSensorPluginTestInstance.class);\r\n \r\n private static final String PROCEDURE_DESCRIPTION_FORMAT = \"http://www.opengis.net/sensorML/2.0\";\r\n \r\n private static final String PROCEDURE = \"http://my.namespace.org/procedure/\";\r\n \r\n private static int procedureNumber = 0;\r\n \r\n private static final String PLUGIN_TYPE = \"test_procedure\";\r\n\r\n /**\r\n * Creates a plugin instance for testing. It creates its {@link InMemorySensorTaskRepository} instance.\r\n * \r\n * @return a very simple instance of {@link SensorPlugin} for testing purposes.\r\n * @throws InternalServiceException if instance creation fails\r\n */\r\n public static SensorPlugin createInstance() throws InternalServiceException {\r\n SensorTaskRepository taskRepository = new InMemorySensorTaskRepository();\r\n SensorTaskService taskService = new SensorTaskService(taskRepository);\r\n return new SimpleSensorPluginTestInstance(taskService, createSensorConfiguration());\r\n }\r\n \r\n /**\r\n * Creates a plugin instance for testing which is coupled to a {@link SensorInstanceProvider}'s configuration, \r\n * i.e. reuses the {@link SensorTaskRepository} instance from the instance provider to interact with tasks.\r\n * \r\n * @param sensorInstanceProvider a sensorProvider which provides access to a {@link SensorTaskRepository}\r\n * @return an instance of {@link SensorPlugin} for testing purposes.\r\n * @throws InternalServiceException if instance creation fails\r\n */\r\n public static SensorPlugin createInstance(SensorInstanceProvider sensorInstanceProvider) throws InternalServiceException {\r\n SensorTaskRepository taskRepository = sensorInstanceProvider.getSensorTaskRepository();\r\n SensorTaskService taskService = new SensorTaskService(taskRepository);\r\n return new SimpleSensorPluginTestInstance(taskService, createSensorConfiguration());\r\n }\r\n \r\n private static SensorConfiguration createSensorConfiguration() {\r\n SensorConfiguration configuration = new SensorConfiguration();\r\n configuration.setProcedure(PROCEDURE + ++procedureNumber);\r\n configuration.setSensorPluginType(PLUGIN_TYPE);\r\n SensorDescription sensorDescription = new SensorDescription(PROCEDURE_DESCRIPTION_FORMAT, \"http://my.link.com/\");\r\n configuration.addSensorDescription(sensorDescription);\r\n return configuration;\r\n }\r\n\r\n public static SensorPlugin createInstance(SensorTaskService sensorTaskService, SensorConfiguration sensorConfiguration) throws InternalServiceException {\r\n return new SimpleSensorPluginTestInstance(sensorTaskService, sensorConfiguration);\r\n }\r\n\r\n private SimpleSensorPluginTestInstance(SensorTaskService sensorTaskService, SensorConfiguration configuration) throws InternalServiceException {\r\n super(sensorTaskService, configuration);\r\n }\r\n\r\n public Availability getResultAccessibility() {\r\n LanguageStringType testMessage = LanguageStringType.Factory.newInstance();\r\n testMessage.setStringValue(\"no data available for testing purposes.\");\r\n return new DataNotAvailable(testMessage).getResultAccessibility();\r\n }\r\n\r\n public boolean isDataAvailable() {\r\n return false;\r\n }\r\n\r\n @Override\r\n public SensorTask submit(SubmitTaskingRequest submit, OwsExceptionReport owsExceptionReport) throws OwsException {\r\n LOGGER.warn(\"method does not contain test code.\");\r\n return null;\r\n }\r\n\r\n @Override\r\n public void qualifyDataComponent(AbstractDataComponentType componentToQualify) {\r\n LOGGER.warn(\"method does not contain test code.\");\r\n }\r\n\r\n @Override\r\n public Availability getResultAccessibilityFor(SensorTask sensorTask) {\r\n // TODO Auto-generated method stub\r\n return null;\r\n \r\n }\r\n \r\n public void setSensorConfiguration(SensorConfiguration sensorConfiguration) {\r\n this.configuration = sensorConfiguration;\r\n }\r\n\r\n}\r", "public class SensorConfiguration {\r\n\r\n private Long id; // database id\r\n\r\n private List<SensorOfferingType> sensorOfferings = new ArrayList<SensorOfferingType>();\r\n\r\n private List<SensorDescription> sensorDescriptions = new ArrayList<SensorDescription>();\r\n\r\n private String procedure;\r\n\r\n private String sensorPluginType;\r\n \r\n private XmlObject sensorSetup;\r\n\r\n private AbstractDataComponentType taskingParametersTemplate;\r\n\r\n private ResultAccessDataServiceReference resultAccessDataServiceTemplate;\r\n\r\n public SensorConfiguration() {\r\n // db serialization\r\n }\r\n\r\n Long getId() {\r\n return id;\r\n }\r\n\r\n void setId(Long id) {\r\n this.id = id;\r\n }\r\n \r\n public List<String> getSensorOfferingsAsString() {\r\n List<String> offerings = new ArrayList<String>();\r\n for (SensorOfferingType offeringType : sensorOfferings) {\r\n offerings.add(offeringType.xmlText());\r\n }\r\n return offerings;\r\n }\r\n\r\n public List<SensorOfferingType> getSensorOfferings() {\r\n return sensorOfferings;\r\n }\r\n \r\n public void setSensorOfferingsAsString(List<String> sensorOfferings) throws XmlException {\r\n this.sensorOfferings.clear();\r\n for (String sensorOffering : sensorOfferings) {\r\n this.sensorOfferings.add(SensorOfferingType.Factory.parse(sensorOffering));\r\n }\r\n }\r\n\r\n public void setSensorOfferings(List<SensorOfferingType> sensorOfferings) {\r\n this.sensorOfferings = sensorOfferings;\r\n }\r\n\r\n public boolean addSensorOffering(SensorOfferingType sensorOfferingType) {\r\n return sensorOfferings.add(sensorOfferingType);\r\n }\r\n\r\n public boolean removeSensorOffering(String offeringIdentifier) {\r\n for (SensorOfferingType sensorOffering : sensorOfferings) {\r\n if (sensorOffering.getIdentifier().equals(offeringIdentifier)) {\r\n return sensorOfferings.remove(sensorOffering);\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n public String getProcedure() {\r\n return procedure;\r\n }\r\n\r\n public void setProcedure(String procedure) {\r\n this.procedure = procedure;\r\n }\r\n\r\n public String getSensorPluginType() {\r\n return sensorPluginType;\r\n }\r\n\r\n public void setSensorPluginType(String sensorPluginType) {\r\n this.sensorPluginType = sensorPluginType;\r\n }\r\n\r\n public XmlObject getSensorSetup() {\r\n return sensorSetup;\r\n }\r\n \r\n public void setSensorSetup(XmlObject sensorSetup) {\r\n this.sensorSetup = sensorSetup;\r\n }\r\n \r\n public String getSensorSetupAsString() {\r\n return sensorSetup != null ? sensorSetup.xmlText(): null;\r\n }\r\n \r\n public void setSensorSetupAsString(String sensorSetup) throws XmlException {\r\n if (sensorSetup != null) {\r\n this.sensorSetup = XmlObject.Factory.parse(sensorSetup);\r\n }\r\n }\r\n \r\n public List<SensorDescription> getSensorDescriptions() {\r\n return sensorDescriptions;\r\n }\r\n\r\n public void setSensorDescriptions(List<SensorDescription> sensorDescriptions) {\r\n this.sensorDescriptions = sensorDescriptions;\r\n }\r\n\r\n public List<String> getSensorDescriptionUrisFor(String procedureDescriptionFormat) {\r\n List<String> descriptionUris = new ArrayList<String>();\r\n for (SensorDescription sensorDescription : sensorDescriptions) {\r\n if (sensorDescription.getProcedureDescriptionFormat().equals(procedureDescriptionFormat)) {\r\n descriptionUris.add(sensorDescription.getDownloadLink());\r\n }\r\n }\r\n return descriptionUris;\r\n }\r\n\r\n public boolean addSensorDescription(SensorDescription sensorDescription) {\r\n return sensorDescriptions.add(sensorDescription);\r\n }\r\n\r\n public boolean removeSensorDescription(SensorDescription sensorDescription) {\r\n return sensorDescriptions.remove(sensorDescription);\r\n }\r\n\r\n /**\r\n * @param procedureDescriptionFormat\r\n * the format of SensorDescription\r\n * @return <code>true</code> if the given format is available, <code>false</code> otherwise.\r\n */\r\n public boolean supportsProcedureDescriptionFormat(String procedureDescriptionFormat) {\r\n for (SensorDescription sensorDescription : sensorDescriptions) {\r\n if (sensorDescription.getProcedureDescriptionFormat().equals(procedureDescriptionFormat)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n public void setTaskingParametersTemplate(AbstractDataComponentType taskingParameters) {\r\n this.taskingParametersTemplate = taskingParameters;\r\n }\r\n\r\n /**\r\n * @return deep copy of configured tasking parameters to be used as template. The caller has to qualify\r\n * the returned {@link AbstractDataComponentType} to a corresponding Substitution type.\r\n */\r\n public AbstractDataComponentType getTaskingParametersTemplate() {\r\n return (AbstractDataComponentType) taskingParametersTemplate.copy();\r\n }\r\n\r\n public String getTaskingParameters() {\r\n return taskingParametersTemplate.xmlText();\r\n }\r\n\r\n public void setTaskingParameters(String taskingParameters) throws XmlException {\r\n this.taskingParametersTemplate = AbstractDataComponentType.Factory.parse(taskingParameters);\r\n }\r\n\r\n public ResultAccessDataServiceReference getResultAccessDataService() {\r\n return resultAccessDataServiceTemplate;\r\n }\r\n\r\n public void setResultAccessDataService(ResultAccessDataServiceReference resultAccessDataService) {\r\n this.resultAccessDataServiceTemplate = resultAccessDataService;\r\n }\r\n\r\n}\r", "public abstract class InternalServiceException extends Exception {\r\n \r\n private static final long serialVersionUID = -1598594769157092219L;\r\n \r\n public static final int BAD_REQUEST = 400;\r\n \r\n private List<String> detailedMessages = new ArrayList<String>();\r\n private String exceptionCode;\r\n private String locator;\r\n\r\n public InternalServiceException(String exceptionCode, String locator) {\r\n this.exceptionCode = exceptionCode;\r\n this.locator = locator;\r\n }\r\n\r\n public String getExceptionCode() {\r\n return exceptionCode;\r\n }\r\n\r\n public void setExceptionCode(String exceptionCode) {\r\n this.exceptionCode = exceptionCode;\r\n }\r\n\r\n public String getLocator() {\r\n return locator;\r\n }\r\n\r\n public void setLocator(String locator) {\r\n this.locator = locator;\r\n }\r\n\r\n public void addDetailedMessage(String detailedMessage) {\r\n detailedMessages.add(detailedMessage);\r\n }\r\n \r\n public Iterable<String> getDetailedMessages() {\r\n return detailedMessages;\r\n }\r\n\r\n public abstract int getHttpStatusCode();\r\n\r\n \r\n}\r", "public interface SensorConfigurationRepository {\r\n\r\n public void storeNewSensorConfiguration(SensorConfiguration sensorConfiguration);\r\n \r\n public void saveOrUpdateSensorConfiguration(SensorConfiguration sensorConfiguration);\r\n \r\n public void removeSensorConfiguration(SensorConfiguration sensorConfiguration);\r\n\r\n public SensorConfiguration getSensorConfiguration(String procedure);\r\n\r\n public Iterable<SensorConfiguration> getSensorConfigurations();\r\n\r\n public boolean containsSensorConfiguration(String procedure);\r\n\r\n}\r", "public class InMemorySensorConfigurationRepository implements SensorConfigurationRepository {\r\n \r\n private Map<String, SensorConfiguration> sensors = new HashMap<String, SensorConfiguration>();\r\n\r\n public void storeNewSensorConfiguration(SensorConfiguration sensorInstance) {\r\n sensors.put(sensorInstance.getProcedure(), sensorInstance);\r\n }\r\n \r\n public void saveOrUpdateSensorConfiguration(SensorConfiguration sensorInstance) {\r\n sensors.put(sensorInstance.getProcedure(), sensorInstance);\r\n }\r\n\r\n public void removeSensorConfiguration(SensorConfiguration sensorInstance) {\r\n sensors.remove(sensorInstance.getProcedure());\r\n }\r\n\r\n public SensorConfiguration getSensorConfiguration(String procedure) {\r\n return sensors.get(procedure);\r\n }\r\n\r\n public boolean containsSensorConfiguration(String procedure) {\r\n return sensors.containsKey(procedure);\r\n }\r\n \r\n public Iterable<SensorConfiguration> getSensorConfigurations() {\r\n return sensors.values();\r\n }\r\n\r\n}\r" ]
import org.junit.Test; import org.n52.sps.sensor.SensorPlugin; import org.n52.sps.sensor.SimpleSensorPluginTestInstance; import org.n52.sps.sensor.model.SensorConfiguration; import org.n52.sps.service.InternalServiceException; import org.n52.sps.store.SensorConfigurationRepository; import org.n52.sps.util.nodb.InMemorySensorConfigurationRepository; import static org.junit.Assert.*; import org.junit.Before;
/** * Copyright (C) 2012-${latestYearOfContribution} 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package org.n52.sps.util.nodb; public class InMemorySensorConfigurationRepositoryTest { private SensorConfigurationRepository repository; @Before public void setUp() {
repository = new InMemorySensorConfigurationRepository();
5
Zhuinden/simple-stack
simple-stack/src/test/java/com/zhuinden/simplestack/ScopeLookupModeTest.java
[ "public interface Action {\n public void doSomething();\n}", "public interface HasParentServices\n extends ScopeKey.Child {\n void bindServices(ServiceBinder serviceBinder);\n}", "public interface HasServices\n extends ScopeKey {\n void bindServices(ServiceBinder serviceBinder);\n}", "public class ServiceProvider\n implements ScopedServices {\n @Override\n public void bindServices(@Nonnull ServiceBinder serviceBinder) {\n Object key = serviceBinder.getKey();\n if(key instanceof HasServices) {\n ((HasServices) key).bindServices(serviceBinder);\n return;\n }\n if(key instanceof HasParentServices) {\n ((HasParentServices) key).bindServices(serviceBinder);\n //noinspection UnnecessaryReturnStatement\n return;\n }\n }\n}", "public class TestKey\n implements Parcelable {\n public final String name;\n\n public TestKey(String name) {\n this.name = name;\n }\n\n protected TestKey(Parcel in) {\n name = in.readString();\n }\n\n public static final Creator<TestKey> CREATOR = new Creator<TestKey>() {\n @Override\n public TestKey createFromParcel(Parcel in) {\n return new TestKey(in);\n }\n\n @Override\n public TestKey[] newArray(int size) {\n return new TestKey[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if(this == o) {\n return true;\n }\n if(o == null || getClass() != o.getClass()) {\n return false;\n }\n TestKey key = (TestKey) o;\n return name.equals(key.name);\n }\n\n @Override\n public int hashCode() {\n return name.hashCode();\n }\n\n @Override\n public String toString() {\n return String.format(\"%s{%h}\", name, this);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(name);\n }\n}", "public static void assertThrows(Action action) {\n try {\n action.doSomething();\n Assert.fail(\"Did not throw exception.\");\n } catch(Exception e) {\n // OK!\n }\n}" ]
import static org.assertj.core.api.Assertions.assertThat; import android.os.Parcel; import com.zhuinden.simplestack.helpers.Action; import com.zhuinden.simplestack.helpers.HasParentServices; import com.zhuinden.simplestack.helpers.HasServices; import com.zhuinden.simplestack.helpers.ServiceProvider; import com.zhuinden.simplestack.helpers.TestKey; import org.junit.Test; import java.util.List; import javax.annotation.Nonnull; import static com.zhuinden.simplestack.helpers.AssertionHelper.assertThrows;
@Nonnull @Override public String getScopeTag() { return name; } @Nonnull @Override public List<String> getParentScopes() { return History.of("parent1"); } } class Key2 extends TestKey implements HasServices, HasParentServices { Key2(String name) { super(name); } protected Key2(Parcel in) { super(in); } @Override public void bindServices(ServiceBinder serviceBinder) { if("parent2".equals(serviceBinder.getScopeTag())) { serviceBinder.addService("parentService2", parentService2); } else if(name.equals(serviceBinder.getScopeTag())) { serviceBinder.addService("service2", service2); } } @Nonnull @Override public String getScopeTag() { return name; } @Nonnull @Override public List<String> getParentScopes() { return History.of("parent2"); } } backstack.setup(History.of(new Key1("beep"), new Key2("boop"))); assertThat(backstack.canFindFromScope("boop", "service")).isFalse(); backstack.setStateChanger(new StateChanger() { @Override public void handleStateChange(@Nonnull StateChange stateChange, @Nonnull Callback completionCallback) { completionCallback.stateChangeComplete(); } }); // default (ALL) assertThat(backstack.canFindFromScope("beep", "service1")).isTrue(); assertThat(backstack.canFindFromScope("beep", "service2")).isFalse(); assertThat(backstack.canFindFromScope("beep", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("beep", "parentService2")).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service1")).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service2")).isFalse(); assertThat(backstack.canFindFromScope("parent1", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("parent1", "parentService2")).isFalse(); assertThat(backstack.canFindFromScope("boop", "service1")).isTrue(); assertThat(backstack.canFindFromScope("boop", "service2")).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService2")).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service1")).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service2")).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService1")).isTrue(); assertThat(backstack.canFindFromScope("parent2", "parentService2")).isTrue(); // ALL specified assertThat(backstack.canFindFromScope("beep", "service1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("beep", "service2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("beep", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("beep", "parentService2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service1", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent1", "parentService2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("boop", "service1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("boop", "service2", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService2", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service2", ScopeLookupMode.ALL)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "parentService2", ScopeLookupMode.ALL)).isTrue(); // EXPLICIT specified assertThat(backstack.canFindFromScope("beep", "service1", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("beep", "service2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("beep", "parentService1", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("beep", "parentService2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "service2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent1", "parentService1", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("parent1", "parentService2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("boop", "service1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("boop", "service2", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("boop", "parentService1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("boop", "parentService2", ScopeLookupMode.EXPLICIT)).isTrue(); assertThat(backstack.canFindFromScope("parent2", "service1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "service2", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService1", ScopeLookupMode.EXPLICIT)).isFalse(); assertThat(backstack.canFindFromScope("parent2", "parentService2", ScopeLookupMode.EXPLICIT)).isTrue(); // default (ALL)
assertThrows(new Action() {
5
idega/com.idega.block.category
src/java/com/idega/block/category/business/FolderBlockBusinessBean.java
[ "public interface ICInformationCategory extends TreeableEntity,com.idega.block.category.data.InformationCategory\n{\n public void addCategoryToInstance(int p0)throws java.sql.SQLException;\n public int getChildCount();\n public java.util.Iterator getChildrenIterator();\n public java.util.Iterator getChildrenIterator(java.lang.String p0);\n public java.sql.Timestamp getCreated();\n public boolean getDeleted();\n public int getDeletedBy();\n public java.sql.Timestamp getDeletedWhen();\n public java.lang.String getDescription();\n public int getICObjectId();\n public java.lang.String getName();\n public int getOwnerFolderId();\n public java.lang.String getType();\n public boolean getValid();\n public void removeCategoryFromInstance(int p0)throws java.sql.SQLException;\n public void setCreated(java.sql.Timestamp p0);\n public void setDeleted(int p0,boolean p1);\n public void setDescription(java.lang.String p0);\n public void setFolderSpecific(int p0);\n public void setGlobal()throws java.sql.SQLException;\n public void setICObjectId(int p0);\n public void setName(java.lang.String p0);\n public void setType(java.lang.String p0);\n public void setValid(boolean p0);\n}", "public interface ICInformationCategoryHome extends com.idega.data.IDOHome\n{\n public ICInformationCategory create() throws javax.ejb.CreateException;\n public ICInformationCategory createLegacy();\n public ICInformationCategory findByPrimaryKey(Object pk) throws javax.ejb.FinderException;\n public ICInformationCategory findByPrimaryKey(int id) throws javax.ejb.FinderException;\n public ICInformationCategory findByPrimaryKeyLegacy(int id) throws java.sql.SQLException;\n public java.util.Collection findAvailableCategories(int p0,int p1)throws javax.ejb.FinderException;\n public java.util.Collection findAvailableTopNodeCategories(int p0,int p1)throws javax.ejb.FinderException;\n public boolean hasAvailableCategory(int icObjectID) throws IDOException;\n}", "public interface ICInformationCategoryTranslation extends com.idega.data.IDOEntity\n{\n public java.lang.String getDescription();\n public com.idega.core.localisation.data.ICLocale getLocale();\n public java.lang.String getName();\n public com.idega.block.category.data.ICInformationCategory getSuperInformationCategory();\n public void initializeAttributes();\n public void setDescription(java.lang.String p0);\n public void setLocale(int p0);\n public void setLocale(com.idega.core.localisation.data.ICLocale p0);\n public void setName(java.lang.String p0);\n public void setSuperInformationCategory(int p0);\n public void setSuperInformationCategory(com.idega.block.category.data.ICInformationCategory p0);\n}", "public interface ICInformationCategoryTranslationHome extends com.idega.data.IDOHome\n{\n public ICInformationCategoryTranslation create() throws javax.ejb.CreateException;\n public ICInformationCategoryTranslation findByPrimaryKey(Object pk) throws javax.ejb.FinderException;\n public java.util.Collection findAllByCategory(int p0)throws javax.ejb.FinderException;\n public ICInformationCategoryTranslation findByCategoryAndLocale(int p0,int p1)throws javax.ejb.FinderException;\n\n}", "public interface ICInformationFolder extends com.idega.data.IDOLegacyEntity,com.idega.block.category.data.InformationFolder\n{\n public java.sql.Timestamp getCreated();\n public boolean getDeleted();\n public int getDeletedBy();\n public java.sql.Timestamp getDeletedWhen();\n public java.lang.String getDescription();\n public com.idega.block.category.data.ICInformationFolder getEntity();\n public int getICObjectId();\n public int getLocaleId();\n public java.lang.String getName();\n public int getOwnerGroupID();\n public com.idega.block.category.data.ICInformationFolder getParent();\n public int getParentId();\n public java.lang.String getType();\n public boolean getValid();\n public void setCreated(java.sql.Timestamp p0);\n public void setDeleted(boolean p0);\n public void setDescription(java.lang.String p0);\n public void setICObjectId(int p0);\n public void setLocaleId(int p0);\n public void setName(java.lang.String p0);\n public void setOwnerGroupID(int p0);\n public void setParentId(int p0);\n public void setType(java.lang.String p0);\n public void setValid(boolean p0);\n}" ]
import java.rmi.RemoteException; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.category.data.ICInformationCategory; import com.idega.block.category.data.ICInformationCategoryHome; import com.idega.block.category.data.ICInformationCategoryTranslation; import com.idega.block.category.data.ICInformationCategoryTranslationHome; import com.idega.block.category.data.ICInformationFolder; import com.idega.block.category.data.InformationCategory; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.business.IBOServiceBean; import com.idega.core.component.data.ICObjectInstance; import com.idega.core.component.data.ICObjectInstanceHome; import com.idega.core.localisation.business.ICLocaleBusiness; import com.idega.data.EntityFinder; import com.idega.data.GenericEntity; import com.idega.data.IDOException; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.data.IDORemoveRelationshipException; import com.idega.data.IDOStoreException; import com.idega.idegaweb.IWApplicationContext; import com.idega.presentation.IWContext; import com.idega.util.IWTimestamp;
package com.idega.block.category.business; /** * <p>Title: idegaWeb</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: idega</p> * @author <a href="gummi@idega.is">Gudmundur Agust Saemundsson</a> * @version 1.0 */ public class FolderBlockBusinessBean extends IBOServiceBean implements FolderBlockBusiness { public FolderBlockBusinessBean() { } public static FolderBlockBusinessBean getInstance(IWApplicationContext iwac) throws IBOLookupException { return (FolderBlockBusinessBean) IBOLookup.getServiceInstance(iwac,FolderBlockBusiness.class); }
public ICInformationFolder getInstanceWorkeFolder(int icObjectInstanceId, int icObjectId, int localeId, boolean autocreate) {
4
ghelmling/beeno
src/java/meetup/beeno/Criteria.java
[ "public class ColumnMatchFilter implements Filter {\n\n\t/** Comparison operators. */\n\tpublic enum CompareOp {\n\t\t/** less than */\n\t\tLESS,\n\t\t/** less than or equal to */\n\t\tLESS_OR_EQUAL,\n\t\t/** equals */\n\t\tEQUAL,\n\t\t/** not equal */\n\t\tNOT_EQUAL,\n\t\t/** greater than or equal to */\n\t\tGREATER_OR_EQUAL,\n\t\t/** greater than */\n\t\tGREATER;\n\t}\n\n\tprivate byte[] columnName;\n\tprivate CompareOp compareOp;\n\tprivate byte[] value;\n\tprivate boolean filterIfColumnMissing;\n\tprivate boolean columnSeen = false;\n\tprivate boolean columnFiltered = false;\n\n\tpublic ColumnMatchFilter() {\n\t\t// for Writable\n\t}\n\n\t/**\n\t * Constructor.\n\t * \n\t * @param columnName\n\t * name of column\n\t * @param compareOp\n\t * operator\n\t * @param value\n\t * value to compare column values against\n\t */\n\tpublic ColumnMatchFilter( final byte[] columnName, final CompareOp compareOp,\n\t\t\tfinal byte[] value ) {\n\t\tthis(columnName, compareOp, value, true);\n\t}\n\n\t/**\n\t * Constructor.\n\t * \n\t * @param columnName\n\t * name of column\n\t * @param compareOp\n\t * operator\n\t * @param value\n\t * value to compare column values against\n\t * @param filterIfColumnMissing\n\t * if true then we will filter rows that don't have the column.\n\t */\n\tpublic ColumnMatchFilter( final byte[] columnName, final CompareOp compareOp,\n\t\t\tfinal byte[] value, boolean filterIfColumnMissing ) {\n\t\tthis.columnName = columnName;\n\t\tthis.compareOp = compareOp;\n\t\tthis.value = value;\n\t\tthis.filterIfColumnMissing = filterIfColumnMissing;\n\t}\n\n\t/**\n\t * Constructor.\n\t * \n\t * @param columnName\n\t * name of column\n\t * @param compareOp\n\t * operator\n\t * @param comparator\n\t * Comparator to use.\n\t */\n\tpublic ColumnMatchFilter( final byte[] columnName, final CompareOp compareOp ) {\n\t\tthis(columnName, compareOp, true);\n\t}\n\n\t/**\n\t * Constructor.\n\t * \n\t * @param columnName\n\t * name of column\n\t * @param compareOp\n\t * operator\n\t * @param comparator\n\t * Comparator to use.\n\t * @param filterIfColumnMissing\n\t * if true then we will filter rows that don't have the column.\n\t */\n\tpublic ColumnMatchFilter( final byte[] columnName, final CompareOp compareOp,\n\t\t\tboolean filterIfColumnMissing ) {\n\t\tthis.columnName = columnName;\n\t\tthis.compareOp = compareOp;\n\t\tthis.filterIfColumnMissing = filterIfColumnMissing;\n\t}\n\n\tpublic boolean filterRowKey( final byte[] rowKey, int offset, int length ) {\n\t\treturn false;\n\t}\n\n\tpublic Filter.ReturnCode filterKeyValue( KeyValue v ) {\n\t\tif (v.matchingColumn(this.columnName)) {\n\t\t\tbyte[] val = v.getValue();\n\t\t\tif (val != null && val.length > 0)\n\t\t\t\tthis.columnSeen = true;\n\t\t\tif (filterColumnValue(v.getValue())) {\n\t\t\t\tthis.columnFiltered = true;\n\t\t\t\treturn Filter.ReturnCode.NEXT_ROW;\n\t\t\t}\n\t\t}\n\n\t\treturn Filter.ReturnCode.INCLUDE;\n\t}\n\n\tprivate boolean filterColumnValue( final byte[] data ) {\n\t\tint compareResult;\n\t\tcompareResult = compare(value, data);\n\n\t\tswitch (compareOp) {\n\t\tcase LESS:\n\t\t\treturn compareResult <= 0;\n\t\tcase LESS_OR_EQUAL:\n\t\t\treturn compareResult < 0;\n\t\tcase EQUAL:\n\t\t\treturn compareResult != 0;\n\t\tcase NOT_EQUAL:\n\t\t\treturn compareResult == 0;\n\t\tcase GREATER_OR_EQUAL:\n\t\t\treturn compareResult > 0;\n\t\tcase GREATER:\n\t\t\treturn compareResult >= 0;\n\t\tdefault:\n\t\t\tthrow new RuntimeException(\"Unknown Compare op \" + compareOp.name());\n\t\t}\n\t}\n\n\tpublic boolean filterAllRemaining() {\n\t\treturn false;\n\t}\n\n\tpublic boolean filterRow() {\n\t\tif (columnFiltered)\n\t\t\treturn true;\n\t\t\n\t\tif (filterIfColumnMissing && !columnSeen)\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tprivate int compare( final byte[] b1, final byte[] b2 ) {\n\t\tint len = Math.min(b1.length, b2.length);\n\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tif (b1[i] != b2[i]) {\n\t\t\t\treturn b1[i] - b2[i];\n\t\t\t}\n\t\t}\n\t\treturn b1.length - b2.length;\n\t}\n\n\tpublic void reset() {\n\t\tthis.columnSeen = false;\n\t\tthis.columnFiltered = false;\n\t}\n\n\tpublic void readFields( final DataInput in ) throws IOException {\n\t\tint valueLen = in.readInt();\n\t\tif (valueLen > 0) {\n\t\t\tvalue = new byte[valueLen];\n\t\t\tin.readFully(value);\n\t\t}\n\t\tcolumnName = Bytes.readByteArray(in);\n\t\tcompareOp = CompareOp.valueOf(in.readUTF());\n\t\tfilterIfColumnMissing = in.readBoolean();\n\t}\n\n\tpublic void write( final DataOutput out ) throws IOException {\n\t\tif (value == null) {\n\t\t\tout.writeInt(0);\n\t\t}\n\t\telse {\n\t\t\tout.writeInt(value.length);\n\t\t\tout.write(value);\n\t\t}\n\t\tBytes.writeByteArray(out, columnName);\n\t\tout.writeUTF(compareOp.name());\n\t\tout.writeBoolean(filterIfColumnMissing);\n\t}\n\n}", "public class WhileMatchFilter implements Filter {\n\tprivate boolean filterAllRemaining = false;\n\tprivate Filter filter;\n\n\tpublic WhileMatchFilter() {\n\t\tsuper();\n\t}\n\n\tpublic WhileMatchFilter( Filter filter ) {\n\t\tthis.filter = filter;\n\t}\n\n\tpublic void reset() {\n\t\t// no state.\n\t}\n\n\tprivate void changeFAR( boolean value ) {\n\t\tfilterAllRemaining = filterAllRemaining || value;\n\t}\n\n\tpublic boolean filterRowKey( byte[] buffer, int offset, int length ) {\n\t\tchangeFAR(filter.filterRowKey(buffer, offset, length));\n\t\treturn filterAllRemaining();\n\t}\n\n\tpublic boolean filterAllRemaining() {\n\t\treturn this.filterAllRemaining || this.filter.filterAllRemaining();\n\t}\n\n\tpublic ReturnCode filterKeyValue( KeyValue v ) {\n\t\treturn filter.filterKeyValue(v);\n\t}\n\n\tpublic boolean filterRow() {\n\t\tchangeFAR(filter.filterRow());\n\t\treturn filterAllRemaining();\n\t}\n\n\tpublic void write( DataOutput out ) throws IOException {\n\t\tout.writeUTF(this.filter.getClass().getName());\n\t\tthis.filter.write(out);\n\t}\n\n\tpublic void readFields( DataInput in ) throws IOException {\n\t\tString className = in.readUTF();\n\t\ttry {\n\t\t\tthis.filter = (Filter) (Class.forName(className).newInstance());\n\t\t\tthis.filter.readFields(in);\n\t\t}\n\t\tcatch (InstantiationException e) {\n\t\t\tthrow new RuntimeException(\"Failed deserialize.\", e);\n\t\t}\n\t\tcatch (IllegalAccessException e) {\n\t\t\tthrow new RuntimeException(\"Failed deserialize.\", e);\n\t\t}\n\t\tcatch (ClassNotFoundException e) {\n\t\t\tthrow new RuntimeException(\"Failed deserialize.\", e);\n\t\t}\n\t}\n}", "public class EntityInfo {\n\tprivate Class entityClass = null;\n\tprivate String table = null;\n\tprivate PropertyDescriptor keyProperty = null;\n\t\n\tprivate List<FieldMapping> mappedProps = new ArrayList<FieldMapping>();\n\tprivate Map<String, PropertyDescriptor> propertiesByName = new HashMap<String, PropertyDescriptor>();\n\tprivate Map<PropertyDescriptor, FieldMapping> fieldsByProperty = new HashMap<PropertyDescriptor, FieldMapping>();\n\tprivate Map<PropertyDescriptor, PropertyType> typesByProperty = new HashMap<PropertyDescriptor, PropertyType>();\n\tprivate Map<PropertyDescriptor, List<IndexMapping>> indexesByProperty = new HashMap<PropertyDescriptor, List<IndexMapping>>();\n\t\n\tpublic EntityInfo(Class clazz) {\n\t\tthis.entityClass = clazz;\n\t}\n\t\n\tpublic Class getEntityClass() { return this.entityClass; }\n\t\n\t/**\n\t * Returns the HBase table identified by the entity's {@link HEntity} \n\t * annotation.\n\t * @return\n\t */\n\tpublic String getTablename() { return this.table; }\n\tpublic void setTablename(String tablename) { this.table = tablename; }\n\t\n\t/**\n\t * Returns the java bean properties mapped by the entity's {@link HRowKey}\n\t * annotation.\n\t * \n\t * @return\n\t */\n\tpublic PropertyDescriptor getKeyProperty() { return this.keyProperty; }\n\tpublic void setKeyProperty(PropertyDescriptor prop) { this.keyProperty = prop; }\n\t\n\tpublic void addProperty(HProperty mapping, PropertyDescriptor prop, PropertyType type) {\n\t\tFieldMapping field = FieldMapping.get(mapping, prop);\n\t\tthis.mappedProps.add(field);\n\t\tthis.propertiesByName.put(prop.getName(), prop);\n\t\tthis.fieldsByProperty.put(prop, field);\n\t\tif (type != null)\n\t\t\tthis.typesByProperty.put(prop, type);\n\t\t\n\t\t// !!! ADD HANDLING FOR INDEX ANNOTATIONS !!!\n\t\tHIndex[] indexes = mapping.indexes();\n\t\tif (indexes != null && indexes.length > 0) {\n\t\t\tfor (HIndex idx : indexes)\n\t\t\t\taddIndex( new IndexMapping(this.table, field, idx), prop );\n\t\t}\n\t}\n\t\n\tpublic void addIndex(IndexMapping index, PropertyDescriptor prop) {\n\t\tList<IndexMapping> curIndexes = this.indexesByProperty.get(prop);\n\t\tif (curIndexes == null) {\n\t\t\tcurIndexes = new ArrayList<IndexMapping>();\n\t\t\tthis.indexesByProperty.put(prop, curIndexes);\n\t\t}\n\t\t\n\t\tcurIndexes.add(index);\n\t}\n\t\n\tpublic PropertyDescriptor getFieldProperty(String fieldname) {\n\t\tfor (FieldMapping mapping : this.mappedProps) {\n\t\t\tif (mapping.matches(fieldname)) {\n\t\t\t\treturn mapping.getBeanProperty();\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\t\n\tpublic List<FieldMapping> getMappedFields() { return this.mappedProps; }\n\t\n\tpublic PropertyDescriptor getProperty(String propName) {\n\t\treturn this.propertiesByName.get(propName);\n\t}\n\n\tpublic FieldMapping getPropertyMapping(String propName) {\n\t\tif (this.propertiesByName.get(propName) != null) {\n\t\t\treturn this.fieldsByProperty.get( this.propertiesByName.get(propName) );\n\t\t}\n\n\t\treturn null;\n\t}\n\t\n\tpublic PropertyType getPropertyType(PropertyDescriptor prop) {\n\t\treturn this.typesByProperty.get(prop);\n\t}\n\t\n\tpublic List<IndexMapping> getPropertyIndexes(String propname) {\n\t\tPropertyDescriptor prop = getProperty(propname);\n\t\tif (prop != null)\n\t\t\treturn getPropertyIndexes(prop);\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic List<IndexMapping> getPropertyIndexes(PropertyDescriptor prop) {\n\t\treturn this.indexesByProperty.get(prop);\n\t}\n\t\n\tpublic IndexMapping getFirstPropertyIndex(String propname) {\n\t\tPropertyDescriptor prop = getProperty(propname);\n\t\tif (prop != null)\n\t\t\treturn getFirstPropertyIndex(prop);\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic IndexMapping getFirstPropertyIndex(PropertyDescriptor prop) {\n\t\tList<IndexMapping> indexes = getPropertyIndexes(prop);\n\t\tif (indexes != null && indexes.size() > 0)\n\t\t\treturn indexes.get(0);\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic Map<PropertyDescriptor, List<IndexMapping>> getIndexesByProperty() {\n\t\treturn this.indexesByProperty;\n\t}\n\t\n\t/**\n\t * Returns all index mappings present on this entity class\n\t * @return\n\t */\n\tpublic List<IndexMapping> getMappedIndexes() {\n\t\tList<IndexMapping> indexes = new ArrayList<IndexMapping>(this.indexesByProperty.size());\n\t\tfor (List<IndexMapping> propIndexes : this.indexesByProperty.values())\n\t\t\tindexes.addAll(propIndexes);\n\t\t\n\t\treturn indexes;\n\t}\n\t\n\tpublic boolean isGettable(String fieldname) {\n\t\tPropertyDescriptor prop = getFieldProperty(fieldname);\n\t\treturn (prop != null && prop.getReadMethod() != null);\n\t}\n\n\tpublic boolean isSettable(String fieldname) {\n\t\tPropertyDescriptor prop = getFieldProperty(fieldname);\n\t\treturn (prop != null && prop.getWriteMethod() != null);\n\t}\n\t\n\tpublic Collection<String> getColumnFamilyNames() {\n\t\tif (this.columnFamilies == null) {\n\t\t\tSet<String> names = new HashSet<String>();\n\t\t\tfor (FieldMapping mapping : this.mappedProps)\n\t\t\t\tnames.add(mapping.getFamily());\n\t\t\t\n\t\t\tthis.columnFamilies = names;\n\t\t}\n\t\t\n\t\treturn this.columnFamilies;\n\t}\n\tprivate Set<String> columnFamilies = null;\n}", "public class FieldMapping {\n\tprotected String family = null;\n\tprotected String column = null;\n\tprotected String fieldname = null;\n\tprotected PropertyDescriptor beanProperty = null;\n\tpublic FieldMapping(HProperty prop, PropertyDescriptor beanProperty) {\n\t\tthis.family = prop.family();\n\t\tthis.column = prop.name();\n\t\tthis.fieldname = this.family+\":\"+this.column;\n\t\tthis.beanProperty = beanProperty;\n\t}\n\n\tpublic boolean matches(String fieldname) { return this.fieldname.equals(fieldname); }\n\tpublic PropertyDescriptor getBeanProperty() { return this.beanProperty; }\n\tpublic String getFamily() { return this.family; }\n\tpublic String getColumn() { return this.column; }\n\tpublic String getFieldName() { return this.fieldname; }\n\n\tpublic static FieldMapping get(HProperty prop, PropertyDescriptor beanProperty) {\n\t\tif (Map.class.isAssignableFrom(beanProperty.getPropertyType())) {\n\t\t\treturn new MapField(prop, beanProperty);\n\t\t}\n\t\telse if (Collection.class.isAssignableFrom(beanProperty.getPropertyType())) {\n\t\t\treturn new ListField(prop, beanProperty);\n\t\t}\n\n\t\treturn new FieldMapping(prop, beanProperty);\n\t}\n}", "public class MappingException extends HBaseException {\n\n\tprivate Class entityClass = null;\n\t\n\tpublic MappingException( Class entityClass ) {\n\t\tthis.entityClass = entityClass;\n\t}\n\n\tpublic MappingException( Class entityClass, String message ) {\n\t\tsuper(message);\n\t\tthis.entityClass = entityClass;\n\t}\n\n\tpublic MappingException( Class entityClass, Throwable cause ) {\n\t\tsuper(cause);\n\t\tthis.entityClass = entityClass;\n\t}\n\n\tpublic MappingException( Class entityClass, String message, Throwable cause ) {\n\t\tsuper(message, cause);\n\t\tthis.entityClass = entityClass;\n\t}\n\n\tpublic Class getEntityClass() { return this.entityClass; }\n}", "public class IOUtil {\n\tpublic static enum VALUE_TYPE {STRING, INT, LONG, FLOAT, DOUBLE, DATE, ENUM, OBJECT};\n\tprivate static Logger log = Logger.getLogger(IOUtil.class);\n\n\tpublic static void writeNullable( ObjectOutput out, Object value ) throws IOException {\n\t\tif (value == null) {\n\t\t\tout.writeBoolean(true);\n\t\t}\n\t\telse {\n\t\t\tout.writeBoolean(false);\n\t\t\tif (value instanceof String)\n\t\t\t\tout.writeUTF((String)value);\n\t\t\telse if (value instanceof Integer)\n\t\t\t\tout.writeInt(((Integer)value).intValue());\n\t\t\telse if (value instanceof Float)\n\t\t\t\tout.writeFloat(((Float)value).floatValue());\n\t\t\telse if (value instanceof Double)\n\t\t\t\tout.writeDouble(((Double)value).doubleValue());\n\t\t\telse if (value instanceof Long)\n\t\t\t\tout.writeLong(((Long)value).longValue());\n\t\t\telse if (value instanceof Date)\n\t\t\t\tout.writeLong(((Date)value).getTime());\n\t\t\telse if (value instanceof Enum)\n\t\t\t\tout.writeUTF(((Enum)value).name());\n\t\t\telse\n\t\t\t\tout.writeObject(value);\n\t\t}\n\t}\n\t\n\tpublic static void writeNullableWithType( ObjectOutput out, Object value ) throws IOException {\n\t\tif (value == null) {\n\t\t\tout.writeBoolean(true);\n\t\t}\n\t\telse {\n\t\t\tout.writeBoolean(false);\n\t\t\tif (value instanceof String) {\n\t\t\t\tout.writeUTF(VALUE_TYPE.STRING.name());\n\t\t\t\tout.writeUTF((String)value);\n\t\t\t}\n\t\t\telse if (value instanceof Integer) {\n\t\t\t\tout.writeUTF(VALUE_TYPE.INT.name());\t\t\t\t\n\t\t\t\tout.writeInt(((Integer)value).intValue());\n\t\t\t}\n\t\t\telse if (value instanceof Float) {\n\t\t\t\tout.writeUTF(VALUE_TYPE.FLOAT.name());\n\t\t\t\tout.writeFloat(((Float)value).floatValue());\n\t\t\t}\n\t\t\telse if (value instanceof Double) {\n\t\t\t\tout.writeUTF(VALUE_TYPE.DOUBLE.name());\n\t\t\t\tout.writeDouble(((Double)value).doubleValue());\n\t\t\t}\n\t\t\telse if (value instanceof Long) {\n\t\t\t\tout.writeUTF(VALUE_TYPE.LONG.name());\n\t\t\t\tout.writeLong(((Long)value).longValue());\n\t\t\t} \n\t\t\telse if (value instanceof Date) {\n\t\t\t\tout.writeUTF(VALUE_TYPE.DATE.name());\n\t\t\t\tout.writeLong(((Date)value).getTime());\n\t\t\t} \n\t\t\telse if (value instanceof Enum) {\n\t\t\t\tout.writeUTF(VALUE_TYPE.ENUM.name());\n\t\t\t\tout.writeUTF(value.getClass().getName());\n\t\t\t\tout.writeUTF(((Enum)value).name());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tout.writeUTF(VALUE_TYPE.OBJECT.name());\n\t\t\t\tout.writeObject(value);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static Integer readInteger( ObjectInput in ) throws IOException {\n\t\treturn (in.readBoolean() ? null : new Integer(in.readInt()));\n\t}\n\n\tpublic static Long readLong( ObjectInput in ) throws IOException {\n\t\treturn (in.readBoolean() ? null : new Long(in.readLong()));\n\t}\n\n\tpublic static Float readFloat( ObjectInput in ) throws IOException {\n\t\treturn (in.readBoolean() ? null : new Float(in.readFloat()));\n\t}\n\n\tpublic static Double readDouble( ObjectInput in ) throws IOException {\n\t\treturn (in.readBoolean() ? null : new Double(in.readDouble()));\n\t}\n\n\tpublic static String readString( ObjectInput in ) throws IOException {\n\t\treturn (in.readBoolean() ? null : in.readUTF());\n\t}\n\n\tpublic static Date readDate( ObjectInput in ) throws IOException {\n\t\treturn (in.readBoolean() ? null : new Date(in.readLong()));\n\t}\n\n\tpublic static <T extends Enum<T>> T readEnum( ObjectInput in, Class<T> enumType ) throws IOException {\n\t\tString enumName = readString(in);\n\t\tif (enumName == null)\n\t\t\treturn null;\n\t\t\n\t\treturn Enum.valueOf(enumType, enumName);\n\t}\n\n\t/**\n\t * Reads back a generic object (if not null) with no guarantee as to the \n\t * returned type.\n\t */\n\tpublic static Object readObject( ObjectInput in ) throws IOException, ClassNotFoundException {\n\t\tif (in.readBoolean())\n\t\t\treturn null;\n\n\t\treturn in.readObject();\n\t}\n\n\n\t/**\n\t * Reads an object from the input stream that has been serialized by\n\t * calling {@link #writeNullableWithType(ObjectOutput, Object)}. \n\t * \n\t * Note: If called on a serialized object value that has not been written\n\t * with the type, this will fail!\n\t * @param in\n\t * @return\n\t * @throws IOException\n\t */\n\tpublic static Object readWithType( ObjectInput in ) throws IOException, ClassNotFoundException {\n\t\tif (in.readBoolean())\n\t\t\treturn null;\n\t\t\n\t\ttry {\n\t\t\tVALUE_TYPE type = VALUE_TYPE.valueOf( in.readUTF() );\n\t\t\tswitch (type) {\n\t\t\tcase STRING:\n\t\t\t\treturn in.readUTF();\n\t\t\tcase INT:\n\t\t\t\treturn in.readInt();\n\t\t\tcase LONG:\n\t\t\t\treturn in.readLong();\n\t\t\tcase FLOAT:\n\t\t\t\treturn in.readFloat();\n\t\t\tcase DOUBLE:\n\t\t\t\treturn in.readDouble();\n\t\t\tcase DATE:\n\t\t\t\treturn new Date(in.readLong());\n\t\t\tcase ENUM:\n\t\t\t\ttry {\n\t\t\t\t\tClass enumClass = Class.forName(in.readUTF());\n\t\t\t\t\treturn Enum.valueOf(enumClass, in.readUTF());\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\tlog.error(\"Error reading enum value from object input\", e);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\tcase OBJECT:\n\t\t\t\treturn in.readObject();\n\t\t\tdefault:\n\t\t\t\tlog.warn(\"Invalid serialized value type!\");\n\t\t\t}\n\t\t}\n\t\tcatch (IllegalArgumentException iae) {\n\t\t\tlog.error(\"Invalid serialized type reading from object input stream\", iae);\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n}", "public class PBUtil {\n\n\tprivate static Logger log = Logger.getLogger(PBUtil.class);\n\t\n\t\n\t/* ********** Google Protocol Buffer versions for serialization *********** */\n\tpublic static byte[] toBytes(Object val) {\n\t\tif (val == null)\n\t\t\treturn null;\n\n\t\tMessage pb = null;\n\t\tif (val.getClass().isArray() && val.getClass().getComponentType() == Byte.TYPE) {\n\t\t\tpb = toMessage( (byte[])val );\n\t\t}\t\t\n\t\telse if (val instanceof Integer) {\n\t\t\tpb = toMessage( (Integer)val );\n\t\t}\n\t\telse if (val instanceof Float) {\n\t\t\tpb = toMessage( (Float)val );\n\t\t}\n\t\telse if (val instanceof Double) {\n\t\t\tpb = toMessage( (Double)val );\n\t\t}\n\t\telse if (val instanceof Long) {\n\t\t\tpb = toMessage( (Long)val );\n\t\t}\n\t\telse if (val instanceof String) {\n\t\t\tpb = toMessage( (String)val );\n\t\t}\n\t\telse if (val instanceof Date) {\n\t\t\tpb = toMessage( (Date)val );\n\t\t}\n\t\telse if (val instanceof Enum) {\n\t\t\tpb = toMessage( (Enum)val );\n\t\t}\n\t\telse if (val instanceof Collection) {\n\t\t\t// assume it's a string collection for now!\n\t\t\tpb = toMessage( (Collection)val );\n\t\t}\n\t\telse {\n\t\t\t// not handled\n\t\t\tlog.warn(String.format(\"Unknown conversion to protobuf for property value type %s\", val.getClass().getName()));\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tif (pb != null) {\n\t\t\t// self describing message\n\t\t\treturn pb.toByteArray();\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static HDataTypes.HField readMessage(byte[] bytes) {\n\t\tif (bytes == null || bytes.length == 0)\n\t\t\treturn null;\n\t\t\n\t\t// convert to the underlying message type\n\t\tHDataTypes.HField field = null;\n\t\ttry {\n\t\t\tfield = HDataTypes.HField.parseFrom(bytes);\n\t\t\tif (log.isDebugEnabled())\n\t\t\t\tlog.debug(\"Read field:\\n\"+field.toString());\n\t\t}\n\t\tcatch (InvalidProtocolBufferException e) {\n\t\t\tlog.error(\"Invalid protocol buffer parsing bytes\", e);\n\t\t}\n\t\t\n\t\treturn field;\n\t}\n\t\n\tpublic static Object toValue(byte[] bytes) {\n\t\tHDataTypes.HField field = readMessage(bytes);\n\t\tif (field == null)\n\t\t\treturn null;\n\t\t\n\t\tswitch (field.getType()) {\n\t\tcase TEXT:\n\t\t\treturn field.getText();\n\t\tcase INTEGER:\n\t\t\treturn field.getInteger();\n\t\tcase FLOAT:\n\t\t\treturn field.getFloat();\n\t\tcase BOOLEAN:\n\t\t\treturn field.getBoolean();\n\t\tcase BINARY:\n\t\t\treturn field.getBinary().toByteArray();\n\t\tcase DATETIME:\n\t\t\tHDataTypes.DateTime dt = field.getDateTime();\n\t\t\tCalendar cal = Calendar.getInstance();\n\t\t\tcal.setTimeInMillis(dt.getTimestamp());\n\t\t\tif (dt.hasTimezone())\n\t\t\t\tcal.setTimeZone( TimeZone.getTimeZone(dt.getTimezone()) );\n\t\t\treturn cal.getTime();\n\t\tcase JAVAENUM:\n\t\t\ttry {\n\t\t\t\tHDataTypes.JavaEnum en = field.getJavaEnum();\n\t\t\t\tClass enumClass = Class.forName(en.getType());\n\t\t\t\treturn Enum.valueOf(enumClass, en.getValue());\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tlog.error(\"Error instantiating field value for JavaEnum\", e);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase STRINGLIST:\n\t\t\treturn field.getStringList().getValuesList();\n\t\tdefault:\n\t\t\tlog.error(\"Unknown field type \"+field.getType());\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static HDataTypes.HField toMessage(String val) {\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType(HDataTypes.HField.Type.TEXT)\n\t\t\t.setText(val)\n\t\t\t.build();\n\t}\n\t\n\tpublic static HDataTypes.HField toMessage(Integer val) {\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType(HDataTypes.HField.Type.INTEGER)\n\t\t\t.setInteger(val)\n\t\t\t.build();\n\t}\n\n\tpublic static HDataTypes.HField toMessage(Long val) {\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType(HDataTypes.HField.Type.INTEGER)\n\t\t\t.setInteger(val)\n\t\t\t.build();\n\t}\n\n\tpublic static HDataTypes.HField toMessage(Float val) {\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType(HDataTypes.HField.Type.FLOAT)\n\t\t\t.setFloat(val)\n\t\t\t.build();\n\t}\n\n\tpublic static HDataTypes.HField toMessage(Double val) {\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType(HDataTypes.HField.Type.FLOAT)\n\t\t\t.setFloat(val)\n\t\t\t.build();\n\t}\n\t\n\tpublic static HDataTypes.HField toMessage(Date val) {\n\t\tCalendar cal = Calendar.getInstance();\n\t\tcal.setTime(val);\n\t\tHDataTypes.DateTime dt = HDataTypes.DateTime.newBuilder()\n\t\t\t.setTimestamp(cal.getTime().getTime())\n\t\t\t.setTimezone(cal.getTimeZone().getID())\n\t\t\t.build();\n\t\t\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType(HDataTypes.HField.Type.DATETIME)\n\t\t\t.setDateTime(dt)\n\t\t\t.build();\n\t}\n\t\n\tpublic static HDataTypes.HField toMessage(Boolean val) {\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType(HDataTypes.HField.Type.BOOLEAN)\n\t\t\t.setBoolean(val)\n\t\t\t.build();\n\t}\n\t\n\tpublic static HDataTypes.HField toMessage(byte[] val) {\n\t\tByteString bytes = ByteString.copyFrom(val);\n\t\t\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType( HDataTypes.HField.Type.BINARY )\n\t\t\t.setBinary( bytes )\n\t\t\t.build();\n\t}\n\t\n\tpublic static HDataTypes.HField toMessage(Enum val) {\n\t\tHDataTypes.JavaEnum en = HDataTypes.JavaEnum.newBuilder()\n\t\t\t.setType( val.getClass().getName() )\n\t\t\t.setValue( val.name() )\n\t\t\t.build();\n\t\t\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType( HDataTypes.HField.Type.JAVAENUM )\n\t\t\t.setJavaEnum( en )\n\t\t\t.build();\n\t}\n\t\n\tpublic static HDataTypes.HField toMessage(Collection<? extends String> vals) {\n\t\tHDataTypes.StringList list = HDataTypes.StringList.newBuilder()\n\t\t\t.addAllValues(vals)\n\t\t\t.build();\n\t\t\n\t\treturn HDataTypes.HField.newBuilder()\n\t\t\t.setType( HDataTypes.HField.Type.STRINGLIST )\n\t\t\t.setStringList( list )\n\t\t\t.build();\n\t}\n}" ]
import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.List; import meetup.beeno.filter.ColumnMatchFilter; import meetup.beeno.filter.WhileMatchFilter; import meetup.beeno.mapping.EntityInfo; import meetup.beeno.mapping.FieldMapping; import meetup.beeno.mapping.MappingException; import meetup.beeno.util.IOUtil; import meetup.beeno.util.PBUtil; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger;
package meetup.beeno; /** * Utility for building up criteria for HBaseEntity queries. * * @author garyh * */ public class Criteria implements Externalizable { private static Logger log = Logger.getLogger(Criteria.class); private List<Expression> expressions = new ArrayList<Expression>(); public Criteria() { } public Criteria add(Expression expr) { this.expressions.add(expr); return this; } public boolean isEmpty() { return this.expressions.isEmpty(); } public List<Expression> getExpressions() { return this.expressions; } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { this.expressions = (in.readBoolean() ? null : (List<Expression>)in.readObject()); } @Override public void writeExternal( ObjectOutput out ) throws IOException { IOUtil.writeNullable(out, this.expressions); } /* ************* Expressions and builder methods ************** */ public static Expression require(Expression expr) { return new RequireExpression(expr); } public static Expression and(Expression... expr) { CompoundExpression wrapper = new CompoundExpression(true); for (Expression e : expr) { wrapper.add(e); } return wrapper; } public static Expression or(Expression... expr) { CompoundExpression wrapper = new CompoundExpression(false); for (Expression e : expr) { if (log.isDebugEnabled()) log.debug(String.format("Adding OR expression %s", expr.toString())); wrapper.add(e); } return wrapper; } public static Expression or(List<Expression> expr) { CompoundExpression wrapper = new CompoundExpression(false); for (Expression e : expr) { if (log.isDebugEnabled()) log.debug(String.format("Adding OR expression %s", expr)); wrapper.add(e); } return wrapper; } public static Expression eq(String prop, Object val) { return new PropertyComparison(prop, val, ColumnMatchFilter.CompareOp.EQUAL); } public static Expression ne(String prop, Object val) { return new PropertyComparison(prop, val, ColumnMatchFilter.CompareOp.NOT_EQUAL); } public static abstract class Expression implements Externalizable { public Expression() { } public abstract Filter getFilter(EntityInfo info) throws HBaseException; public String toString() { return "["+this.getClass().getSimpleName()+"]"; } } public static abstract class PropertyExpression extends Expression implements Externalizable { protected String property; protected Object value; public PropertyExpression() { // for Externalizable } public PropertyExpression(String prop, Object val) { this.property = prop; this.value = val; } public String getProperty() { return this.property; } public Object getValue() { return this.value; } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { this.property = IOUtil.readString(in); this.value = IOUtil.readWithType(in); } @Override public void writeExternal( ObjectOutput out ) throws IOException { IOUtil.writeNullable(out, this.property); IOUtil.writeNullableWithType(out, this.value); } public String toString() { return "["+this.getClass().getSimpleName()+": property="+this.property+", value="+this.value+"]"; } } public static class PropertyComparison extends PropertyExpression { private ColumnMatchFilter.CompareOp op = null; public PropertyComparison() { // for Externalizable } public PropertyComparison(String prop, Object val, ColumnMatchFilter.CompareOp op) { super(prop, val); this.op = op; } public Filter getFilter(EntityInfo entityInfo) throws HBaseException { FieldMapping mapping = entityInfo.getPropertyMapping(this.property); if (mapping == null) {
throw new MappingException( entityInfo.getEntityClass(),
4
BlackCraze/GameResourceBot
src/main/java/de/blackcraze/grb/commands/FileProcessor.java
[ "public static Device getMateDevice(Message message) {\r\n Mate mate = getMateDao().getOrCreateMate(message, getDefaultLocale());\r\n return mate.getDevice();\r\n}\r", "public static Locale getResponseLocale(Message message) {\r\n Locale channelLocale = getDefaultLocale();\r\n Mate mate = getMateDao().getOrCreateMate(message, channelLocale);\r\n if (mate != null && !StringUtils.isEmpty(mate.getLanguage())) {\r\n return new Locale(mate.getLanguage());\r\n }\r\n return channelLocale;\r\n}\r", "public static List<String> prettyPrint(PrintableTable... stocks) {\r\n List<String> returnHandle = new ArrayList<>(stocks.length);\r\n for (PrintableTable stock : stocks) {\r\n if (stock != null) {\r\n int boardWidth = stock.getWidth();\r\n int headerWidth = boardWidth - 2; // outer borders\r\n StringBuilder b = new StringBuilder();\r\n Board board = new Board(boardWidth);\r\n // board.showBlockIndex(true); // DEBUG\r\n Block header = new Block(board, headerWidth, 1, stock.getHeader());\r\n header.setDataAlign(Block.DATA_MIDDLE_LEFT);\r\n board.setInitialBlock(header);\r\n\r\n Table table = new Table(board, boardWidth, stock.getTitles(), stock.getRows(),\r\n stock.getWidths(), stock.getAligns());\r\n board.appendTableTo(0, Board.APPEND_BELOW, table);\r\n\r\n for (int i = 0; i < stock.getFooter().size(); i++) {\r\n Block footer =\r\n new Block(board, stock.getWidths().get(i), 1, stock.getFooter().get(i));\r\n footer.setDataAlign(stock.getAligns().get(i));\r\n if (i == 0) {\r\n header.getMostBelowBlock().setBelowBlock(footer);\r\n } else {\r\n header.getMostBelowBlock().getMostRightBlock().setRightBlock(footer);\r\n }\r\n }\r\n\r\n board.build();\r\n b.append(board.getPreview());\r\n returnHandle.add(b.toString());\r\n }\r\n }\r\n return returnHandle;\r\n}\r", "public class Update implements BaseCommand {\r\n public void run(Scanner scanner, Message message) {\r\n Locale responseLocale = getResponseLocale(message);\r\n Map<String, Long> stocks = parseStocks(scanner, responseLocale);\r\n internalUpdate(message, responseLocale, stocks);\r\n }\r\n\r\n public static void internalUpdate(Message message, Locale locale, Map<String, Long> stocks) {\r\n try {\r\n Mate mate = getMateDao().getOrCreateMate(message, getResponseLocale(message));\r\n List<String> unknownStocks = getMateDao().updateStocks(mate, stocks);\r\n if (stocks.size() > 0) {\r\n if (!unknownStocks.isEmpty()) {\r\n Speaker.err(message, Resource.getError(\"DO_NOT_KNOW_ABOUT\", locale,\r\n unknownStocks.toString()));\r\n }\r\n if (unknownStocks.size() != stocks.size()) {\r\n message.addReaction(Speaker.Reaction.SUCCESS).queue();\r\n }\r\n } else {\r\n Speaker.err(message, Resource.getError(\"RESOURCES_EMPTY\", locale));\r\n }\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n message.addReaction(Speaker.Reaction.FAILURE).queue();\r\n }\r\n }\r\n\r\n}\r", "public class BotConfig {\r\n\r\n static final String[] REQUIRED_ENV_VARS = { \"GRB_DISCORD_TOKEN\" };\r\n\r\n static final String DISCORD_TOKEN = System.getenv(\"GRB_DISCORD_TOKEN\");\r\n public static final String DATABASE_URL = getEnv(\"DATABASE_URL\", \"postgres://gbr:gbr@localhost:5432/gbr\");\r\n public static final String USE_SSL = getEnv(\"USE_SSL\", \"\");\r\n public static final String TESS_DATA = getEnv(\"TESS_DATA\", \"./tessdata\");\r\n\r\n private static ServerConfig config = new ServerConfig();\r\n\r\n public static class ServerConfig {\r\n public String PREFIX = getEnv(\"PREFIX\", \"bot\");\r\n public String CHANNEL = getEnv(\"CHANNEL\", \"statistik\");\r\n public String LANGUAGE = getEnv(\"LANGUAGE\", \"en\");\r\n public String OCR_RESULT = getEnv(\"OCR_RESULT\", \"on\");\r\n public String DELETE_PICTURE_MESSAGE = getEnv(\"DELETE_PICTURE_MESSAGE\", \"off\");\r\n }\r\n\r\n private static String getEnv(String envVar, String defaultValue) {\r\n Optional<String> envValue = Optional.ofNullable(System.getenv(envVar));\r\n return envValue.orElse(defaultValue);\r\n }\r\n\r\n public static ServerConfig getConfig() {\r\n return config;\r\n }\r\n}\r", "public class Speaker {\r\n\r\n public static class Reaction {\r\n public final static String SUCCESS = \"✅\";\r\n public final static String FAILURE = \"❌\";\r\n }\r\n\r\n public static void say(MessageChannel channel, String text) {\r\n say(channel, text, \"\", \"\");\r\n }\r\n\r\n public static void say(MessageChannel channel, List<String> texts) {\r\n texts.forEach(text -> say(channel, text));\r\n }\r\n\r\n public static void sayCode(MessageChannel channel, List<String> texts) {\r\n texts.forEach(text -> sayCode(channel, text));\r\n }\r\n\r\n public static void sayCode(MessageChannel channel, String text) {\r\n say(channel, text, \"```dsconfig\\n\", \"\\n```\");\r\n }\r\n\r\n private static void say(MessageChannel channel, String text, String prefix, String suffix) {\r\n if (StringUtils.isEmpty(text)) {\r\n return;\r\n }\r\n StringTokenizer t = new StringTokenizer(text, \"\\n\", true);\r\n StringBuffer b = new StringBuffer(prefix);\r\n b.append(suffix);\r\n while (t.hasMoreTokens()) {\r\n String token = t.nextToken();\r\n if (b.length() + token.length() <= 2000) {\r\n b.insert(b.length() - suffix.length(), token);\r\n } else {\r\n channel.sendMessage(b.toString()).queue();\r\n b = new StringBuffer(prefix);\r\n b.append(token);\r\n b.append(suffix);\r\n }\r\n }\r\n channel.sendMessage(b.toString()).queue();\r\n }\r\n\r\n public static void err(Message message, String text) {\r\n message.addReaction(Reaction.FAILURE).queue();\r\n say(message.getChannel(), text);\r\n }\r\n\r\n}\r", "public class Resource {\r\n\r\n private Resource() {\r\n\r\n }\r\n\r\n public static String guessItemKey(String item, Locale locale) {\r\n ResourceBundle resourceBundle =\r\n ResourceBundle.getBundle(\"items\", locale, new ResourceBundleControl());\r\n\r\n String itemTyped = correctItemName(item);\r\n String bestMatch = null;\r\n int diffScore = Integer.MAX_VALUE;\r\n\r\n for (String key : resourceBundle.keySet()) {\r\n String itemName = correctItemName(resourceBundle.getString(key));\r\n if (itemTyped.equals(itemName)) {\r\n return key;\r\n } else {\r\n int score = compareFuzzy(itemName, itemTyped);\r\n if (score < diffScore) {\r\n diffScore = score;\r\n bestMatch = key;\r\n }\r\n }\r\n }\r\n if (scoreIsGood(itemTyped, diffScore)) {\r\n return bestMatch;\r\n } else {\r\n throw new RuntimeException(String.format(\"Can't find %s in %s %s.\", item, \"items\",\r\n locale.toLanguageTag()));\r\n }\r\n }\r\n\r\n public static String guessHelpKey(String key, Locale locale) {\r\n ResourceBundle resourceBundle =\r\n ResourceBundle.getBundle(\"help\", locale, new ResourceBundleControl());\r\n String keyTyped = StringUtils.upperCase(key);\r\n String bestMatch = null;\r\n int diffScore = Integer.MAX_VALUE;\r\n\r\n for (String helpKey : resourceBundle.keySet()) {\r\n if (keyTyped.equals(helpKey)) {\r\n return helpKey;\r\n } else {\r\n int score = compareFuzzy(helpKey, keyTyped);\r\n if (score < diffScore) {\r\n diffScore = score;\r\n bestMatch = helpKey;\r\n }\r\n }\r\n }\r\n if (scoreIsGood(keyTyped, diffScore)) {\r\n return bestMatch;\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n private static boolean scoreIsGood(String itemTyped, int diffScore) {\r\n return itemTyped.length() * 0.5 >= diffScore;\r\n }\r\n\r\n public static String correctItemName(String item) {\r\n return item.toUpperCase().replaceAll(\"-\", \"\").replaceAll(\"\\\\s+\", \"\").replace(\"Ü\", \"U\")\r\n .replace(\"Ä\", \"A\").replace(\"Ö\", \"O\");\r\n }\r\n\r\n public static int compareFuzzy(String one, String another) {\r\n DiffMatchPatch matcher = new DiffMatchPatch();\r\n LinkedList<Diff> diffs = matcher.diff_main(one, another);\r\n return matcher.diff_levenshtein(diffs);\r\n }\r\n\r\n public static String getItem(String key, Locale locale) {\r\n return getResource(key, locale, \"items\");\r\n }\r\n\r\n public static String getError(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"errors\", args);\r\n }\r\n\r\n public static String getHeader(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"headers\", args);\r\n }\r\n\r\n public static String getHelp(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"help\", args);\r\n }\r\n\r\n public static String getInfo(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"inform\", args);\r\n }\r\n\r\n private static String getResource(String key, Locale locale, String baseName, Object... args) {\r\n ResourceBundle resourceBundle =\r\n ResourceBundle.getBundle(baseName, locale, new ResourceBundleControl());\r\n String string = resourceBundle.getString(key);\r\n if (args != null && args.length > 0) {\r\n return String.format(string, args);\r\n } else {\r\n return string;\r\n }\r\n }\r\n\r\n}\r", "public class OCR {\r\n\r\n private TessBaseAPI api;\r\n\r\n private static final OCR OBJ = new OCR();\r\n\r\n private OCR() {\r\n System.setProperty(\"jna.encoding\", \"UTF8\");\r\n }\r\n\r\n public static OCR getInstance() {\r\n return OBJ;\r\n }\r\n\r\n /**\r\n * preprocess with {@link Preprocessor}\r\n *\r\n * @throws IOException\r\n */\r\n public Map<String, Long> convertToStocks(InputStream stream, Locale locale, Device device)\r\n throws IOException {\r\n Map<String, Long> stocks = new HashMap<>();\r\n List<File> frames = Preprocessor.load(stream);\r\n for (File frame : frames) {\r\n try {\r\n File[] pair = Preprocessor.extract(frame, device);\r\n File text = pair[0];\r\n File number = pair[1];\r\n\r\n if (text == null && number == null) {\r\n // That's okay - empty fragment\r\n // Nothing to do.\r\n continue;\r\n }\r\n\r\n String itemName = null;\r\n try {\r\n itemName = doOcr(text, getTesseractForText());\r\n if (StringUtils.isEmpty(itemName)) {\r\n continue;\r\n }\r\n itemName = Resource.guessItemKey(itemName, locale);\r\n } catch (Exception e) {\r\n // We add the clear text stock name with an identifier value.\r\n // This way, we can show the user an error message that\r\n // includes incorrect type names.\r\n stocks.put(itemName, Long.MIN_VALUE);\r\n continue;\r\n } finally {\r\n if (text != null) {\r\n text.delete();\r\n }\r\n }\r\n\r\n String value = doOcr(number, getTesseractForNumbers());\r\n String valueCorrected = StringUtils.replaceAll(value, \"\\\\D\", \"\");\r\n try {\r\n Long valueOf = Long.valueOf(valueCorrected);\r\n stocks.put(itemName, valueOf);\r\n } catch (NumberFormatException e) {\r\n System.err.println(\"Could not convert to number: '\" + value + \"'\");\r\n stocks.put(itemName + \": '\" + value + \"'\", Long.MIN_VALUE);\r\n } finally {\r\n if (number != null) {\r\n number.delete();\r\n }\r\n }\r\n } finally {\r\n if (frame != null) {\r\n frame.delete();\r\n }\r\n }\r\n }\r\n return stocks;\r\n }\r\n\r\n public String doOcr(File tempFile, TessBaseAPI api) throws IOException {\r\n if (tempFile == null) {\r\n return null;\r\n }\r\n PIX image = pixRead(tempFile.getAbsolutePath());\r\n api.SetImage(image);\r\n BytePointer outText = api.GetUTF8Text();\r\n String out = outText.getString(\"UTF-8\");\r\n outText.deallocate();\r\n pixDestroy(image);\r\n return out;\r\n }\r\n\r\n public TessBaseAPI getTesseractForText() {\r\n getTesseract();\r\n api.ReadConfigFile(\"./tessdata/configs/chars\");\r\n return api;\r\n }\r\n\r\n public TessBaseAPI getTesseractForNumbers() {\r\n getTesseract();\r\n api.ReadConfigFile(\"./tessdata/configs/digits\");\r\n return api;\r\n }\r\n\r\n private void getTesseract() {\r\n if (api == null) {\r\n api = new TessBaseAPI();\r\n int init = api.Init(BotConfig.TESS_DATA, \"deu\");\r\n if (init != 0) {\r\n // Another case where I failed to save the original. I hope it's right.\r\n throw new RuntimeException(\"Could not initialise tesseract.\");\r\n }\r\n }\r\n }\r\n\r\n}\r" ]
import static de.blackcraze.grb.util.CommandUtils.getMateDevice; import static de.blackcraze.grb.util.CommandUtils.getResponseLocale; import static de.blackcraze.grb.util.PrintUtils.prettyPrint; import static org.bytedeco.javacpp.Pointer.deallocateReferences; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.Locale; import java.util.Map; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import de.blackcraze.grb.commands.concrete.Update; import de.blackcraze.grb.core.BotConfig; import de.blackcraze.grb.core.Speaker; import de.blackcraze.grb.i18n.Resource; import de.blackcraze.grb.model.Device; import de.blackcraze.grb.ocr.OCR; import net.dv8tion.jda.api.entities.ChannelType; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message.Attachment;
package de.blackcraze.grb.commands; public class FileProcessor { public static void ocrImages(Message message) { Locale locale = getResponseLocale(message); Device device = getMateDevice(message); for (Attachment att : message.getAttachments()) { if (att.isImage()) { InputStream stream = null; try { // Check if the filename ends with .png (only working image format). if (!FilenameUtils.getExtension(att.getFileName()).equalsIgnoreCase("png")) {
Speaker.err(message, Resource.getError("ONLY_PNG_IMAGES", locale));
6
zetbaitsu/CodePolitan
app/src/main/java/id/zelory/codepolitan/ui/fragment/AbstractHomeFragment.java
[ "public abstract class BenihRecyclerAdapter<Data, Holder extends BenihItemViewHolder> extends\n RecyclerView.Adapter<Holder>\n{\n protected Context context;\n protected List<Data> data;\n protected OnItemClickListener itemClickListener;\n protected OnLongItemClickListener longItemClickListener;\n\n public BenihRecyclerAdapter(Context context)\n {\n this.context = context;\n data = new ArrayList<>();\n Timber.tag(getClass().getSimpleName());\n }\n\n public BenihRecyclerAdapter(Context context, List<Data> data)\n {\n this.context = context;\n this.data = data;\n Timber.tag(getClass().getSimpleName());\n }\n\n protected View getView(ViewGroup parent, int viewType)\n {\n return LayoutInflater.from(context).inflate(getItemView(viewType), parent, false);\n }\n\n protected abstract int getItemView(int viewType);\n\n @Override\n public abstract Holder onCreateViewHolder(ViewGroup parent, int viewType);\n\n @Override\n public void onBindViewHolder(Holder holder, int position)\n {\n holder.bind(data.get(position));\n }\n\n @Override\n public int getItemCount()\n {\n try\n {\n return data.size();\n } catch (Exception e)\n {\n return 0;\n }\n }\n\n @Override\n public long getItemId(int position)\n {\n return position;\n }\n\n public interface OnItemClickListener\n {\n void onItemClick(View view, int position);\n }\n\n public void setOnItemClickListener(OnItemClickListener itemClickListener)\n {\n this.itemClickListener = itemClickListener;\n }\n\n public interface OnLongItemClickListener\n {\n void onLongItemClick(View view, int position);\n }\n\n public void setOnLongItemClickListener(OnLongItemClickListener longItemClickListener)\n {\n this.longItemClickListener = longItemClickListener;\n }\n\n public List<Data> getData()\n {\n return data;\n }\n\n public void add(Data item)\n {\n data.add(item);\n notifyItemInserted(data.size() - 1);\n }\n\n public void add(Data item, int position)\n {\n data.add(position, item);\n notifyItemInserted(position);\n }\n\n public void add(final List<Data> items)\n {\n final int size = items.size();\n BenihWorker.pluck()\n .doInComputation(new Runnable()\n {\n @Override\n public void run()\n {\n for (int i = 0; i < size; i++)\n {\n data.add(items.get(i));\n }\n }\n }).subscribe(new Action1<Object>()\n {\n @Override\n public void call(Object o)\n {\n notifyDataSetChanged();\n }\n });\n }\n\n public void remove(int position)\n {\n data.remove(position);\n notifyItemRemoved(position);\n }\n\n public void remove(Data item)\n {\n int position = data.indexOf(item);\n data.remove(position);\n notifyItemRemoved(position);\n }\n\n public void clear()\n {\n data.clear();\n notifyDataSetChanged();\n }\n}", "public abstract class BenihFragment<Data extends Parcelable> extends RxFragment\n{\n protected Data data;\n\n public BenihFragment()\n {\n\n }\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n Timber.tag(getClass().getSimpleName());\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)\n {\n View view = LayoutInflater.from(getActivity()).inflate(getFragmentView(), container, false);\n ButterKnife.bind(this, view);\n return view;\n }\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState)\n {\n super.onActivityCreated(savedInstanceState);\n if (savedInstanceState != null)\n {\n data = savedInstanceState.getParcelable(\"data\");\n }\n onViewReady(savedInstanceState);\n }\n\n public void setData(Data data)\n {\n this.data = data;\n }\n\n public Data getData()\n {\n return data;\n }\n\n protected abstract int getFragmentView();\n\n protected abstract void onViewReady(@Nullable Bundle savedInstanceState);\n\n @Override\n public void onSaveInstanceState(Bundle outState)\n {\n outState.putParcelable(\"data\", data);\n super.onSaveInstanceState(outState);\n }\n\n @Override\n public void onDestroy()\n {\n data = null;\n super.onDestroy();\n }\n\n public void replace(int containerId, BenihFragment fragment, boolean addToBackStack)\n {\n if (addToBackStack)\n {\n getFragmentManager().beginTransaction()\n .replace(containerId, fragment, fragment.getClass().getSimpleName())\n .addToBackStack(null)\n .commit();\n } else\n {\n getFragmentManager().beginTransaction()\n .replace(containerId, fragment, fragment.getClass().getSimpleName())\n .commit();\n }\n }\n\n public void replace(int containerId, BenihFragment fragment, boolean addToBackStack, int transitionStyle)\n {\n if (addToBackStack)\n {\n getFragmentManager().beginTransaction()\n .replace(containerId, fragment, fragment.getClass().getSimpleName())\n .setTransitionStyle(transitionStyle)\n .commit();\n } else\n {\n getFragmentManager().beginTransaction()\n .replace(containerId, fragment, fragment.getClass().getSimpleName())\n .setTransitionStyle(transitionStyle)\n .commit();\n }\n }\n\n protected ActionBar getSupportActionBar()\n {\n return ((BenihActivity) getActivity()).getSupportActionBar();\n }\n\n protected void setSupportActionBar(Toolbar toolbar)\n {\n ((BenihActivity) getActivity()).setSupportActionBar(toolbar);\n }\n}", "public class BenihRecyclerView extends RecyclerView\n{\n public BenihRecyclerView(Context context)\n {\n super(context);\n }\n\n public BenihRecyclerView(Context context, AttributeSet attrs)\n {\n super(context, attrs);\n }\n\n public BenihRecyclerView(Context context, AttributeSet attrs, int defStyle)\n {\n super(context, attrs, defStyle);\n }\n\n public void setUpAsList()\n {\n setHasFixedSize(true);\n setLayoutManager(new LinearLayoutManager(getContext()));\n }\n\n public void setUpAsGrid(int spanCount)\n {\n setHasFixedSize(true);\n setLayoutManager(new GridLayoutManager(getContext(), spanCount));\n }\n}", "public class ArticleController extends BenihController<ArticleController.Presenter>\n{\n private Article article;\n private List<Article> articles;\n\n public ArticleController(Presenter presenter)\n {\n super(presenter);\n }\n\n public void setArticle(Article article)\n {\n this.article = article;\n }\n\n public void loadArticle(int id)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .getDetailArticle(id)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .map(ObjectResponse::getResult)\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n return article;\n })\n .subscribe(article -> {\n this.article = article;\n if (presenter != null)\n {\n presenter.showArticle(article);\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.LOAD_ARTICLE));\n presenter.dismissLoading();\n }\n });\n }\n\n public void loadArticles(int page)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .getLatestArticles(page)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n article.setBig(BenihUtils.randInt(0, 8) == 5);\n return article;\n })\n .toList()\n .subscribe(articles -> {\n BenihWorker.pluck()\n .doInNewThread(() -> {\n if (page == 1)\n {\n if (!articles.isEmpty())\n {\n articles.get(0).setBig(true);\n }\n this.articles = articles;\n } else\n {\n this.articles.addAll(articles);\n }\n }).subscribe(o -> {\n if (presenter != null)\n {\n presenter.showArticles(articles);\n }\n });\n if (presenter != null)\n {\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.LOAD_LIST_ARTICLE_BY_PAGE));\n presenter.dismissLoading();\n }\n });\n }\n\n public void loadFollowedArticles(int page)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .getLatestArticles(page)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))\n .map(article -> CodePolitanApi.pluck()\n .getApi()\n .getDetailArticle(article.getId())\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO)))\n .flatMap(objectResponseObservable -> objectResponseObservable\n .flatMap(articleObjectResponse -> Observable.just(articleObjectResponse.getResult())))\n .filter(article -> {\n int size = article.getCategory().size();\n for (int i = 0; i < size; i++)\n {\n if (DataBaseHelper.pluck().isFollowed(article.getCategory().get(i)))\n {\n return true;\n }\n }\n size = article.getTags().size();\n for (int i = 0; i < size; i++)\n {\n if (DataBaseHelper.pluck().isFollowed(article.getTags().get(i)))\n {\n return true;\n }\n }\n\n return false;\n })\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n article.setBig(BenihUtils.randInt(0, 8) == 5);\n return article;\n })\n .toList()\n .subscribe(articles -> {\n BenihWorker.pluck()\n .doInNewThread(() -> {\n if (page == 1)\n {\n if (!articles.isEmpty())\n {\n articles.get(0).setBig(true);\n }\n this.articles = articles;\n } else\n {\n this.articles.addAll(articles);\n }\n }).subscribe(o -> {\n if (presenter != null)\n {\n presenter.showArticles(articles);\n }\n });\n if (presenter != null)\n {\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.LOAD_FOLLOWED_ARTICLES));\n presenter.dismissLoading();\n }\n });\n }\n\n public void loadUnFollowedArticles(int page)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .getLatestArticles(page)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))\n .map(article -> CodePolitanApi.pluck()\n .getApi()\n .getDetailArticle(article.getId())\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO)))\n .flatMap(objectResponseObservable -> objectResponseObservable\n .flatMap(articleObjectResponse -> Observable.just(articleObjectResponse.getResult())))\n .filter(article -> {\n int size = article.getCategory().size();\n for (int i = 0; i < size; i++)\n {\n if (DataBaseHelper.pluck().isFollowed(article.getCategory().get(i)))\n {\n return false;\n }\n }\n size = article.getTags().size();\n for (int i = 0; i < size; i++)\n {\n if (DataBaseHelper.pluck().isFollowed(article.getTags().get(i)))\n {\n return false;\n }\n }\n\n return true;\n })\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n article.setBig(BenihUtils.randInt(0, 8) == 5);\n return article;\n })\n .toList()\n .subscribe(articles -> {\n BenihWorker.pluck()\n .doInNewThread(() -> {\n if (page == 1)\n {\n if (!articles.isEmpty())\n {\n articles.get(0).setBig(true);\n }\n this.articles = articles;\n } else\n {\n this.articles.addAll(articles);\n }\n }).subscribe(o -> {\n if (presenter != null)\n {\n presenter.showArticles(articles);\n }\n });\n if (presenter != null)\n {\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.LOAD_UNFOLLOWED_ARTICLES));\n presenter.dismissLoading();\n }\n });\n }\n\n public void searchArticles(String keyword, int page)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .searchArticles(keyword, page)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n article.setBig(BenihUtils.randInt(0, 8) == 5);\n return article;\n })\n .toList()\n .subscribe(articles -> {\n BenihWorker.pluck()\n .doInNewThread(() -> {\n if (page == 1)\n {\n if (!articles.isEmpty())\n {\n articles.get(0).setBig(true);\n }\n this.articles = articles;\n } else\n {\n this.articles.addAll(articles);\n }\n }).subscribe(o -> {\n if (presenter != null)\n {\n presenter.showArticles(articles);\n }\n });\n if (presenter != null)\n {\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.SEARCH_ARTICLES));\n presenter.dismissLoading();\n }\n });\n }\n\n public void loadArticles(String postType, int page)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .getLatestArticles(postType, page)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n article.setBig(BenihUtils.randInt(0, 8) == 5);\n article.setPostType(postType);\n return article;\n })\n .toList()\n .subscribe(articles -> {\n BenihWorker.pluck()\n .doInNewThread(() -> {\n if (page == 1)\n {\n articles.get(0).setBig(true);\n this.articles = articles;\n } else\n {\n this.articles.addAll(articles);\n }\n }).subscribe(o -> {\n if (presenter != null)\n {\n presenter.showArticles(articles);\n }\n });\n if (presenter != null)\n {\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.LOAD_LIST_ARTICLE_BY_POST_TYPE));\n presenter.dismissLoading();\n }\n });\n }\n\n public void loadArticles(Category category, int page)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .getArticles(category, page)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n article.setBig(BenihUtils.randInt(0, 8) == 5);\n return article;\n })\n .toList()\n .subscribe(articles -> {\n BenihWorker.pluck()\n .doInNewThread(() -> {\n if (page == 1)\n {\n articles.get(0).setBig(true);\n this.articles = articles;\n } else\n {\n this.articles.addAll(articles);\n }\n }).subscribe(o -> {\n if (presenter != null)\n {\n presenter.showArticles(articles);\n }\n });\n if (presenter != null)\n {\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.LOAD_LIST_ARTICLE_BY_CATEGORY));\n presenter.dismissLoading();\n }\n });\n }\n\n public void loadArticles(Tag tag, int page)\n {\n presenter.showLoading();\n CodePolitanApi.pluck()\n .getApi()\n .getArticles(tag, page)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.IO))\n .flatMap(articleListResponse -> Observable.from(articleListResponse.getResult()))\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n article.setBig(BenihUtils.randInt(0, 8) == 5);\n return article;\n })\n .toList()\n .subscribe(articles -> {\n BenihWorker.pluck()\n .doInNewThread(() -> {\n if (page == 1)\n {\n articles.get(0).setBig(true);\n this.articles = articles;\n } else\n {\n this.articles.addAll(articles);\n }\n }).subscribe(o -> {\n if (presenter != null)\n {\n presenter.showArticles(articles);\n }\n });\n if (presenter != null)\n {\n presenter.dismissLoading();\n }\n }, throwable -> {\n if (presenter != null)\n {\n Timber.e(throwable.getMessage());\n presenter.showError(new Throwable(ErrorEvent.LOAD_LIST_ARTICLE_BY_TAG));\n presenter.dismissLoading();\n }\n });\n }\n\n public void filter(String query)\n {\n if (articles != null)\n {\n Observable.from(articles)\n .compose(BenihScheduler.pluck().applySchedulers(BenihScheduler.Type.NEW_THREAD))\n .filter(article -> article.getTitle().toLowerCase().contains(query.toLowerCase()))\n .map(article -> {\n article.setBookmarked(DataBaseHelper.pluck().isBookmarked(article.getId()));\n article.setReadLater(DataBaseHelper.pluck().isReadLater(article.getId()));\n return article;\n })\n .toList()\n .subscribe(presenter::showFilteredArticles, presenter::showError);\n } else\n {\n presenter.showFilteredArticles(new ArrayList<>());\n }\n }\n\n\n @Override\n public void loadState(Bundle bundle)\n {\n article = bundle.getParcelable(\"article\");\n if (article != null)\n {\n presenter.showArticle(article);\n } else\n {\n presenter.showError(new Throwable(ErrorEvent.LOAD_STATE_ARTICLE));\n }\n\n articles = bundle.getParcelableArrayList(\"articles\");\n if (articles != null)\n {\n presenter.showArticles(articles);\n } else\n {\n presenter.showError(new Throwable(ErrorEvent.LOAD_STATE_LIST_ARTICLE));\n }\n }\n\n @Override\n public void saveState(Bundle bundle)\n {\n bundle.putParcelable(\"article\", article);\n bundle.putParcelableArrayList(\"articles\", (ArrayList<Article>) articles);\n }\n\n public interface Presenter extends BenihController.Presenter\n {\n void showArticle(Article article);\n\n void showArticles(List<Article> articles);\n\n void showFilteredArticles(List<Article> articles);\n }\n}", "public interface ErrorEvent\n{\n String LOAD_STATE_ARTICLE = \"0\";\n String LOAD_STATE_LIST_ARTICLE = \"1\";\n String LOAD_STATE_LIST_CATEGORY = \"2\";\n String LOAD_STATE_LIST_TAG = \"3\";\n String LOAD_STATE_RANDOM_ARTICLES = \"4\";\n String LOAD_ARTICLE = \"5\";\n String LOAD_LIST_ARTICLE_BY_PAGE = \"6\";\n String LOAD_LIST_ARTICLE_BY_POST_TYPE = \"7\";\n String LOAD_LIST_ARTICLE_BY_CATEGORY = \"8\";\n String LOAD_LIST_ARTICLE_BY_TAG = \"9\";\n String LOAD_BOOKMARKED_ARTICLES = \"10\";\n String LOAD_READ_LATER_ARTICLES = \"11\";\n String ON_READ_LATER = \"12\";\n String LOAD_RANDOM_ARTICLES = \"13\";\n String LOAD_RANDOM_ARTICLES_BY_CATEGORY = \"14\";\n String LOAD_RANDOM_ARTICLES_BY_TAG = \"15\";\n String LOAD_RANDOM_CATEGORY = \"16\";\n String LOAD_RANDOM_TAG = \"17\";\n String LOAD_STATE_RANDOM_CATEGORY = \"18\";\n String LOAD_STATE_RANDOM_TAG = \"19\";\n String LOAD_LIST_CATEGORY = \"20\";\n String LOAD_LIST_TAG = \"21\";\n String LOAD_POPULAR_TAGS = \"22\";\n String LOAD_STATE_POPULAR_TAGS = \"23\";\n String LOAD_FOLLOWED_CATEGORIES = \"24\";\n String LOAD_FOLLOWED_TAGS = \"25\";\n String LOAD_FOLLOWED_ARTICLES = \"26\";\n String LOAD_UNFOLLOWED_ARTICLES = \"27\";\n String SEARCH_ARTICLES = \"28\";\n}", "public class Article implements Parcelable\n{\n public final static String TYPE_NEWS = \"news\";\n public final static String TYPE_KOMIK = \"nyankomik\";\n public final static String TYPE_MEME = \"meme\";\n public final static String TYPE_QUOTE = \"quotes\";\n\n private int id;\n private String slug;\n private String title;\n private String excerpt;\n private String content;\n private String date;\n private String dateClear;\n private String link;\n private String thumbnailSmall;\n private String thumbnailMedium;\n private boolean bookmarked;\n private boolean readLater;\n private boolean big;\n private String postType;\n private List<Category> category;\n private List<Tag> tags;\n\n public Article()\n {\n postType = TYPE_NEWS;\n }\n\n protected Article(Parcel in)\n {\n id = in.readInt();\n slug = in.readString();\n title = in.readString();\n excerpt = in.readString();\n content = in.readString();\n date = in.readString();\n dateClear = in.readString();\n link = in.readString();\n thumbnailSmall = in.readString();\n thumbnailMedium = in.readString();\n bookmarked = in.readByte() != 0;\n readLater = in.readByte() != 0;\n big = in.readByte() != 0;\n postType = in.readString();\n category = in.createTypedArrayList(Category.CREATOR);\n tags = in.createTypedArrayList(Tag.CREATOR);\n }\n\n public static final Creator<Article> CREATOR = new Creator<Article>()\n {\n @Override\n public Article createFromParcel(Parcel in)\n {\n return new Article(in);\n }\n\n @Override\n public Article[] newArray(int size)\n {\n return new Article[size];\n }\n };\n\n public int getId()\n {\n return id;\n }\n\n public void setId(int id)\n {\n this.id = id;\n }\n\n public String getSlug()\n {\n return slug;\n }\n\n public void setSlug(String slug)\n {\n this.slug = slug;\n }\n\n public String getTitle()\n {\n return title;\n }\n\n public void setTitle(String title)\n {\n this.title = title;\n }\n\n public String getExcerpt()\n {\n return excerpt;\n }\n\n public void setExcerpt(String excerpt)\n {\n this.excerpt = excerpt;\n }\n\n public String getContent()\n {\n return content;\n }\n\n public void setContent(String content)\n {\n this.content = content;\n }\n\n public String getDate()\n {\n return date;\n }\n\n public void setDate(String date)\n {\n this.date = date;\n }\n\n public String getDateClear()\n {\n return dateClear;\n }\n\n public void setDateClear(String dateClear)\n {\n this.dateClear = dateClear;\n }\n\n public String getLink()\n {\n return link;\n }\n\n public void setLink(String link)\n {\n this.link = link;\n }\n\n public String getThumbnailSmall()\n {\n return thumbnailSmall;\n }\n\n public void setThumbnailSmall(String thumbnailSmall)\n {\n this.thumbnailSmall = thumbnailSmall;\n }\n\n public String getThumbnailMedium()\n {\n return thumbnailMedium;\n }\n\n public void setThumbnailMedium(String thumbnailMedium)\n {\n this.thumbnailMedium = thumbnailMedium;\n }\n\n public boolean isBookmarked()\n {\n return bookmarked;\n }\n\n public void setBookmarked(boolean bookmarked)\n {\n this.bookmarked = bookmarked;\n }\n\n public boolean isReadLater()\n {\n return readLater;\n }\n\n public void setReadLater(boolean readLater)\n {\n this.readLater = readLater;\n }\n\n public boolean isBig()\n {\n return big;\n }\n\n public void setBig(boolean big)\n {\n this.big = big;\n }\n\n public String getPostType()\n {\n return postType;\n }\n\n public void setPostType(String postType)\n {\n this.postType = postType;\n }\n\n public List<Category> getCategory()\n {\n return category;\n }\n\n public void setCategory(List<Category> category)\n {\n this.category = category;\n }\n\n public List<Tag> getTags()\n {\n return tags;\n }\n\n public void setTags(List<Tag> tags)\n {\n this.tags = tags;\n }\n\n @Override\n public int describeContents()\n {\n return hashCode();\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags)\n {\n dest.writeInt(id);\n dest.writeString(slug);\n dest.writeString(title);\n dest.writeString(excerpt);\n dest.writeString(content);\n dest.writeString(date);\n dest.writeString(dateClear);\n dest.writeString(link);\n dest.writeString(thumbnailSmall);\n dest.writeString(thumbnailMedium);\n dest.writeByte((byte) (bookmarked ? 1 : 0));\n dest.writeByte((byte) (readLater ? 1 : 0));\n dest.writeByte((byte) (big ? 1 : 0));\n dest.writeString(postType);\n dest.writeTypedList(category);\n dest.writeTypedList(tags);\n }\n}", "public class LocalDataManager\n{\n public static void saveArticles(List<Article> articles)\n {\n BenihPreferenceUtils.putString(CodePolitanApplication.pluck().getApplicationContext(), \"articles\",\n Bson.pluck().getParser().toJson(articles));\n }\n\n public static void savePosition(int position)\n {\n BenihPreferenceUtils.putInt(CodePolitanApplication.pluck().getApplicationContext(), \"position\", position);\n }\n\n public static List<Article> getArticles()\n {\n return Bson.pluck()\n .getParser()\n .fromJson(BenihPreferenceUtils.getString(CodePolitanApplication.pluck().getApplicationContext(), \"articles\"),\n new TypeToken<List<Article>>() {}.getType());\n }\n\n public static int getPosition()\n {\n return BenihPreferenceUtils.getInt(CodePolitanApplication.pluck().getApplicationContext(), \"position\");\n }\n\n public static void setFollowAll(boolean isFollowAll)\n {\n BenihPreferenceUtils.putBoolean(CodePolitanApplication.pluck().getApplicationContext(),\n \"follow_all_categories\", isFollowAll);\n }\n\n public static boolean isFollowAll()\n {\n return BenihPreferenceUtils.getBoolean(CodePolitanApplication.pluck().getApplicationContext(),\n \"follow_all_categories\");\n }\n\n public static void setNotificationActive(boolean isNotificationActive)\n {\n BenihPreferenceUtils.putBoolean(CodePolitanApplication.pluck().getApplicationContext(),\n \"notification\", isNotificationActive);\n }\n\n public static boolean isNotificationActive()\n {\n return BenihPreferenceUtils.getBoolean(CodePolitanApplication.pluck().getApplicationContext(),\n \"notification\");\n }\n\n public static void setRingtone(String path)\n {\n BenihPreferenceUtils.putString(CodePolitanApplication.pluck().getApplicationContext(),\n \"ringtone\", path);\n }\n\n public static String getRingtone()\n {\n return BenihPreferenceUtils.getString(CodePolitanApplication.pluck().getApplicationContext(),\n \"ringtone\");\n }\n\n public static void setVibrate(boolean isVibrate)\n {\n BenihPreferenceUtils.putBoolean(CodePolitanApplication.pluck().getApplicationContext(),\n \"vibrate\", isVibrate);\n }\n\n public static boolean isVibrate()\n {\n return BenihPreferenceUtils.getBoolean(CodePolitanApplication.pluck().getApplicationContext(),\n \"vibrate\");\n }\n\n public static void setAutoRemoveReadLater(boolean isAutoRemove)\n {\n BenihPreferenceUtils.putBoolean(CodePolitanApplication.pluck().getApplicationContext(),\n \"remove_read_later\", isAutoRemove);\n }\n\n public static boolean isAutoRemoveReadLater()\n {\n Context context = CodePolitanApplication.pluck().getApplicationContext();\n SharedPreferences sharedPreferences = context.getSharedPreferences(\"Zelory\", Context.MODE_PRIVATE);\n return sharedPreferences.getBoolean(\"remove_read_later\", true);\n }\n}" ]
import android.os.Bundle; import android.os.Handler; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.View; import java.util.List; import butterknife.Bind; import id.zelory.benih.adapter.BenihRecyclerAdapter; import id.zelory.benih.fragment.BenihFragment; import id.zelory.benih.util.BenihBus; import id.zelory.benih.util.KeyboardUtil; import id.zelory.benih.view.BenihRecyclerView; import id.zelory.codepolitan.R; import id.zelory.codepolitan.controller.ArticleController; import id.zelory.codepolitan.controller.event.ErrorEvent; import id.zelory.codepolitan.data.model.Article; import id.zelory.codepolitan.data.LocalDataManager; import timber.log.Timber;
/* * Copyright (c) 2015 Zelory. * * 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 id.zelory.codepolitan.ui.fragment; /** * Created on : August 3, 2015 * Author : zetbaitsu * Name : Zetra * Email : zetra@mail.ugm.ac.id * GitHub : https://github.com/zetbaitsu * LinkedIn : https://id.linkedin.com/in/zetbaitsu */ public abstract class AbstractHomeFragment<Adapter extends BenihRecyclerAdapter> extends BenihFragment implements ArticleController.Presenter, SwipeRefreshLayout.OnRefreshListener, SearchView.OnQueryTextListener { protected ArticleController articleController; @Bind(R.id.swipe_layout) SwipeRefreshLayout swipeRefreshLayout; @Bind(R.id.recycler_view) BenihRecyclerView recyclerView; protected SearchView searchView; protected Adapter adapter; protected int currentPage = 1; protected boolean searching = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override protected void onViewReady(Bundle bundle) { BenihBus.pluck() .receive() .subscribe(o -> { if (o instanceof Menu) { onMenuCreated((Menu) o); } }, throwable -> Timber.e(throwable.getMessage())); currentPage = bundle != null ? bundle.getInt("currentPage") : 1; setUpSwipeLayout(); setUpAdapter(bundle); setUpRecyclerView(); setupController(bundle); } protected abstract void setUpRecyclerView(); protected abstract Adapter createAdapter(); protected void setUpAdapter(Bundle bundle) { if (adapter == null) { adapter = createAdapter(); adapter.setOnItemClickListener(this::onItemClick); recyclerView.setAdapter(adapter); } } protected abstract void onItemClick(View view, int position); protected void setUpSwipeLayout() { swipeRefreshLayout.setColorSchemeResources(R.color.primary, R.color.accent); swipeRefreshLayout.setOnRefreshListener(this); } private void onMenuCreated(Menu menu) { searchView = (SearchView) menu.getItem(0).getActionView(); searchView.setOnQueryTextListener(this); } protected void setupController(Bundle bundle) { if (articleController == null) { articleController = new ArticleController(this); } if (bundle != null) { articleController.loadState(bundle); } else { new Handler().postDelayed(this::onRefresh, 800); } } @Override public void onRefresh() { currentPage = 1; adapter.clear(); setUpRecyclerView(); } @Override public void showArticle(Article article) { } @Override public void showArticles(List<Article> articles) { if (!searching && adapter != null) { adapter.add(articles); } } @Override public void showFilteredArticles(List<Article> articles) { adapter.clear(); adapter.add(articles); } @Override public void showLoading() { if (!searching) { swipeRefreshLayout.setRefreshing(true); } } @Override public void dismissLoading() { swipeRefreshLayout.setRefreshing(false); } @Override public void showError(Throwable throwable) { switch (throwable.getMessage()) { case ErrorEvent.LOAD_STATE_LIST_ARTICLE: onRefresh(); break; case ErrorEvent.LOAD_LIST_ARTICLE_BY_PAGE: Snackbar.make(recyclerView, R.string.error_message, Snackbar.LENGTH_LONG) .setAction(R.string.retry, v -> {
if (LocalDataManager.isFollowAll())
6
RepreZen/KaiZen-OpenAPI-Editor
com.reprezen.swagedit.core/src/com/reprezen/swagedit/core/hyperlinks/ReferenceHyperlinkDetector.java
[ "public abstract class JsonDocument extends Document {\n\n private final ObjectMapper mapper;\n private CompositeSchema schema;\n\n public enum Version {\n SWAGGER, OPENAPI;\n }\n\n private final Yaml yaml = new Yaml();\n\n private AtomicReference<Result<JsonNode>> jsonContent = new AtomicReference<>(new Failure<>(null));\n private AtomicReference<Result<Node>> yamlContent = new AtomicReference<>(new Failure<>(null));\n private AtomicReference<Model> model = new AtomicReference<>();\n\n public JsonDocument(CompositeSchema schema) {\n this.mapper = new ObjectMapper(new YAMLFactory());\n this.schema = schema;\n }\n\n public abstract Version getVersion();\n\n public Exception getYamlError() {\n return yamlContent.get().getError();\n }\n\n public Exception getJsonError() {\n return jsonContent.get().getError();\n }\n\n /**\n * Returns YAML abstract representation of the document.\n * \n * @return Node\n */\n public Node getYaml() {\n if (yamlContent.get() == null || yamlContent.get().getResult() == null) {\n updateYaml(get());\n }\n return yamlContent.get().getResult();\n }\n\n /**\n * Returns the JSON representation of the document.\n * \n * Will throw an exception if the content of the document is not valid YAML.\n * \n * @return JsonNode\n * @throws ParserException\n * @throws IOException\n */\n public JsonNode asJson() {\n if (jsonContent.get() == null || jsonContent.get().getResult() == null) {\n updateJson(get());\n }\n return jsonContent.get().getResult();\n }\n\n public CompositeSchema getSchema() {\n return schema;\n }\n\n /**\n * Returns position of the symbol ':' in respect to the given offset.\n * \n * Will return -1 if reaches beginning of line of other symbol before finding ':'.\n * \n * @param offset\n * @return position\n */\n public int getDelimiterPosition(int offset) {\n while (true) {\n try {\n char c = getChar(--offset);\n if (Character.isLetterOrDigit(c)) {\n return -1;\n }\n if (c == ':') {\n return offset;\n }\n if (Character.isWhitespace(c)) {\n continue;\n }\n if (c != ':' && !Character.isLetterOrDigit(c)) {\n return -1;\n }\n } catch (BadLocationException e) {\n return -1;\n }\n }\n }\n\n public void onChange() {\n final String content = get();\n\n updateModel();\n updateYaml(content);\n\n // No need to parse json if\n // there is already a yaml parsing error.\n if (!yamlContent.get().isSuccess()) {\n jsonContent.getAndSet(new Failure<>(null));\n } else {\n updateJson(content);\n }\n }\n\n private void updateYaml(String content) {\n yamlContent.getAndSet(parseYaml(content));\n }\n\n private Result<Node> parseYaml(String content) {\n try {\n return new Success<>(yaml.compose(new StringReader(content)));\n } catch (Exception e) {\n return new Failure<>(e);\n }\n }\n\n private void updateJson(String content) {\n jsonContent.getAndSet(parseJson(content));\n }\n\n private Result<JsonNode> parseJson(String content) {\n try {\n Object expandedYamlObject = new Yaml().load(content);\n return new Success<>(mapper.valueToTree(expandedYamlObject));\n } catch (Exception e) {\n return new Failure<>(e);\n }\n }\n\n private void updateModel() {\n model.getAndSet(parseModel());\n }\n\n private Model parseModel() {\n try {\n return Model.parseYaml(schema, get());\n } catch (Exception e) {\n return null;\n }\n }\n\n /**\n * @return the Model, or null if the spec is invalid YAML\n */\n public Model getModel() {\n if (model.get() == null) {\n model.getAndSet(parseModel());\n }\n return model.get();\n }\n\n /*\n * Used by code-assist\n */\n public Model getModel(int offset) {\n // no parse errors\n final Model modelValue = model.get();\n if (modelValue != null) {\n return modelValue;\n }\n // parse errors -> return the model at offset, do NOT update the `model` field\n try {\n if (0 > offset || offset > getLength()) {\n return Model.parseYaml(schema, get());\n } else {\n return Model.parseYaml(schema, get(0, offset));\n }\n } catch (BadLocationException e) {\n return null;\n }\n }\n\n public JsonPointer getPath(int line, int column) {\n return getModel().getPath(line, column);\n }\n\n public JsonPointer getPath(IRegion region) {\n int lineOfOffset;\n try {\n lineOfOffset = getLineOfOffset(region.getOffset());\n } catch (BadLocationException e) {\n return null;\n }\n\n return getModel().getPath(lineOfOffset, getColumnOfOffset(lineOfOffset, region));\n }\n\n public int getColumnOfOffset(int line, IRegion region) {\n int lineOffset;\n try {\n lineOffset = getLineOffset(line);\n } catch (BadLocationException e) {\n lineOffset = 0;\n }\n\n return (region.getOffset() + region.getLength()) - lineOffset;\n }\n\n public IRegion getRegion(JsonPointer pointer) {\n Model model = getModel();\n if (model == null) {\n return null;\n }\n\n AbstractNode node = model.find(pointer);\n if (node == null) {\n return new Region(0, 0);\n }\n\n Position position = node.getPosition(this);\n\n return new Region(position.getOffset(), position.getLength());\n }\n\n public interface Result<T> {\n boolean isSuccess();\n\n T getResult();\n\n Exception getError();\n }\n\n public final class Success<T> implements Result<T> {\n private final T result;\n\n public Success(T result) {\n this.result = result;\n }\n\n public boolean isSuccess() {\n return true;\n }\n\n @Override\n public Exception getError() {\n return null;\n }\n\n @Override\n public T getResult() {\n return result;\n }\n }\n\n public final class Failure<T> implements Result<T> {\n private final Exception error;\n\n public Failure(Exception error) {\n this.error = error;\n }\n\n public boolean isSuccess() {\n return false;\n }\n\n @Override\n public Exception getError() {\n return error;\n }\n\n @Override\n public T getResult() {\n return null;\n }\n }\n\n}", "public class JsonReference {\n\n public static final String PROPERTY = \"$ref\";\n\n /**\n * Represents an unqualified reference, this class is used to support deprecated references.\n */\n public static class SimpleReference extends JsonReference {\n\n SimpleReference(URI baseURI, JsonPointer ptr, Object source) {\n super(URI.create(baseURI + \"#\" + ptr.toString()), ptr, false, true, false, source);\n }\n\n }\n\n private final URI uri;\n private final JsonPointer pointer;\n private final boolean absolute;\n private final boolean local;\n private final Object source;\n private final boolean containsWarning;\n\n private JsonNode resolved;\n private JsonDocumentManager manager = JsonDocumentManager.getInstance();\n\n JsonReference(URI uri, JsonPointer pointer, boolean absolute, boolean local, boolean containsWarning,\n Object source) {\n this.uri = uri;\n this.pointer = pointer;\n this.absolute = absolute;\n this.local = local;\n this.source = source;\n this.containsWarning = containsWarning;\n }\n\n public void setDocumentManager(JsonDocumentManager manager) {\n this.manager = manager;\n }\n\n /**\n * Returns true if the reference was constructed from an invalid string, e.g. it contains invalid characters.\n * \n * @return true if is invalid URI.\n */\n public boolean isInvalid() {\n return uri == null || pointer == null;\n }\n\n /**\n * Returns true if the reference cannot be resolved and the pointer points to an inexistent element.\n * \n * @param document\n * @param baseURI\n * @return true if the reference can be resolved.\n */\n public boolean isMissing(JsonDocument document, URI baseURI) {\n if (isInvalid()) {\n return false;\n }\n\n JsonNode resolved = resolve(document, baseURI);\n return resolved == null || resolved.isMissingNode();\n }\n\n /**\n * Returns the node that is referenced by this reference.\n * \n * If the resolution of the referenced node fails, this method returns null. If the pointer does not points to an\n * existing node, this method will return a missing node (see JsonNode.isMissingNode()).\n * \n * @param document\n * @param baseURI\n * @return referenced node\n */\n public JsonNode resolve(JsonDocument document, URI baseURI) {\n if (resolved == null) {\n JsonNode doc = getDocument(document, baseURI);\n if (doc != null) {\n try {\n resolved = doc.at(pointer);\n } catch (Exception e) {\n resolved = null;\n }\n }\n }\n\n return resolved;\n }\n\n protected URI resolveURI(URI baseURI) {\n if (baseURI == null || absolute) {\n return getUri();\n } else {\n try {\n return baseURI.resolve(getUri());\n } catch (NullPointerException e) {\n return null;\n }\n }\n }\n\n public JsonPointer getPointer() {\n return pointer;\n }\n\n public URI getUri() {\n return uri;\n }\n\n public boolean isLocal() {\n return local;\n }\n\n public boolean isAbsolute() {\n return absolute;\n }\n\n public boolean containsWarning() {\n return containsWarning;\n }\n\n public Object getSource() {\n return source;\n }\n\n /**\n * Returns true if the argument can be identified as a JSON reference node.\n * \n * A node is considered a reference if it is an object node and has a field named $ref having a textual value.\n * \n * @param node\n * @return true if a reference node\n */\n public static boolean isReference(JsonNode value) {\n return value != null && value.isObject() && value.has(PROPERTY) && value.get(PROPERTY).isTextual();\n }\n\n public static boolean isReference(AbstractNode value) {\n return value != null && value.isObject() && value.get(PROPERTY) != null;\n }\n\n public static JsonPointer getPointer(JsonNode node) {\n JsonNode value = node.get(PROPERTY);\n\n if (value != null) {\n return createPointer(value.asText());\n } else {\n return createPointer(null);\n }\n }\n\n private static JsonPointer createPointer(String text) {\n if (StringUtils.emptyToNull(text) == null) {\n return JsonPointer.compile(\"\");\n }\n\n if (text.startsWith(\"#\")) {\n text = text.substring(1);\n }\n return JsonPointer.compile(text);\n }\n\n /**\n * Returns true if the argument can be identified as a JSON reference node.\n * \n * @param tuple\n * @return true if a reference node\n */\n public static boolean isReference(NodeTuple tuple) {\n if (tuple.getKeyNode().getNodeId() == NodeId.scalar) {\n String value = ((ScalarNode) tuple.getKeyNode()).getValue();\n\n return JsonReference.PROPERTY.equals(value) && tuple.getValueNode().getNodeId() == NodeId.scalar;\n }\n return false;\n }\n\n public static JsonPointer getPointer(ObjectNode node) {\n ValueNode value = node.get(PROPERTY).asValue();\n\n if (value != null) {\n return createPointer((String) value.getValue());\n } else {\n return createPointer(null);\n }\n }\n\n /**\n * Returns the JSON document that contains the node referenced by this reference.\n * \n * @param document\n * @param baseURI\n * @return referenced node\n */\n public JsonNode getDocument(JsonDocument document, URI baseURI) {\n if (isLocal()) {\n return document.asJson();\n } else {\n return manager.getDocument(resolveURI(baseURI));\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((pointer == null) ? 0 : pointer.hashCode());\n result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (!(obj instanceof JsonReference)) {\n return false;\n }\n JsonReference other = (JsonReference) obj;\n if (pointer == null) {\n if (other.pointer != null) {\n return false;\n }\n } else if (!pointer.equals(other.pointer)) {\n return false;\n }\n if (uri == null) {\n if (other.uri != null) {\n return false;\n }\n } else if (!uri.equals(other.uri)) {\n return false;\n }\n return true;\n }\n\n}", "public class JsonReferenceFactory {\n\n public JsonReference create(AbstractNode node) {\n if (node == null) {\n return new JsonReference(null, null, false, false, false, node);\n }\n\n ValueNode value = getReferenceValue(node);\n if (value != null) {\n return doCreate((String) value.getValue(), value);\n } else {\n return null;\n }\n }\n\n public JsonReference create(JsonNode node) {\n if (node == null || node.isMissingNode()) {\n return new JsonReference(null, null, false, false, false, node);\n }\n\n return doCreate(getReferenceValue(node), node);\n }\n\n public JsonReference create(ScalarNode node) {\n if (node == null) {\n return new JsonReference(null, null, false, false, false, node);\n }\n\n return doCreate(node.getValue(), node);\n }\n\n /**\n * Returns a simple reference if the value node points to a definition inside the same document.\n * \n * @param baseURI\n * @param value\n * @return reference\n */\n public JsonReference createSimpleReference(URI baseURI, AbstractNode valueNode) {\n if (valueNode == null || valueNode.isArray() || valueNode.isObject()) {\n return null;\n }\n\n final Object value = valueNode.asValue().getValue();\n if (!(value instanceof String)) {\n return null;\n }\n\n String stringValue = (String) value;\n if (StringUtils.emptyToNull(stringValue) == null || stringValue.startsWith(\"#\") || stringValue.contains(\"/\")) {\n return null;\n }\n\n final Model model = valueNode.getModel();\n if (model != null) {\n JsonPointer ptr = JsonPointer.compile(\"/definitions/\" + value);\n AbstractNode target = model.find(ptr);\n if (target != null) {\n return new JsonReference.SimpleReference(baseURI, ptr, valueNode);\n }\n }\n\n return null;\n }\n\n public JsonReference doCreate(String value, Object source) {\n String notNull = StringUtils.nullToEmpty(value);\n\n URI uri;\n try {\n uri = URI.create(notNull);\n } catch (NullPointerException | IllegalArgumentException e) {\n // try to encode illegal characters, e.g. curly braces\n try {\n uri = URI.create(URLUtils.encodeURL(notNull));\n } catch (NullPointerException | IllegalArgumentException e2) {\n return new JsonReference(null, null, false, false, false, source);\n }\n }\n\n String fragment = uri.getFragment();\n JsonPointer pointer = null;\n try {\n // Pointer fails to resolve if ends with /\n if (fragment != null && fragment.length() > 1 && fragment.endsWith(\"/\")) {\n fragment = fragment.substring(0, fragment.length() - 1);\n }\n\n pointer = JsonPointer.compile(StringUtils.emptyToNull(fragment));\n } catch (IllegalArgumentException e) {\n // let the pointer be null\n }\n\n uri = uri.normalize();\n boolean absolute = uri.isAbsolute();\n boolean local = !absolute && uri.getPath().isEmpty();\n // should warn when using curly braces\n boolean warnings = notNull.contains(\"{\") || uri.toString().contains(\"}\");\n\n return new JsonReference(uri, pointer, absolute, local, warnings, source);\n }\n\n protected Boolean isReference(AbstractNode node) {\n return JsonReference.isReference(node);\n }\n\n protected ValueNode getReferenceValue(AbstractNode node) {\n if (node.isValue()) {\n return node.asValue();\n }\n AbstractNode value = node.get(PROPERTY);\n if (value != null && value.isValue()) {\n return value.asValue();\n }\n return null;\n }\n\n protected String getReferenceValue(JsonNode node) {\n return node.isTextual() ? node.asText() : node.get(PROPERTY).asText();\n }\n}", "public abstract class AbstractNode {\n\n private final Model model;\n private final JsonPointer pointer;\n private final AbstractNode parent;\n\n private String property;\n private TypeDefinition type;\n private Location start;\n private Location end;\n\n AbstractNode(Model model, AbstractNode parent, JsonPointer ptr) {\n this.model = model;\n this.parent = parent;\n this.pointer = ptr;\n }\n\n public Model getModel() {\n return model;\n }\n\n /**\n * Returns the child node that is contained at the given index.\n * \n * @param pos\n * @return node\n */\n public AbstractNode get(int index) {\n return null;\n }\n\n /**\n * Returns the child node that is contained by the given property.\n * \n * @param property\n * @return node\n */\n public AbstractNode get(String property) {\n return null;\n }\n\n /**\n * Returns true if the node is an object.\n * \n * @return true if object\n */\n public boolean isObject() {\n return false;\n }\n\n /**\n * Returns true if the node is an array.\n * \n * @return true if array\n */\n public boolean isArray() {\n return false;\n }\n\n /**\n * Returns true if the node is a value\n * \n * @return true if value\n */\n public boolean isValue() {\n return false;\n }\n\n /**\n * Returns the current node as an {@link ObjectNode} if it is an instance, or null otherwise.\n * \n * @return node\n */\n public ObjectNode asObject() {\n return null;\n }\n\n /**\n * Returns the current node as an {@link ArrayNode} if it is an instance, or null otherwise.\n * \n * @return node\n */\n public ArrayNode asArray() {\n return null;\n }\n\n /**\n * Returns the current node as an {@link ValueNode} if it is an instance, or null otherwise.\n * \n * @return node\n */\n public ValueNode asValue() {\n return null;\n }\n\n /**\n * Returns the JSON pointer that identifies this node.\n * \n * @return JSON pointer\n */\n public JsonPointer getPointer() {\n return pointer;\n }\n \n /**\n * \n * @return JSON pointer as a string\n */\n public String getPointerString() {\n return getPointer().toString();\n }\n\n public void setType(TypeDefinition type) {\n this.type = type;\n }\n\n public TypeDefinition getType() {\n return type;\n }\n\n /**\n * Returns the parent node that contains this node, or null if the node is the root node.\n * \n * @return parent node\n */\n public AbstractNode getParent() {\n return parent;\n }\n\n public String getProperty() {\n return property;\n }\n\n public void setProperty(String name) {\n this.property = name;\n }\n\n /**\n * Returns the children elements of this node.\n * \n * @return node's children\n */\n public AbstractNode[] elements() {\n return new AbstractNode[0];\n }\n\n /**\n * Returns the number of elements contained by this node.\n * \n * @return size of children\n */\n public int size() {\n return elements().length;\n }\n\n public abstract String getText();\n\n /**\n * Returns the position of the node inside the given document. <br/>\n * The position matches the area that contains all the node's content.\n * \n * @param document\n * @return position inside the document\n */\n public Position getPosition(IDocument document) {\n boolean selectEntireElement = false;\n int startLine = getStart().getLine();\n int offset = 0;\n int length = 0;\n\n int endLine = getEnd().getLine();\n int endCol = getEnd().getColumn();\n try {\n offset = document.getLineOffset(startLine);\n if (selectEntireElement) {\n length = (document.getLineOffset(endLine) + endCol) - offset;\n } else if (startLine < document.getNumberOfLines() - 1) {\n length = document.getLineOffset(startLine+1) - offset;\n } else {\n length = document.getLineLength(startLine);\n }\n } catch (BadLocationException e) {\n return new Position(0);\n }\n\n return new Position(Math.max(0, offset), length);\n }\n\n public void setStartLocation(Location start) {\n this.start = start;\n }\n\n public void setEndLocation(Location location) {\n this.end = location;\n }\n\n /**\n * Returns the start location of this node.\n * \n * @return start location\n */\n public Location getStart() {\n return start;\n }\n\n /**\n * Returns the end location of this node.\n * \n * @return end location\n */\n public Location getEnd() {\n return end;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((parent == null) ? 0 : parent.hashCode());\n result = prime * result + ((pointer == null) ? 0 : pointer.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n AbstractNode other = (AbstractNode) obj;\n\n return Objects.equals(getModel(), other.getModel()) && Objects.equals(getPointer(), other.getPointer());\n }\n\n}", "public class DocumentUtils {\n\n /**\n * Returns the currently active editor.\n * \n * @return editor\n */\n public static FileEditorInput getActiveEditorInput() {\n IEditorInput input = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()\n .getEditorInput();\n\n return input instanceof FileEditorInput ? (FileEditorInput) input : null;\n }\n\n /**\n * Returns the swagger document if exists for the given path.\n * \n * @param path\n * @return document\n * @throws IOException \n */\n public static String getDocumentContent(IPath path) throws IOException {\n if (path == null || !path.getFileExtension().matches(\"ya?ml\")) {\n return null;\n }\n\n InputStream content = null;\n IFile file = getWorkspaceFile(path);\n if (file == null) {\n IFileStore store = getExternalFile(path);\n if (store != null) {\n try {\n content = store.openInputStream(EFS.NONE, null);\n } catch (CoreException e) {\n content = null;\n }\n }\n } else if (file.exists()) {\n try {\n content = file.getContents();\n } catch (CoreException e) {\n content = null;\n }\n }\n\n if (content == null) {\n return null;\n }\n\n return StringUtils.toString(content);\n }\n\n /**\n * @param uri\n * - URI, representing an absolute path\n * @return\n */\n public static IFile getWorkspaceFile(URI uri) {\n return getWorkspaceFile(new Path(uri.getPath()));\n }\n\n /**\n * @param path\n * - absolute path to the element\n * @return\n */\n public static IFile getWorkspaceFile(IPath path) {\n IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();\n\n try {\n return root.getFileForLocation(path);\n } catch (Exception e) {\n return null;\n }\n }\n\n public static IFileStore getExternalFile(IPath path) {\n IFileStore fileStore = EFS.getLocalFileSystem().getStore(path);\n IFileInfo fileInfo = fileStore.fetchInfo();\n\n return fileInfo != null && fileInfo.exists() ? fileStore : null;\n }\n\n /**\n * Opens the editor for the given file and reveal the given region.\n * \n * @param file\n * @param region\n */\n public static void openAndReveal(IFile file, IRegion region) {\n final IEditorPart editor = openEditor(file);\n if (editor instanceof ITextEditor) {\n if (region != null) {\n ((ITextEditor) editor).selectAndReveal(region.getOffset(), region.getLength());\n }\n }\n }\n\n /**\n * Opens the editor for the file located at the given path and reveal the selection.\n * \n * @param path\n * @param selection\n */\n public static void openAndReveal(IPath path, ISelection selection) {\n final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();\n final IFile file = root.getFile(path);\n final IEditorPart editor = openEditor(file);\n\n if (editor instanceof IShowInTarget) {\n IShowInTarget showIn = (IShowInTarget) editor;\n showIn.show(new ShowInContext(null, selection));\n }\n }\n\n protected static IEditorPart openEditor(IFile file) {\n final IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();\n try {\n return IDE.openEditor(page, file);\n } catch (PartInitException e) {\n return null;\n }\n }\n}" ]
import java.net.URI; import org.eclipse.core.resources.IFile; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.ui.part.FileEditorInput; import com.fasterxml.jackson.core.JsonPointer; import com.reprezen.swagedit.core.editor.JsonDocument; import com.reprezen.swagedit.core.json.references.JsonReference; import com.reprezen.swagedit.core.json.references.JsonReferenceFactory; import com.reprezen.swagedit.core.model.AbstractNode; import com.reprezen.swagedit.core.utils.DocumentUtils;
/******************************************************************************* * Copyright (c) 2016 ModelSolv, Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * ModelSolv, Inc. - initial API and implementation and/or initial documentation *******************************************************************************/ package com.reprezen.swagedit.core.hyperlinks; public abstract class ReferenceHyperlinkDetector extends AbstractJsonHyperlinkDetector { protected final JsonReferenceFactory factory = new JsonReferenceFactory(); protected abstract JsonFileHyperlink createFileHyperlink(IRegion linkRegion, String label, IFile file, JsonPointer pointer); @Override protected abstract boolean canDetect(JsonPointer pointer); @Override protected IHyperlink[] doDetect(JsonDocument doc, ITextViewer viewer, HyperlinkInfo info, JsonPointer pointer) { URI baseURI = getBaseURI();
AbstractNode node = doc.getModel().find(pointer);
3
Divendo/math-dragon
mathdragon/src/main/java/org/teaminfty/math_dragon/view/fragments/FragmentKeyboard.java
[ "public class MathSymbolEditor extends View\n{\n /** An enum that represents the symbol we're currently editing */\n public enum EditingSymbol\n {\n FACTOR((byte) 0), PI((byte) 1), E((byte) 2), I((byte) 3), VAR((byte) 4);\n \n private byte b;\n \n private EditingSymbol(byte b)\n { this.b = b; }\n \n public byte toByte()\n { return b; }\n \n public static EditingSymbol fromByte(byte b)\n {\n switch(b)\n {\n case 0: return FACTOR;\n case 1: return PI;\n case 2: return E;\n case 3: return I;\n case 4: return VAR;\n }\n return FACTOR;\n }\n }\n \n /** A class that represents a single symbol */\n private static class SymbolRepresentation\n {\n /** The factor of this symbol */\n public String factor = \"0\";\n /** The power of the PI symbol */\n public String piPow = \"\";\n /** Whether the PI symbol is shown or not */\n public boolean showPi = false;\n /** The power of the E symbol */\n public String ePow = \"\";\n /** Whether the E symbol is shown or not */\n public boolean showE = false;\n /** The power of the imaginary unit */\n public String iPow = \"\";\n /** Whether the I symbol is shown or not */\n public boolean showI = false;\n /** The powers of the variables */\n public String[] varPowers = new String[26];\n /** The whether or not to show the variables */\n public boolean[] showVars = new boolean[26];\n \n /** Constructor */\n public SymbolRepresentation()\n {\n for(int i = 0; i < varPowers.length; ++i)\n varPowers[i] = \"\";\n }\n \n /** The factor as a string */\n private static final String BUNDLE_FACTOR = \"factor\";\n /** The PI power as a string */\n private static final String BUNDLE_PI_POW = \"pi_pow\";\n /** Whether or not to show PI, as a boolean */\n private static final String BUNDLE_PI_SHOW = \"pi_show\";\n /** The E power as a string */\n private static final String BUNDLE_E_POW = \"e_pow\";\n /** Whether or not to show E, as a boolean */\n private static final String BUNDLE_E_SHOW = \"e_show\";\n /** The i power as a string */\n private static final String BUNDLE_I_POW = \"i_pow\";\n /** Whether or not to show i, as a boolean */\n private static final String BUNDLE_I_SHOW = \"i_show\";\n /** The powers of the variables as a string array */\n private static final String BUNDLE_VAR_POWS = \"var_pows\";\n /** Whether or not to show the variables as an boolean array */\n private static final String BUNDLE_VAR_SHOW = \"var_show\";\n \n /** Stores the representation as a bundle */\n public Bundle toBundle()\n {\n // The bundle we're going to return\n Bundle out = new Bundle();\n \n // Store all values\n out.putString(BUNDLE_FACTOR, factor);\n out.putString(BUNDLE_PI_POW, piPow);\n out.putBoolean(BUNDLE_PI_SHOW, showPi);\n out.putString(BUNDLE_E_POW, ePow);\n out.putBoolean(BUNDLE_E_SHOW, showE);\n out.putString(BUNDLE_I_POW, iPow);\n out.putBoolean(BUNDLE_I_SHOW, showI);\n out.putStringArray(BUNDLE_VAR_POWS, varPowers);\n out.putBooleanArray(BUNDLE_VAR_SHOW, showVars);\n \n // Return the result\n return out;\n }\n \n /** Constructs a {@link SymbolRepresentation} from the given {@link Bundle}\n * @param bundle The bundle to construct from\n * @return The created {@link SymbolRepresentation} */\n public static SymbolRepresentation fromBundle(Bundle bundle)\n {\n // This will be our output\n SymbolRepresentation out = new SymbolRepresentation();\n \n // Load the values\n out.factor = bundle.getString(BUNDLE_FACTOR);\n out.piPow = bundle.getString(BUNDLE_PI_POW);\n out.showPi = bundle.getBoolean(BUNDLE_PI_SHOW);\n out.ePow = bundle.getString(BUNDLE_E_POW);\n out.showE = bundle.getBoolean(BUNDLE_E_SHOW);\n out.iPow = bundle.getString(BUNDLE_I_POW);\n out.showI = bundle.getBoolean(BUNDLE_I_SHOW);\n out.varPowers = bundle.getStringArray(BUNDLE_VAR_POWS);\n out.showVars = bundle.getBooleanArray(BUNDLE_VAR_SHOW);\n \n // Return the result\n return out;\n }\n \n /** Constructs a {@link Symbol} from the current values\n * @return The constructed {@link Symbol} */\n public Symbol getMathSymbol()\n {\n // The MathSymbol we're going to return\n Symbol out = new Symbol();\n \n // Set the factor\n if(factor.isEmpty())\n out.setFactor(symbolVisible() ? 1 : 0);\n else\n out.setFactor(factor.equals(\"-\") ? -1 : Double.parseDouble(factor));\n \n // Set the PI power\n if(showPi)\n out.setPiPow(piPow.isEmpty() ? 1 : (piPow.equals(\"-\") ? -1 : Long.parseLong(piPow)) );\n\n // Set the E power\n if(showE)\n out.setEPow(ePow.isEmpty() ? 1 : (ePow.equals(\"-\") ? -1 : Long.parseLong(ePow)) );\n\n // Set the I power\n if(showI)\n out.setIPow(iPow.isEmpty() ? 1 : (iPow.equals(\"-\") ? -1 : Long.parseLong(iPow)) );\n \n // Set the powers for the variables\n for(int i = 0; i < varPowers.length && i < out.varPowCount(); ++i)\n {\n if(showVars[i])\n out.setVarPow(i, varPowers[i].isEmpty() ? 1 : (varPowers[i].equals(\"-\") ? -1 : Long.parseLong(varPowers[i])) );\n }\n \n // Return the result\n return out;\n }\n \n /** Returns whether or not some symbols (i.e. variables or the constants pi, e, i) are visible\n * @return True if one or more symbols are visible, false otherwise */\n public boolean symbolVisible()\n {\n if(showPi || showE || showI)\n return true;\n for(int i = 0; i < showVars.length; ++i)\n {\n if(showVars[i])\n return true;\n }\n return false;\n }\n }\n \n /** The symbols in this editor */\n private ArrayList<SymbolRepresentation> symbols = new ArrayList<SymbolRepresentation>();\n \n /** The symbol representation we're currently editing */\n private int editingIndex = 0;\n /** The symbol we're currently editing */\n private EditingSymbol editingSymbol = EditingSymbol.FACTOR;\n /** The variable we're currently editing */\n private char currVar = 'a';\n \n /** The paint that is used to draw the factor and the symbols */\n protected Paint paint = new Paint();\n \n /** The text size factor for exponents */\n protected static final float EXPONENT_FACTOR = 1.0f / 2;\n\n public MathSymbolEditor(Context context)\n {\n super(context);\n initPaints();\n symbols.add(new SymbolRepresentation());\n gestureDetector = new GestureDetector(getContext(), new GestureListener());\n }\n\n public MathSymbolEditor(Context context, AttributeSet attrs)\n {\n super(context, attrs);\n initPaints();\n symbols.add(new SymbolRepresentation());\n gestureDetector = new GestureDetector(getContext(), new GestureListener());\n }\n\n public MathSymbolEditor(Context context, AttributeSet attrs, int defStyleAttr)\n {\n super(context, attrs, defStyleAttr);\n initPaints();\n symbols.add(new SymbolRepresentation());\n gestureDetector = new GestureDetector(getContext(), new GestureListener());\n }\n\n /** Initialises the paints */\n private void initPaints()\n {\n paint.setTypeface(TypefaceHolder.dejavuSans);\n paint.setAntiAlias(true);\n paint.setTextSize(getResources().getDimensionPixelSize(R.dimen.math_symbol_editor_font_size));\n }\n \n /** The prefix for the bundles containing the symbol representations */\n private static final String BUNDLE_SYMBOL_REP_PREFIX = \"symbol_rep_\";\n /** An int containing the index of the symbol representation we were editing */\n private static final String BUNDLE_EDITING_INDEX = \"editing_index\";\n /** A byte containing which symbol we were editing */\n private static final String BUNDLE_CURR_SYMBOL = \"curr_symbol\";\n /** A char containing which variable we were editing */\n private static final String BUNDLE_CURR_VAR = \"curr_var\";\n \n /** Saves the current state to a bundle\n * @return The bundle containing the current state */\n public Bundle toBundle()\n {\n // The bundle we're going to return\n Bundle out = new Bundle();\n \n // Store all values\n for(int i = 0; i < symbols.size(); ++i)\n out.putBundle(BUNDLE_SYMBOL_REP_PREFIX + Integer.toString(i), symbols.get(i).toBundle());\n \n // Store the state\n out.putInt(BUNDLE_EDITING_INDEX, editingIndex);\n out.putByte(BUNDLE_CURR_SYMBOL, editingSymbol.toByte());\n out.putChar(BUNDLE_CURR_VAR, currVar);\n \n // Return the result\n return out;\n }\n \n /** Loads the state from the given bundle\n * @param bundle The bundle to load the state from */\n public void fromBundle(Bundle bundle)\n {\n // Load all values\n symbols = new ArrayList<MathSymbolEditor.SymbolRepresentation>();\n for(int i = 0; bundle.containsKey(BUNDLE_SYMBOL_REP_PREFIX + Integer.toString(i)); ++i)\n symbols.add(SymbolRepresentation.fromBundle(bundle.getBundle(BUNDLE_SYMBOL_REP_PREFIX + Integer.toString(i))));\n \n // Restore the state\n editingIndex = bundle.getInt(BUNDLE_EDITING_INDEX);\n editingSymbol = EditingSymbol.fromByte(bundle.getByte(BUNDLE_CURR_SYMBOL));\n currVar = bundle.getChar(BUNDLE_CURR_VAR);\n \n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** Sets the variable we're currently editing.\n * @param name The name of the variable */\n public void setCurrVar(char name)\n {\n currVar = name;\n invalidate();\n }\n \n /** Returns the name of the variable we're currently editing\n * @return The name of the variable we're currently editing */\n public char getCurrVar()\n { return currVar; }\n \n /** Set the symbol we're currently editing\n * @param newSymbol The symbol we're editing from now on */\n public void setEditingSymbol(EditingSymbol newSymbol)\n {\n // Set the new symbol\n editingSymbol = newSymbol;\n \n // Redraw\n invalidate();\n \n // Request a scroll\n callOnScrollToListener();\n }\n \n /** Toggle the symbol we're currently editing for the given variable name\n * @param varName The name of the variable we're toggling */\n public void toggleEditingSymbol(char varName)\n {\n if(editingSymbol == EditingSymbol.VAR)\n {\n if(currVar == varName)\n toggleEditingSymbol(EditingSymbol.FACTOR);\n else\n {\n // Set the current variable\n setCurrVar(varName);\n \n // Show the current variable (if it isn't visible already)\n final int currVarIndex = currVar - 'a';\n if(!symbols.get(editingIndex).showVars[currVarIndex])\n {\n symbols.get(editingIndex).varPowers[currVarIndex] = \"\";\n symbols.get(editingIndex).showVars[currVarIndex] = true;\n if(symbols.get(editingIndex).factor.equals(\"0\"))\n symbols.get(editingIndex).factor = \"\";\n else if(symbols.get(editingIndex).factor.equals(\"-0\"))\n symbols.get(editingIndex).factor = \"-\";\n }\n\n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n }\n else\n {\n setCurrVar(varName);\n toggleEditingSymbol(EditingSymbol.VAR);\n }\n }\n\n /** Toggle the symbol we're currently editing\n * @param symbol The symbol we're toggling */\n public void toggleEditingSymbol(EditingSymbol newSymbol)\n {\n // We may wan't to adjust something in the factor / powers\n switch(newSymbol)\n {\n case PI:\n if(editingSymbol == EditingSymbol.PI)\n setEditingSymbol(EditingSymbol.FACTOR);\n else\n {\n if(!symbols.get(editingIndex).showPi)\n {\n symbols.get(editingIndex).piPow = \"\";\n symbols.get(editingIndex).showPi = true;\n if(symbols.get(editingIndex).factor.equals(\"0\"))\n symbols.get(editingIndex).factor = \"\";\n else if(symbols.get(editingIndex).factor.equals(\"-0\"))\n symbols.get(editingIndex).factor = \"-\";\n }\n setEditingSymbol(EditingSymbol.PI);\n }\n break;\n\n case E:\n if(editingSymbol == EditingSymbol.E)\n setEditingSymbol(EditingSymbol.FACTOR);\n else\n {\n if(!symbols.get(editingIndex).showE)\n {\n symbols.get(editingIndex).ePow = \"\";\n symbols.get(editingIndex).showE = true;\n if(symbols.get(editingIndex).factor.equals(\"0\"))\n symbols.get(editingIndex).factor = \"\";\n else if(symbols.get(editingIndex).factor.equals(\"-0\"))\n symbols.get(editingIndex).factor = \"-\";\n }\n setEditingSymbol(EditingSymbol.E);\n }\n break;\n\n case I:\n if(editingSymbol == EditingSymbol.I)\n setEditingSymbol(EditingSymbol.FACTOR);\n else\n {\n if(!symbols.get(editingIndex).showI)\n {\n symbols.get(editingIndex).iPow = \"\";\n symbols.get(editingIndex).showI = true;\n if(symbols.get(editingIndex).factor.equals(\"0\"))\n symbols.get(editingIndex).factor = \"\";\n else if(symbols.get(editingIndex).factor.equals(\"-0\"))\n symbols.get(editingIndex).factor = \"-\";\n }\n setEditingSymbol(EditingSymbol.I);\n }\n break;\n\n case VAR:\n if(editingSymbol == EditingSymbol.VAR)\n setEditingSymbol(EditingSymbol.FACTOR);\n else\n {\n final int currVarIndex = currVar - 'a';\n if(!symbols.get(editingIndex).showVars[currVarIndex])\n {\n symbols.get(editingIndex).varPowers[currVarIndex] = \"\";\n symbols.get(editingIndex).showVars[currVarIndex] = true;\n if(symbols.get(editingIndex).factor.equals(\"0\"))\n symbols.get(editingIndex).factor = \"\";\n else if(symbols.get(editingIndex).factor.equals(\"-0\"))\n symbols.get(editingIndex).factor = \"-\";\n }\n setEditingSymbol(EditingSymbol.VAR);\n }\n break;\n \n default:\n setEditingSymbol(newSymbol);\n break;\n }\n\n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n\n /** Get the symbol we're currently editing\n * @param The symbol we're currently editing */\n public EditingSymbol getEditingSymbol()\n { return editingSymbol; }\n\n /** Converts a <tt>double</tt> to a string, dropping <tt>\".0\"</tt> if necessary.\n * Also returns, for example, <tt>\"0.002\"</tt> instead of <tt>\"2.0E-3\"</tt>.\n * @param x The <tt>double</tt> to convert\n * @return The <tt>double</tt> as a string */\n private String doubleToString(double x)\n {\n // Convert the double to a string\n String str = Double.toString(x);\n \n // Search for an 'E'\n final int ePos = str.indexOf('E');\n if(ePos != -1)\n {\n // Determine the amount of zeros and whether they need to be appended or prepended\n int zeros = Integer.parseInt(str.substring(ePos + 1));\n final boolean append = zeros >= 0;\n if(!append)\n zeros = (-zeros) - 1;\n \n // Remember the part before the 'E'\n String before = str.substring(0, ePos);\n final int dotPos = before.indexOf('.');\n if(dotPos != -1)\n {\n String tmp = before.substring(dotPos + 1);\n while(tmp.endsWith(\"0\"))\n tmp = tmp.substring(0, tmp.length() - 1);\n before = before.substring(0, dotPos) + tmp;\n \n if(append)\n zeros -= tmp.length();\n if(zeros < 0)\n before = before.substring(0, before.length() + zeros) + '.' + before.substring(before.length() + zeros);\n }\n boolean negative = before.startsWith(\"-\");\n if(negative)\n before = before.substring(1);\n \n // Prepend/append the zeros\n while(zeros > 0)\n {\n if(append)\n before += '0';\n else\n before = '0' + before;\n --zeros;\n }\n if(!append)\n before = \"0.\" + before;\n \n // Put back the minus sign\n if(negative)\n before = '-' + before;\n \n // Remember the result\n str = before;\n }\n \n // Chop off unnecessary '.' and '0'\n while(str.contains(\".\") && (str.endsWith(\".\") || str.endsWith(\"0\")))\n str = str.substring(0, str.length() - 1);\n \n // Return the string\n return str;\n }\n\n /** Resets the symbol in this editor */\n public void reset()\n {\n // Start with a single 0 again\n symbols = new ArrayList<MathSymbolEditor.SymbolRepresentation>();\n symbols.add(new SymbolRepresentation());\n editingIndex = 0;\n \n // We'll be editing the factor again\n setEditingSymbol(EditingSymbol.FACTOR);\n\n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** Copies the values from the given {@link Symbol}\n * @param expr The {@link Expression} to copy the values from */\n public void fromExpression(Expression expr)\n {\n // Reset all values\n reset();\n \n // Set the expression\n symbols.clear();\n fromExprHelper(expr, false);\n if(symbols.size() == 0)\n symbols.add(new SymbolRepresentation());\n\n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** Helper for {@link MathSymbolEditor#fromExpression(Expression) fromExpression()}\n * @param expr The expression to add\n * @param negate Whether or not to negate the expression */\n private void fromExprHelper(Expression expr, boolean negate)\n {\n if(expr instanceof Symbol)\n {\n Symbol mathSymbol = (Symbol) expr;\n SymbolRepresentation symbol = new SymbolRepresentation();\n \n // Set the factor\n symbol.factor = doubleToString(mathSymbol.getFactor());\n \n // If the factor is not 0, we need to set the powers (and their visibility)\n if(mathSymbol.getFactor() != 0)\n {\n // PI\n if(mathSymbol.getPiPow() != 0)\n {\n if(mathSymbol.getPiPow() != 1)\n symbol.piPow = Long.toString(mathSymbol.getPiPow());\n symbol.showPi = true;\n }\n \n // E\n if(mathSymbol.getEPow() != 0)\n {\n if(mathSymbol.getEPow() != 1)\n symbol.ePow = Long.toString(mathSymbol.getEPow());\n symbol.showE = true;\n }\n \n // I\n if(mathSymbol.getIPow() != 0)\n {\n if(mathSymbol.getIPow() != 1)\n symbol.iPow = Long.toString(mathSymbol.getIPow());\n symbol.showI = true;\n }\n \n // Variables\n for(int i = 0; i < mathSymbol.varPowCount() && i < symbol.varPowers.length; ++i)\n {\n if(mathSymbol.getVarPow(i) != 0)\n {\n if(mathSymbol.getVarPow(i) != 1)\n symbol.varPowers[i] = Long.toString(mathSymbol.getVarPow(i));\n symbol.showVars[i] = true;\n }\n }\n }\n \n // Negate (if necessary)\n if(negate)\n {\n if(symbol.factor.startsWith(\"-\"))\n symbol.factor = symbol.factor.substring(1);\n else\n symbol.factor = '-' + symbol.factor;\n }\n \n // Beautify the display\n if(symbol.symbolVisible())\n {\n if(symbol.factor.equals(\"1\"))\n symbol.factor = \"\";\n else if(symbol.factor.equals(\"-1\"))\n symbol.factor = \"-\";\n }\n \n // Add the symbol to the list\n symbols.add(symbol);\n }\n else if(expr instanceof Empty)\n {\n // Simply add a 0\n SymbolRepresentation rep = new SymbolRepresentation();\n rep.factor = negate ? \"-0\" : \"0\";\n symbols.add(rep);\n }\n else if(expr instanceof Add)\n {\n fromExprHelper(expr.getChild(0), false);\n fromExprHelper(expr.getChild(1), false);\n }\n else if(expr instanceof Subtract)\n {\n fromExprHelper(expr.getChild(0), false);\n fromExprHelper(expr.getChild(1), true);\n }\n }\n \n /** Constructs a {@link Expression} from the current values\n * @return The constructed {@link Expression} */\n public Expression getExpression()\n {\n // If we contain only one symbol, we simply return that symbol\n if(symbols.size() == 1)\n return symbols.get(0).getMathSymbol();\n \n // This will be the left operand of the next add or subtract operation\n Expression nextLeft = symbols.get(0).getMathSymbol();\n \n // Loop through all symbols\n for(int i = 1; i < symbols.size(); ++i)\n {\n // Determine whether we'll create a add or a subtract operation\n if(symbols.get(i).factor.startsWith(\"-\"))\n {\n symbols.get(i).factor = symbols.get(i).factor.substring(1);\n nextLeft = new Subtract(nextLeft, symbols.get(i).getMathSymbol());\n symbols.get(i).factor = '-' + symbols.get(i).factor;\n }\n else\n nextLeft = new Add(nextLeft, symbols.get(i).getMathSymbol());\n }\n \n // Return the result\n return nextLeft;\n }\n\n @Override\n protected void onMeasure(int widthSpec, int heightSpec)\n {\n // Get the size we want to take\n final Rect size = getTextBounds();\n \n // Determine the width we'll take\n int width = size.width() + 2 * getResources().getDimensionPixelSize(R.dimen.math_symbol_editor_padding);\n switch(View.MeasureSpec.getMode(widthSpec))\n {\n case View.MeasureSpec.EXACTLY:\n width = View.MeasureSpec.getSize(widthSpec);\n break;\n \n case View.MeasureSpec.AT_MOST:\n width = Math.min(width, View.MeasureSpec.getSize(widthSpec));\n break;\n }\n \n // Determine the height we'll take\n int height = size.height();\n switch(View.MeasureSpec.getMode(heightSpec))\n {\n case View.MeasureSpec.EXACTLY:\n height = View.MeasureSpec.getSize(heightSpec);\n break;\n \n case View.MeasureSpec.AT_MOST:\n height = Math.min(height, View.MeasureSpec.getSize(heightSpec));\n break;\n }\n \n // Return our size\n setMeasuredDimension(width, height);\n }\n \n @Override\n protected void onLayout(boolean changed, int left, int top, int right, int bottom)\n {\n // Call the parent\n super.onLayout(changed, left, top, right, bottom);\n \n // Request a scroll\n callOnScrollToListener();\n }\n \n /** Converts the number in the given string to superscript\n * @param str The string that is to be converted to superscript\n * @return The superscript of the given string\n */\n private String toSuperScript(String str)\n {\n // The string we're going to return\n String out = \"\";\n \n // Loop through all characters\n for(int i = 0; i < str.length(); ++i)\n {\n switch(str.charAt(i))\n {\n case '-': out += '\\u207b'; break;\n case '0': out += '\\u2070'; break;\n case '1': out += '\\u00b9'; break;\n case '2': out += '\\u00b2'; break;\n case '3': out += '\\u00b3'; break;\n case '4': out += '\\u2074'; break;\n case '5': out += '\\u2075'; break;\n case '6': out += '\\u2076'; break;\n case '7': out += '\\u2077'; break;\n case '8': out += '\\u2078'; break;\n case '9': out += '\\u2079'; break;\n }\n }\n \n // Return the result\n return out;\n }\n \n @SuppressLint(\"DrawAllocation\")\n @Override\n protected void onDraw(Canvas canvas)\n {\n // Translate the canvas\n final Rect totalTextBounds = getTextBounds();\n canvas.translate((canvas.getWidth() - totalTextBounds.width()) / 2, (canvas.getHeight() - totalTextBounds.height()) / 2);\n \n // Distinguish the parts of the string\n String[] parts = {\"\", \"\", \"\"};\n int currentPart = 0;\n \n // Loop through all symbols\n for(int i = 0; i < symbols.size(); ++i)\n {\n SymbolRepresentation symbol = symbols.get(i);\n \n if(editingIndex == i && editingSymbol == EditingSymbol.FACTOR)\n ++currentPart;\n if(i != 0 && !symbol.factor.startsWith(\"-\"))\n parts[currentPart] += '+';\n parts[currentPart] += symbol.factor;\n if(editingIndex == i && editingSymbol == EditingSymbol.FACTOR)\n ++currentPart;\n \n if(editingIndex == i && editingSymbol == EditingSymbol.PI)\n ++currentPart;\n if(symbol.showPi)\n parts[currentPart] += '\\u03c0' + toSuperScript(symbol.piPow);\n if(editingIndex == i && editingSymbol == EditingSymbol.PI)\n ++currentPart;\n \n if(editingIndex == i && editingSymbol == EditingSymbol.E)\n ++currentPart;\n if(symbol.showE)\n parts[currentPart] += 'e' + toSuperScript(symbol.ePow);\n if(editingIndex == i && editingSymbol == EditingSymbol.E)\n ++currentPart;\n \n if(editingIndex == i && editingSymbol == EditingSymbol.I)\n ++currentPart;\n if(symbol.showI)\n parts[currentPart] += '\\u03b9' + toSuperScript(symbol.iPow);\n if(editingIndex == i && editingSymbol == EditingSymbol.I)\n ++currentPart;\n \n for(int j = 0; j < symbol.varPowers.length; ++j)\n {\n final char chr = (char) ('a' + j);\n \n if(editingIndex == i && editingSymbol == EditingSymbol.VAR && currVar == chr)\n ++currentPart;\n if(symbol.showVars[j])\n parts[currentPart] += chr + toSuperScript(symbol.varPowers[j]);\n if(editingIndex == i && editingSymbol == EditingSymbol.VAR && currVar == chr)\n ++currentPart;\n }\n }\n \n // Keep track of the current x position\n int x = 0;\n \n // Draw the parts\n if(parts[0] != \"\")\n {\n paint.setColor(getResources().getColor(R.color.black));\n canvas.drawText(parts[0], x - totalTextBounds.left, -totalTextBounds.top, paint);\n \n x += paint.measureText(parts[0]);\n }\n if(parts[1] != \"\")\n {\n paint.setColor(getResources().getColor(R.color.blue));\n canvas.drawText(parts[1], x - totalTextBounds.left, -totalTextBounds.top, paint);\n \n x += paint.measureText(parts[1]);\n }\n if(parts[2] != \"\")\n {\n paint.setColor(getResources().getColor(R.color.black));\n canvas.drawText(parts[2], x - totalTextBounds.left, -totalTextBounds.top, paint);\n \n x += paint.measureText(parts[2]);\n }\n \n // Restore the canvas translation\n canvas.restore();\n }\n\n /** Calculates the bounds of the text in this {@link MathSymbolEditor}\n * @return The bounds of the text in this {@link MathSymbolEditor}\n */\n protected Rect getTextBounds()\n {\n // Determine the string we're going to draw\n String drawMe = \"\";\n for(SymbolRepresentation symbol : symbols)\n {\n if(!drawMe.isEmpty() && !symbol.factor.startsWith(\"-\"))\n drawMe += '+';\n drawMe += symbol.factor;\n if(symbol.showPi)\n drawMe += '\\u03c0' + toSuperScript(symbol.piPow);\n if(symbol.showE)\n drawMe += 'e' + toSuperScript(symbol.ePow);\n if(symbol.showI)\n drawMe += '\\u03b9' + toSuperScript(symbol.iPow);\n for(int i = 0; i < symbol.varPowers.length; ++i)\n {\n if(symbol.showVars[i])\n drawMe += (char) ('a' + i) + toSuperScript(symbol.varPowers[i]);\n }\n }\n \n // Determine and return the text bounds\n Rect bounds = new Rect();\n paint.getTextBounds(drawMe, 0, drawMe.length(), bounds);\n return bounds;\n }\n \n /** Negates the factor or the power of the symbol we're currently editing */\n public void negate()\n {\n // Negate the right string\n switch(editingSymbol)\n {\n case FACTOR:\n if(symbols.get(editingIndex).factor.startsWith(\"-\"))\n symbols.get(editingIndex).factor = symbols.get(editingIndex).factor.substring(1);\n else\n symbols.get(editingIndex).factor = '-' + symbols.get(editingIndex).factor;\n break;\n \n case PI:\n if(symbols.get(editingIndex).piPow.startsWith(\"-\"))\n symbols.get(editingIndex).piPow = symbols.get(editingIndex).piPow.substring(1);\n else\n symbols.get(editingIndex).piPow = '-' + symbols.get(editingIndex).piPow;\n break;\n \n case E:\n if(symbols.get(editingIndex).ePow.startsWith(\"-\"))\n symbols.get(editingIndex).ePow = symbols.get(editingIndex).ePow.substring(1);\n else\n symbols.get(editingIndex).ePow = '-' + symbols.get(editingIndex).ePow;\n break;\n \n case I:\n if(symbols.get(editingIndex).iPow.startsWith(\"-\"))\n symbols.get(editingIndex).iPow = symbols.get(editingIndex).iPow.substring(1);\n else\n symbols.get(editingIndex).iPow = '-' + symbols.get(editingIndex).iPow;\n break;\n \n case VAR:\n {\n final int currVarIndex = currVar - 'a';\n if(symbols.get(editingIndex).varPowers[currVarIndex].startsWith(\"-\"))\n symbols.get(editingIndex).varPowers[currVarIndex] = symbols.get(editingIndex).varPowers[currVarIndex].substring(1);\n else\n symbols.get(editingIndex).varPowers[currVarIndex] = '-' + symbols.get(editingIndex).varPowers[currVarIndex];\n }\n break;\n }\n \n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** The amount of numbers before the dot (if there is one) the current symbol we're editing contains\n * @return The amount of numbers before the dot as an integer */\n public int numberCount()\n {\n String str = \"\";\n switch(editingSymbol)\n {\n case FACTOR: str = symbols.get(editingIndex).factor; break;\n case PI: str = symbols.get(editingIndex).piPow; break;\n case E: str = symbols.get(editingIndex).ePow; break;\n case I: str = symbols.get(editingIndex).iPow; break;\n case VAR: str = symbols.get(editingIndex).varPowers[currVar - 'a']; break;\n }\n \n if(str.startsWith(\"-\"))\n str = str.substring(1);\n \n final int dotPos = str.indexOf('.');\n if(dotPos == -1) return str.length();\n return dotPos;\n }\n \n /** Whether or not the current symbol we're editing contains a dot\n * @return <tt>true</tt> if the current symbol we're editing contains a dot, <tt>false</tt> otherwise */\n public boolean containsDot()\n {\n String str = \"\";\n switch(editingSymbol)\n {\n case FACTOR: str = symbols.get(editingIndex).factor; break;\n case PI: str = symbols.get(editingIndex).piPow; break;\n case E: str = symbols.get(editingIndex).ePow; break;\n case I: str = symbols.get(editingIndex).iPow; break;\n case VAR: str = symbols.get(editingIndex).varPowers[currVar - 'a']; break;\n }\n return str.contains(\".\");\n }\n \n /** The amount of decimals the current symbol we're editing contains\n * @return The amount of decimals as an integer */\n public int decimalCount()\n {\n String str = \"\";\n switch(editingSymbol)\n {\n case FACTOR: str = symbols.get(editingIndex).factor; break;\n case PI: str = symbols.get(editingIndex).piPow; break;\n case E: str = symbols.get(editingIndex).ePow; break;\n case I: str = symbols.get(editingIndex).iPow; break;\n case VAR: str = symbols.get(editingIndex).varPowers[currVar - 'a']; break;\n }\n \n final int dotPos = str.indexOf('.');\n if(dotPos == -1) return 0;\n return str.length() - dotPos - 1;\n }\n\n /** Adds a dot to the factor */\n public void dot()\n {\n // We only add a dot to the factor\n if(editingSymbol != EditingSymbol.FACTOR) return;\n \n // If the factor already contains a dot, we do nothing\n if(symbols.get(editingIndex).factor.contains(\".\")) return;\n \n // Add the dot\n if(symbols.get(editingIndex).factor.equals(\"-\") || symbols.get(editingIndex).factor.isEmpty())\n symbols.get(editingIndex).factor += \"0.\";\n else\n symbols.get(editingIndex).factor += '.';\n \n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** Adds a new symbol */\n public void plus()\n {\n // Whether or not we still have to add a new symbol\n boolean addSym = true;\n \n // If the last symbol is nothing but a 0, we make that our new symbol\n SymbolRepresentation lastSym = symbols.get(symbols.size() - 1);\n if(!lastSym.symbolVisible())\n {\n if(lastSym.factor.equals(\"0\"))\n addSym = false;\n if(lastSym.factor.equals(\"-0\"))\n {\n lastSym.factor = \"0\";\n addSym = false;\n }\n }\n \n // Add a 0\n if(addSym)\n symbols.add(new SymbolRepresentation());\n \n // Set the editing index\n editingIndex = symbols.size() - 1;\n \n // We'll be editing the factor\n setEditingSymbol(EditingSymbol.FACTOR);\n \n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** Subtracts a new symbol */\n public void subtract()\n {\n // Whether or not we still have to add a new symbol\n boolean addSym = true;\n \n // If the last symbol is nothing but a 0, we make that our new symbol\n SymbolRepresentation lastSym = symbols.get(symbols.size() - 1);\n if(!lastSym.symbolVisible())\n {\n if(lastSym.factor.equals(\"0\"))\n {\n lastSym.factor = \"-0\";\n addSym = false;\n }\n if(lastSym.factor.equals(\"-0\"))\n addSym = false;\n }\n \n // Subtract a 0\n if(addSym)\n {\n symbols.add(new SymbolRepresentation());\n symbols.get(symbols.size() - 1).factor = \"-0\";\n }\n \n // Set the editing index\n editingIndex = symbols.size() - 1;\n \n // We'll be editing the factor\n setEditingSymbol(EditingSymbol.FACTOR);\n \n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** Adds the given number to the symbol we're currently editing\n * @param number The number to add */\n public void addNumber(int number)\n {\n // The number as a string\n final String nStr = Integer.toString(number);\n \n // Add the number\n switch(editingSymbol)\n {\n case FACTOR:\n if(symbols.get(editingIndex).factor.equals(\"0\"))\n symbols.get(editingIndex).factor = nStr;\n else if(symbols.get(editingIndex).factor.equals(\"-0\"))\n symbols.get(editingIndex).factor = '-' + nStr;\n else if(!symbols.get(editingIndex).factor.isEmpty() || !nStr.equals(\"0\"))\n symbols.get(editingIndex).factor += nStr;\n break;\n \n case PI:\n if(symbols.get(editingIndex).piPow.equals(\"0\"))\n symbols.get(editingIndex).piPow = nStr;\n else if(symbols.get(editingIndex).piPow.equals(\"-0\"))\n symbols.get(editingIndex).piPow = '-' + nStr;\n else if(!symbols.get(editingIndex).piPow.isEmpty() || !nStr.equals(\"0\"))\n symbols.get(editingIndex).piPow += nStr;\n break;\n \n case E:\n if(symbols.get(editingIndex).ePow.equals(\"0\"))\n symbols.get(editingIndex).ePow = nStr;\n else if(symbols.get(editingIndex).ePow.equals(\"-0\"))\n symbols.get(editingIndex).ePow = '-' + nStr;\n else if(!symbols.get(editingIndex).ePow.isEmpty() || !nStr.equals(\"0\"))\n symbols.get(editingIndex).ePow += nStr;\n break;\n \n case I:\n if(symbols.get(editingIndex).iPow.equals(\"0\"))\n symbols.get(editingIndex).iPow = nStr;\n else if(symbols.get(editingIndex).iPow.equals(\"-0\"))\n symbols.get(editingIndex).iPow = '-' + nStr;\n else if(!symbols.get(editingIndex).iPow.isEmpty() || !nStr.equals(\"0\"))\n symbols.get(editingIndex).iPow += nStr;\n break;\n \n case VAR:\n {\n final int currVarIndex = currVar - 'a';\n if(symbols.get(editingIndex).varPowers[currVarIndex].equals(\"0\"))\n symbols.get(editingIndex).varPowers[currVarIndex] = nStr;\n else if(symbols.get(editingIndex).varPowers[currVarIndex].equals(\"-0\"))\n symbols.get(editingIndex).varPowers[currVarIndex] = '-' + nStr;\n else if(!symbols.get(editingIndex).varPowers[currVarIndex].isEmpty() || !nStr.equals(\"0\"))\n symbols.get(editingIndex).varPowers[currVarIndex] += nStr;\n }\n break;\n }\n \n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** Deletes the last number from the current symbol.\n * Note: this method might change the symbol that currently being editted. */\n public void deleteNumber()\n {\n // Delete one character from the number\n switch(editingSymbol)\n {\n case FACTOR:\n if(symbols.get(editingIndex).factor.length() != 0)\n symbols.get(editingIndex).factor = symbols.get(editingIndex).factor.substring(0, symbols.get(editingIndex).factor.length() - 1);\n break;\n \n case PI:\n if(symbols.get(editingIndex).piPow.length() != 0)\n symbols.get(editingIndex).piPow = symbols.get(editingIndex).piPow.substring(0, symbols.get(editingIndex).piPow.length() - 1);\n else\n {\n symbols.get(editingIndex).showPi = false;\n setEditingSymbol(EditingSymbol.FACTOR);\n }\n break;\n \n case E:\n if(symbols.get(editingIndex).ePow.length() != 0)\n symbols.get(editingIndex).ePow = symbols.get(editingIndex).ePow.substring(0, symbols.get(editingIndex).ePow.length() - 1);\n else\n {\n symbols.get(editingIndex).showE = false;\n setEditingSymbol(EditingSymbol.FACTOR);\n }\n break;\n\n case I:\n if(symbols.get(editingIndex).iPow.length() != 0)\n symbols.get(editingIndex).iPow = symbols.get(editingIndex).iPow.substring(0, symbols.get(editingIndex).iPow.length() - 1);\n else\n {\n symbols.get(editingIndex).showI = false;\n setEditingSymbol(EditingSymbol.FACTOR);\n }\n break;\n \n case VAR:\n {\n final int currVarIndex = currVar - 'a';\n if(symbols.get(editingIndex).varPowers[currVarIndex].length() != 0)\n symbols.get(editingIndex).varPowers[currVarIndex] = symbols.get(editingIndex).varPowers[currVarIndex].substring(0, symbols.get(editingIndex).varPowers[currVarIndex].length() - 1);\n else\n {\n symbols.get(editingIndex).showVars[currVarIndex] = false;\n setEditingSymbol(EditingSymbol.FACTOR);\n }\n }\n break;\n }\n \n // If nothing is shown, we show a 0\n if(symbols.get(editingIndex).factor.length() == 0 && !symbols.get(editingIndex).symbolVisible())\n symbols.get(editingIndex).factor = \"0\";\n \n // If we're only showing a 0 and we're not the only symbol, delete the entire symbol and start editing the previous one\n if(symbols.get(editingIndex).factor.equals(\"0\") && symbols.size() > 1)\n {\n symbols.remove(editingIndex);\n setEditingSymbol(EditingSymbol.FACTOR);\n if(editingIndex != 0) --editingIndex;\n }\n \n // Redraw and recalculate the size\n invalidate();\n requestLayout();\n }\n \n /** A listener that can be implemented to listen for state change events.\n * This events are only fired if the state change is initiated by this View itself. */\n public interface OnStateChangeListener\n {\n /** Called when the state changes */\n public void stateChanged();\n }\n \n /** The current {@link OnStateChangeListener} */\n private OnStateChangeListener onStateChangeListener = null;\n \n /** Set the current {@link OnStateChangeListener}\n * @param listener The new {@link OnStateChangeListener} */\n public void setStateChangeListener(OnStateChangeListener listener)\n { onStateChangeListener = listener; }\n \n /** A listener that's called when the editor should be scrolled */\n public interface OnScrollToListener\n {\n /** Called when the editor should be scrolled to a certain position\n * @param left The left side of the currently active part\n * @param right The right side of the currently active part */\n public void scroll(int left, int right);\n }\n \n /** The current {@link OnScrollToListener} */\n private OnScrollToListener onScrollToListener = null;\n \n /** Set the {@link OnScrollToListener}\n * @param listener The new {@link OnScrollToListener} */\n public void setOnScrollToListener(OnScrollToListener listener)\n { onScrollToListener = listener; }\n \n /** Calls the {@link OnScrollToListener} */\n private void callOnScrollToListener()\n {\n // If no listener is set, we've nothing to do here\n if(onScrollToListener == null) return;\n\n // Get the string parts\n StringBuilder totalStrBuilder = new StringBuilder();\n ArrayList<StringPart> stringParts = getStringParts(totalStrBuilder);\n final String totalStr = totalStrBuilder.toString();\n \n // Search for the currently active part\n float x = 0;\n for(StringPart part : stringParts)\n {\n // Calculate the width of the current part\n final float width = paint.measureText(totalStr, part.start, part.end);\n \n // If this isn't the currently active part, we add its width and continue\n if(part.symbolIndex != editingIndex || part.editingSymbol != editingSymbol || (editingSymbol == EditingSymbol.VAR && part.varName != currVar))\n {\n x += width;\n continue;\n }\n\n // Call the scroll listener and stop\n onScrollToListener.scroll((int) x, (int) (x + width));\n return;\n }\n }\n \n /** The {@link GestureDetector} */\n private GestureDetector gestureDetector;\n\n @Override\n public boolean onTouchEvent(MotionEvent me)\n {\n // Pass the touch event to the gesture detector\n gestureDetector.onTouchEvent(me);\n \n // Never consume the event\n return true;\n }\n \n /** Listens for click events to switch the symbol we're editing */\n private class GestureListener extends GestureDetector.SimpleOnGestureListener\n {\n @Override\n public boolean onSingleTapUp(MotionEvent me)\n {\n // Get the string parts\n StringBuilder totalStrBuilder = new StringBuilder();\n ArrayList<StringPart> stringParts = getStringParts(totalStrBuilder);\n final String totalStr = totalStrBuilder.toString();\n\n // Determine the point where the user clicks\n Rect totalTextBounds = new Rect();\n paint.getTextBounds(totalStr, 0, totalStr.length(), totalTextBounds);\n Point pos = new Point((int) me.getX(), (int) me.getY());\n pos.offset(-(getWidth() - totalTextBounds.width()) / 2, -(getHeight() - totalTextBounds.height()) / 2);\n \n // Check which part of the string the user clicked (if the user clicked one)\n Rect bounds = new Rect();\n int x = 0;\n for(StringPart part : stringParts)\n {\n // Skip empty parts\n if(part.start == part.end) continue;\n \n // Get the bounds of the current string part\n paint.getTextBounds(totalStr, part.start, part.end, bounds);\n bounds.offset(x - totalTextBounds.left, -totalTextBounds.top);\n x += paint.measureText(totalStr, part.start, part.end);\n \n // Check if the user clicked inside the current string part\n if(bounds.contains(pos.x, pos.y))\n {\n // Change the state\n editingIndex = part.symbolIndex;\n editingSymbol = part.editingSymbol;\n currVar = part.varName;\n \n // Notify any listeners that the state has changed\n if(onStateChangeListener != null)\n onStateChangeListener.stateChanged();\n \n // Request a scroll\n callOnScrollToListener();\n \n // Redraw\n invalidate();\n \n // Stop\n break;\n }\n \n // We can stop if we're past all parts that can possibly contain the click position\n if(pos.x < bounds.left)\n break;\n }\n \n // Always return true\n return true;\n }\n }\n \n /** Represents a part of the string with information about what is displayed in that part */\n private class StringPart\n {\n /** The starting position of the string part */\n public int start;\n /** The end position of the string part (exclusive) */\n public int end;\n \n /** The index of the symbol representation of this part */\n public int symbolIndex;\n /** The symbol type of this part */\n public EditingSymbol editingSymbol;\n /** The variable name of this part (ignored if this part isn't a variable) */\n public char varName = 'a';\n \n /** Constructor\n * @param s The starting position of the string part\n * @param e The end position of the string part (exclusive)\n * @param index The index of the symbol representation of this part\n * @param symbol The symbol type of this part */\n public StringPart(int s, int e, int index, EditingSymbol symbol)\n {\n start = s;\n end = e;\n symbolIndex = index;\n editingSymbol = symbol;\n }\n\n /** Constructor\n * @param s The starting position of the string part\n * @param e The end position of the string part (exclusive)\n * @param index The index of the symbol representation of this part\n * @param var The variable name of this part */\n public StringPart(int s, int e, int index, char var)\n {\n this(s, e, index, EditingSymbol.VAR);\n varName = var;\n }\n }\n \n /** Returns a list with {@link StringPart}s for the current visible symbol\n * @param totalStr Used to build (and output) the total string */\n private ArrayList<StringPart> getStringParts(StringBuilder totalStr)\n {\n // Determine the string we'd draw while keeping track of the positions of each part\n ArrayList<StringPart> stringParts = new ArrayList<StringPart>(symbols.size() * 3);\n int oldLength = 0;\n for(int index = 0; index < symbols.size(); ++index)\n {\n // Get the symbol\n SymbolRepresentation symbol = symbols.get(index);\n \n // Factor\n oldLength = totalStr.length();\n if(totalStr.length() != 0 && !symbol.factor.startsWith(\"-\"))\n totalStr.append('+');\n totalStr.append(symbol.factor);\n stringParts.add(new StringPart(oldLength, totalStr.length(), index, EditingSymbol.FACTOR));\n \n // Pi\n if(symbol.showPi)\n {\n oldLength = totalStr.length();\n totalStr.append('\\u03c0' + toSuperScript(symbol.piPow));\n stringParts.add(new StringPart(oldLength, totalStr.length(), index, EditingSymbol.PI));\n }\n \n // Eulers number\n if(symbol.showE)\n {\n oldLength = totalStr.length();\n totalStr.append('e' + toSuperScript(symbol.ePow));\n stringParts.add(new StringPart(oldLength, totalStr.length(), index, EditingSymbol.E));\n }\n \n // Imaginary unit\n if(symbol.showI)\n {\n oldLength = totalStr.length();\n totalStr.append('\\u03b9' + toSuperScript(symbol.iPow));\n stringParts.add(new StringPart(oldLength, totalStr.length(), index, EditingSymbol.I));\n }\n \n // Variables\n for(int i = 0; i < symbol.varPowers.length; ++i)\n {\n if(symbol.showVars[i])\n {\n oldLength = totalStr.length();\n totalStr.append((char) ('a' + i) + toSuperScript(symbol.varPowers[i]));\n stringParts.add(new StringPart(oldLength, totalStr.length(), index, (char) ('a' + i)));\n }\n }\n }\n \n // Return the result\n return stringParts;\n }\n}", "public class ShowcaseViewDialog extends Dialog\n{\n private ShowcaseView sv;\n private Gesture gesture = null;\n \n public ShowcaseViewDialog(Activity ctx, Target target, String title,\n String msg, Gesture gesture)\n {\n // Construct an invisible dialog\n super(ctx, R.style.ShowcaseViewDialogTheme);\n\n ShowcaseView.ConfigOptions co = new ShowcaseView.ConfigOptions();\n RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);\n lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);\n lps.addRule(RelativeLayout.ALIGN_PARENT_LEFT);\n co.buttonLayoutParams = lps;\n // Create the ShowcaseView and directly remove is from its parent\n ShowcaseView sv = ShowcaseView.insertShowcaseView(target, ctx, title,\n msg, co);\n \n ((ViewGroup) sv.getParent()).removeView(sv);\n sv.setOnShowcaseEventListener(new ShowcaseEventListener());\n this.sv = sv;\n\n this.gesture = gesture;\n this.activity = ctx;\n \n // Set the ShowcaseView as content\n setContentView(sv);\n }\n\n public ShowcaseViewDialog(Activity ctx, Target target, String title,\n String msg)\n {\n this(ctx, target, title, msg, null);\n }\n\n public ShowcaseViewDialog(Activity ctx, Target target, int titleId,\n int msgId, Gesture gesture)\n {\n // Simply call the other constructor\n this(ctx, target, ctx.getResources().getString(titleId), ctx\n .getResources().getString(msgId), gesture);\n }\n\n public ShowcaseViewDialog(Activity ctx, Target target, int titleId,\n int msgId)\n {\n this(ctx, target, titleId, msgId, null);\n }\n \n public void animateGesture()\n {\n if(gesture != null)\n sv.animateGesture(gesture.offsetStartX, gesture.offsetStartY,\n gesture.offsetEndX, gesture.offsetEndY);\n }\n \n public void animateGesture(Gesture gesture)\n {\n this.gesture = gesture;\n animateGesture();\n }\n \n @Override\n public void show()\n {\n super.show();\n animateGesture();\n }\n \n /** The activity the dialog is shown for */\n private Activity activity = null;\n\n /** The DialogFragment the dialog is shown for */\n private DialogFragment dlgFrag = null;\n \n /** Sets the DialogFragment that touch events should be passed to */\n public void setDialogFragment(DialogFragment dlg)\n { dlgFrag = dlg; }\n \n @Override\n public boolean onTouchEvent(MotionEvent event)\n {\n if(dlgFrag != null)\n {\n // Translate the touch position\n Point pos = new Point((int) event.getX(), (int) event.getY());\n int[] viewPos = new int[2];\n dlgFrag.getView().getLocationOnScreen(viewPos);\n event.setLocation(pos.x - viewPos[0], pos.y - viewPos[1]);\n \n // Dispatch the event to the DialogFragment\n return dlgFrag.getView().dispatchTouchEvent(event);\n }\n else if(activity != null)\n {\n // Dispatch the event to the Activity\n activity.dispatchTouchEvent(event);\n }\n return false;\n }\n \n /** Translates the given position to or from the coordinate system used by the given DialogFragment\n * @param pos The point to translate\n * @param dlgFrag The DialogFragment that should be translated to or from\n * @param translateFrom Whether the coordinates should be translated from or to the DialogFragment's coordinate system\n * @return The translated point */\n private static Point translateDialogFragmentPos(Point pos, DialogFragment dlgFrag, boolean translateFrom)\n {\n // Get the layout parameters of the dialog and get the content view and the action bar\n WindowManager.LayoutParams params = dlgFrag.getDialog().getWindow().getAttributes();\n View contentView = dlgFrag.getActivity().findViewById(android.R.id.content);\n ActionBar actionBar = dlgFrag.getActivity().getActionBar();\n\n // Calculate the coordinates of the dialog\n int x = (int) params.horizontalMargin;\n if(params.width != LayoutParams.MATCH_PARENT)\n x += (contentView.getWidth() - params.width) / 2;\n\n int y = (int) params.verticalMargin;\n if(params.height != LayoutParams.MATCH_PARENT)\n y += (contentView.getHeight() + actionBar.getHeight() - params.height) / 2;\n \n // Offset the point by the coordinates of the window\n if(translateFrom)\n pos.offset(x, y);\n else\n pos.offset(-x, -y);\n \n // Return the result\n return pos;\n }\n \n /** A target for the ShowcaseView that can target a certain view in a DialogFragment */\n public static class DialogFragmentTarget extends ViewTarget\n {\n /** The DialogFragment */\n private DialogFragment dlgFrag;\n\n public DialogFragmentTarget(View view, DialogFragment dlgFrag)\n {\n // Call the super constructor\n super(view);\n\n // Remember the DialogFragment\n this.dlgFrag = dlgFrag;\n }\n\n @Override\n public Point getPoint()\n {\n // Get the position of the view inside the window\n Point viewPos = super.getPoint();\n\n // Get the layout parameters of the dialog and get the content view\n // and the action bar\n WindowManager.LayoutParams params = dlgFrag.getDialog().getWindow()\n .getAttributes();\n View contentView = dlgFrag.getActivity().findViewById(\n android.R.id.content);\n ActionBar actionBar = dlgFrag.getActivity().getActionBar();\n\n // Calculate the coordinates of the dialog\n int x = (int) params.horizontalMargin;\n if(params.width != LayoutParams.MATCH_PARENT)\n x += (contentView.getWidth() - params.width) / 2;\n\n int y = (int) params.verticalMargin;\n if(params.height != LayoutParams.MATCH_PARENT)\n y += (contentView.getHeight() + actionBar.getHeight() - params.height) / 2;\n\n // Offset the point by the coordinates of the window\n viewPos.offset(x, y);\n\n\n // Translate the position of the view to a position in the ShowcaseView\n return translateDialogFragmentPos(super.getPoint(), dlgFrag, true);\n }\n }\n\n /** The current OnShowcaseEventListener */\n private OnShowcaseEventListener onShowcaseEventListener = null;\n\n /**\n * Sets the current OnShowcaseEventListener\n * \n * @param listener\n * The new listener\n */\n public void setOnShowcaseEventListener(OnShowcaseEventListener listener)\n {\n onShowcaseEventListener = listener;\n }\n\n /** Listens for events from the ShowcaseView */\n private class ShowcaseEventListener implements OnShowcaseEventListener\n {\n\n @Override\n public void onShowcaseViewHide(ShowcaseView showcaseView)\n {\n // Call the OnShowcaseEventListener\n if(onShowcaseEventListener != null)\n onShowcaseEventListener.onShowcaseViewHide(showcaseView);\n }\n\n @Override\n public void onShowcaseViewDidHide(ShowcaseView showcaseView)\n {\n // Simply dismiss the dialog\n dismiss();\n\n // Call the OnShowcaseEventListener\n if(onShowcaseEventListener != null)\n onShowcaseEventListener.onShowcaseViewDidHide(showcaseView);\n }\n\n @Override\n public void onShowcaseViewShow(ShowcaseView showcaseView)\n {\n // Call the OnShowcaseEventListener\n if(onShowcaseEventListener != null)\n onShowcaseEventListener.onShowcaseViewShow(showcaseView);\n }\n\n }\n\n /**\n * Represents the handy gesture. POJO\n */\n public static class Gesture\n {\n public final float offsetStartX, offsetStartY, offsetEndX, offsetEndY;\n\n /**\n * \n * @param offsetStartX the x coordinate of the start of the gesture (relative to the middle of the {@link Target} of this {@link ShowcaseViewDialog})\n * @param offsetStartY the y coordinate of the start of the gesture (relative to the middle of the {@link Target} of this {@link ShowcaseViewDialog})\n * @param offsetEndX the x coordinate of the end of the gesture (relative to the middle of the {@link Target} of this {@link ShowcaseViewDialog})\n * @param offsetEndY the y coordinate of the end of the gesture (relative to the middle of the {@link Target} of this {@link ShowcaseViewDialog})\n */\n public Gesture(float offsetStartX, float offsetStartY,\n float offsetEndX, float offsetEndY)\n {\n this.offsetStartX = offsetStartX;\n this.offsetStartY = offsetStartY;\n this.offsetEndX = offsetEndX;\n this.offsetEndY = offsetEndY;\n }\n }\n}", "public class ShowcaseViewDialogs\n{\n \n /** a list of dialogs */\n private LinkedList<ShowcaseViewDialog> dialogs = new LinkedList<ShowcaseViewDialog>();\n \n /** an event handler */\n private OnShowcaseAcknowledged onShowcaseAcknowledged;\n \n \n private final Tutorial tutorial;\n \n public ShowcaseViewDialogs(Tutorial tutorial)\n { this.tutorial = tutorial; }\n \n /**\n * Adds a new {@link ShowcaseViewDialog} to the queue. \n * @param dg the dialog to add.\n */\n public void addView(final ShowcaseViewDialog dg)\n {\n dialogs.add(dg);\n \n int index = dialogs.indexOf(dg);\n \n \n if(dialogs.size() > 1)\n {\n dialogs.get(index-1).setOnShowcaseEventListener(new OnShowcaseEventListener()\n {\n \n @Override\n public void onShowcaseViewShow(ShowcaseView showcaseView)\n { }\n \n @Override\n public void onShowcaseViewHide(ShowcaseView showcaseView)\n { dg.show(); tutorial.setCurrentShowcaseDialog(dg);}\n \n @Override\n public void onShowcaseViewDidHide(ShowcaseView showcaseView)\n { }\n });\n }\n }\n \n /** \n * Utility method to quickly add multiple {@link ShowcaseViewDialog}s\n * @param dgs The dialogs to add.\n */\n public void addViews(final ShowcaseViewDialog[] dgs)\n { for(ShowcaseViewDialog dg : dgs) addView(dg); }\n \n /** \n * Utility method to quickly add multiple {@link ShowcaseViewDialog}s\n * @param dgs The dialogs to add.\n */ \n public void addViews(final Collection<ShowcaseViewDialog> dgs)\n { for(ShowcaseViewDialog dg : dgs) addView(dg); }\n \n \n /**\n * Shows the {@link ShowcaseViewDialog}s in order that they were added.\n */\n public void show()\n {\n Database db = new Database(tutorial.getActivity());\n if (db.getTutorialState(tutorial.getTutorialId()).tutInProg == false)\n {\n db.close(); return;\n }\n db.close();\n if(!(dialogs.size() > 0)) \n {\n if(onShowcaseAcknowledged != null) onShowcaseAcknowledged.acknowledge(); \n return;\n }\n dialogs.getLast().setOnShowcaseEventListener(new OnShowcaseEventListener()\n {\n \n @Override\n public void onShowcaseViewShow(ShowcaseView showcaseView)\n { }\n \n @Override\n public void onShowcaseViewHide(ShowcaseView showcaseView)\n {\n if (onShowcaseAcknowledged != null) onShowcaseAcknowledged.acknowledge(); \n \n Database db = new Database(tutorial.getActivity());\n Database.TutorialState state = db.getTutorialState(tutorial.getTutorialId());\n state.tutInProg = false;\n db.saveTutorialState(state);\n db.close();\n }\n \n @Override\n public void onShowcaseViewDidHide(ShowcaseView showcaseView)\n { }\n });\n tutorial.setCurrentShowcaseDialog(dialogs.get(0));\n dialogs.get(0).show();\n }\n \n /**\n * Set the listener\n * @param onShowcaseAcknowledged\n */\n public void setOnShowcaseAcknowledged(OnShowcaseAcknowledged onShowcaseAcknowledged)\n {\n this.onShowcaseAcknowledged = onShowcaseAcknowledged;\n }\n \n \n /**\n */\n public interface OnShowcaseAcknowledged\n {\n void acknowledge();\n }\n}", "public enum EditingSymbol\n{\n FACTOR((byte) 0), PI((byte) 1), E((byte) 2), I((byte) 3), VAR((byte) 4);\n \n private byte b;\n \n private EditingSymbol(byte b)\n { this.b = b; }\n \n public byte toByte()\n { return b; }\n \n public static EditingSymbol fromByte(byte b)\n {\n switch(b)\n {\n case 0: return FACTOR;\n case 1: return PI;\n case 2: return E;\n case 3: return I;\n case 4: return VAR;\n }\n return FACTOR;\n }\n}", "public abstract class Expression\n{\n /** The line width that is to be used to draw operators */\n public static float lineWidth = 2.0f;\n \n /** The children of this {@link Expression} */\n protected ArrayList<Expression> children = new ArrayList<Expression>();\n\n /** The center of this object */\n protected Point center;\n \n /** The bounding boxes of this object */\n protected ArrayList<Rect> childrenBoundingBoxes = new ArrayList<Rect>();\n protected ArrayList<Rect> operatorBoundingBoxes = new ArrayList<Rect>();\n protected Rect totalBoundingBox = null;\n \n /** The boolean to keep track if the bounding boxes are still valid */\n protected boolean operatorBoundingBoxValid = false;\n /** The boolean to keep track if the child bounding boxes are still valid */\n protected boolean childrenBoundingBoxValid = false;\n /** The boolean to keep track if the total bounding box is still valid */\n protected boolean totalBoundingBoxValid = false;\n /** The boolean to keep track if the center is still valid */\n protected boolean centerValid = false;\n \n /** The default height of an object */\n protected int defaultHeight = 100;\n \n /** The maximum level depth */\n public final static int MAX_LEVEL = 4;\n\n /** The current hover state */\n protected HoverState state = HoverState.NONE;\n \n /** The current 'level' of the object*/\n protected int level = 0;\n \n /** Returns the precedence of this operation.\n * The highest precedence is 0, greater values are lower precedences.\n * @return The precedence\n */\n public int getPrecedence()\n { return Precedence.HIGHEST; }\n\n /**\n * Returns the number of children this {@link Expression} has\n * \n * @return The number of children this {@link Expression} has\n */\n public int getChildCount()\n { return children.size(); }\n\n /**\n * Returns the child at the given index\n * \n * @param index\n * The index of the child to return\n * @return The requested child\n * @throws IndexOutOfBoundsException\n * thrown when the index number is invalid (i.e. out of range).\n */\n public Expression getChild(int index) throws IndexOutOfBoundsException\n { return children.get(index); }\n\n /**\n * Sets the child at the given index\n * \n * @param index\n * The index of the child that is to be changed\n * @param child\n * The {@link Expression} that should become the child at the given index\n * @throws IndexOutOfBoundsException\n * thrown when the index number is invalid (i.e. out of range).\n */\n public void setChild(int index, Expression child) throws IndexOutOfBoundsException\n {\n // Check the child index\n checkChildIndex(index);\n \n // Create an MathObjectEmpty if null is given\n if(child == null)\n child = new Empty();\n \n // Set the child\n children.set(index, child);\n\n // Refresh all levels and default heights\n // Also reset the bounding box cache\n setAll(level, defaultHeight, false);\n }\n\n /** Sets the child at the given index without refreshing the level, default height or bounding box cache.\n * You'll have to do this yourself.\n * \n * @param index\n * The index of the child that is to be changed\n * @param child\n * The {@link Expression} that should become the child at the given index\n * @throws IndexOutOfBoundsException\n * thrown when the index number is invalid (i.e. out of range).\n */\n public void setChildWithoutRefresh(int index, Expression child) throws IndexOutOfBoundsException\n {\n // Check the child index\n checkChildIndex(index);\n \n // Create an MathObjectEmpty if null is given\n if(child == null)\n child = new Empty();\n \n // Set the child\n children.set(index, child);\n }\n \n /** Returns the default height for this {@link Expression}\n * @return The default height for this {@link Expression} */\n public int getDefaultHeight()\n { return defaultHeight; }\n \n /** Sets the default height for this {@link Expression} and all of its children\n * @param height The default height */\n public void setDefaultHeight(int height)\n {\n // Invalidate the cache (if necessary)\n if(height != defaultHeight)\n invalidateBoundingBoxCacheForSelf();\n \n // Set the default height\n defaultHeight = height;\n \n // Pass the new default height to all children\n for(Expression child : children)\n child.setDefaultHeight(defaultHeight);\n }\n \n /** Invalidate or validate all bounding boxes in the cache (for this expression and all of its children) */\n public void invalidateBoundingBoxCache()\n {\n // Invalidate the whole cache\n invalidateBoundingBoxCacheForSelf();\n \n // Invalidate the whole cache for every child as well\n for(Expression child : children)\n child.invalidateBoundingBoxCache();\n }\n\n /** Invalidate or validate all bounding boxes in the cache (only for this expression) */\n public void invalidateBoundingBoxCacheForSelf()\n {\n // Invalidate the whole cache\n operatorBoundingBoxValid = false;\n childrenBoundingBoxValid = false;\n totalBoundingBoxValid = false;\n centerValid = false;\n }\n \n /** Get the state of the bounding box cache */\n public boolean getOperatorBoundingBoxValid()\n { return operatorBoundingBoxValid; }\n \n /** Get the state of the children bounding box cache */\n public boolean getChildrenBoundingBoxValid()\n { return childrenBoundingBoxValid; }\n \n /** Get the state of the total bounding box cache */\n public boolean getTotalBoundingBoxValid()\n { return totalBoundingBoxValid; }\n \n \n /**\n * Returns the bounding boxes of the operator of this {@link Expression}.\n * The aspect ratio of the bounding boxes should always be the same.\n * \n * @param maxWidth\n * The maximum width the {@link Expression} can have (can be\n * {@link Expression#NO_MAXIMUM})\n * @param maxHeight\n * The maximum height the {@link Expression} can have (can be\n * {@link Expression#NO_MAXIMUM})\n * @return An array containing the requested bounding boxes\n */\n public abstract Rect[] calculateOperatorBoundingBoxes();\n\n public Rect[] getOperatorBoundingBoxes()\n { \t\n // If the cache is invalid or there are no bounding boxes in the current cache, recalculate them\n if( !getOperatorBoundingBoxValid() || operatorBoundingBoxes.isEmpty())\n {\n // First clear the current list\n operatorBoundingBoxes.clear();\n \n // Recalculate the bounding boxes\n Rect[] operatorBB = calculateOperatorBoundingBoxes();\n \n for(int i = 0; i < operatorBB.length; i ++)\n operatorBoundingBoxes.add( operatorBB[i]);\n \n // Set the cache to valid\n operatorBoundingBoxValid = true;\n }\n \n // Create a new array and get a copy of all the bounding boxes\n Rect[] result = new Rect[ operatorBoundingBoxes.size()];\n \n for(int i = 0; i < result.length; i ++)\n result[i] = new Rect(operatorBoundingBoxes.get(i));\n \n // Return the array with the rectangles\n return result;\n }\n /**\n * Returns the bounding box of the child at the given index.\n * The aspect ratio of the box should always be the same.\n * \n * @param index\n * The index of the child whose bounding box is to be returned\n * @return An array containing the requested bounding boxes\n * @throws IndexOutOfBoundsException\n * If an invalid child index is given\n */\n public abstract Rect calculateChildBoundingBox(int index) throws IndexOutOfBoundsException;\n\n public Rect getChildBoundingBox(int index) throws IndexOutOfBoundsException\n { \t\n // If the cache is invalid or the amount of bounding boxes isn't the amount of children, recalculate them\n if( !getChildrenBoundingBoxValid() || (getChildCount() != childrenBoundingBoxes.size()))\n {\n childrenBoundingBoxes.clear();\n \n this.calculateAllChildBoundingBox();\n \n childrenBoundingBoxValid = true;\n }\n \n // Return a copy of the requested bounding box\n return new Rect(childrenBoundingBoxes.get(index));\n }\n \n /** Calculate all the children's bounding boxes and add them to the children arraylist */\n public void calculateAllChildBoundingBox()\n {\n \tint size = getChildCount();\n \n for(int i = 0; i < size; i ++)\n childrenBoundingBoxes.add( calculateChildBoundingBox(i));\n }\n \n /**\n * Returns the bounding box for the entire {@link Expression}.\n * The aspect ratio of the box should always be the same.\n * \n * @return The bounding box for the entire {@link Expression}\n */\n public Rect calculateBoundingBox()\n { \t\n // This will be our result\n Rect out = new Rect();\n\n // Add all operator bounding boxes\n Rect[] operatorBoundingBoxes = getOperatorBoundingBoxes();\n for(Rect tmp : operatorBoundingBoxes)\n out.union(tmp);\n\n // Add all child bounding boxes\n for(int i = 0; i < getChildCount(); ++i)\n out.union(getChildBoundingBox(i));\n int width = out.width();\n int height = out.height();\n\n // Return the result\n return new Rect(0,0,width, height);\n }\n \n public Rect getBoundingBox()\n {\n // If the cache is invalid or there is no bounding box in the cache, recalculate\n if( !getTotalBoundingBoxValid() || totalBoundingBox == null)\n {\n totalBoundingBox = calculateBoundingBox();\n totalBoundingBoxValid = true;\n }\n \n // Return a copy of the bounding box\n return new Rect(totalBoundingBox);\n }\n \n /**\n * Retrieve the current hover state.\n * @return {@link #state}\n */\n public final HoverState getState()\n { return state; }\n\n /**\n * Modifies current state and return the old state. Subclasses may override\n * this method in order to perform actions (e.g. fire a <q>\n * HoverStateChangedListener</q> or something like that).\n * \n * @param state\n * The new state\n * @return The old state.\n * @throws NullPointerException\n * thrown if {@link #state}<tt> == null</tt>\n */\n public HoverState setState(HoverState state)\n {\n if(state == null)\n throw new NullPointerException(\"state\");\n HoverState old = this.state;\n this.state = state;\n return old;\n }\n\n /**\n * Draws the {@link Expression}\n * \n * @param canvas\n * The canvas to draw the {@link Expression} on\n */\n public abstract void draw(Canvas canvas);\n \n /**\n * Draw the child with the given index child on <tt>canvas</tt> within the specified bounding box.\n * @param index The index of the child that is to be drawn\n * @param canvas The graphical instance to draw on\n * @param box The bounding box of the child\n */\n protected void drawChild(int index, Canvas canvas, final Rect box)\n {\n // Draw the child\n canvas.save();\n canvas.translate(box.left, box.top);\n getChild(index).draw(canvas);\n canvas.restore();\n }\n \n /** Draws all children\n * @param canvas The canvas that the children should be drawn on\n\n */\n protected void drawChildren(Canvas canvas)\n {\n // Loop through all children and draw them\n for(int i = 0; i < children.size(); ++i)\n drawChild(i, canvas, getChildBoundingBox(i));\n }\n\n /**\n * Checks if the given child index is valid, and throws an exception if it\n * isn't.\n * \n * @param index\n * The child index that is to be checked\n * @throws IndexOutOfBoundsException\n * If the child index is invalid\n */\n protected final void checkChildIndex(int index) throws IndexOutOfBoundsException\n {\n final int childCount = getChildCount();\n\n if(childCount == 0)\n throw new IndexOutOfBoundsException(getClass().getCanonicalName()\n + \" doesn't have any children.\");\n else if(childCount == 1 && index != 0)\n throw new IndexOutOfBoundsException(\"Invalid child index \"\n + Integer.toString(index) + \", \"\n + getClass().getCanonicalName() + \" has only 1 child.\");\n else if(index < 0 || index >= childCount)\n throw new IndexOutOfBoundsException(\"Invalid child index \"\n + Integer.toString(index) + \", \"\n + getClass().getCanonicalName() + \" has only \"\n + Integer.toString(childCount) + \" children.\");\n }\n \n /** Returns the color for the current state\n * @return The color for the current state\n */\n protected int getColor()\n {\n if(this.state == HoverState.DRAG)\n return Color.rgb(0x88, 0x88, 0x88);\n if(this.state == HoverState.HOVER)\n return Color.rgb(0x44, 0x44, 0xff);\n return Color.BLACK;\n }\n \n /** Set the state of the center point*/\n public void validateCenter(boolean bool)\n {\n \tcenterValid = bool;\n \t\n \tif(!bool)\n \t\tfor(Expression child : children)\n \t\t\tchild.validateCenter(false);\n }\n \n /** Get the state of the center point */\n public boolean getCenterValid()\n { return centerValid; }\n \n /** Returns the centre of the {@link Expression}\n * @return The centre of the {@link Expression}\n */\n public Point getCenter()\n {\n \tif(!getCenterValid() || center == null)\n \t{\n \t\tcenter = calculateCenter();\n \t\tthis.validateCenter(true);\n \t}\n \t\n return center;\n }\n \n /** Calculate the center point */\n public Point calculateCenter()\n {\n \tRect bounding = this.getBoundingBox();\n\t\treturn new Point(bounding.centerX(), bounding.centerY());\n }\n \n /** The deltas that should be added to the level for each corresponding child */\n protected int[] levelDeltas = null;\n \n /** Sets the new level for this {@link Expression} and all of its children\n * @param l The new level */\n public void setLevel(int l)\n {\n // Invalidate the cache (if necessary)\n if(l != level)\n invalidateBoundingBoxCacheForSelf();\n \n // Set the level\n level = l;\n \n // Set the level every child\n for(int i = 0; i < getChildCount(); ++i)\n {\n if(levelDeltas != null && i < levelDeltas.length)\n getChild(i).setLevel(l + levelDeltas[i]);\n else\n getChild(i).setLevel(l);\n }\n }\n \n /** Sets the level, bounding boxes validation and default height for this expression and all of it's children at once\n * @param lvl The new level\n * @param defHeight The new default height\n * @param valid Whether or not the bounding boxes should be valid */\n public void setAll(int lvl, int defHeight, boolean valid)\n {\n // Set the values\n level = lvl;\n defaultHeight = defHeight;\n operatorBoundingBoxValid = valid;\n childrenBoundingBoxValid = valid;\n totalBoundingBoxValid = valid;\n centerValid = valid;\n \n // Set the values for all children\n for(int i = 0; i < getChildCount(); ++i)\n {\n if(levelDeltas != null && i < levelDeltas.length)\n getChild(i).setAll(lvl + levelDeltas[i], defHeight, valid);\n else\n getChild(i).setAll(lvl, defHeight, valid);\n }\n }\n \n /** Whether or not to draw the bounding boxes */\n private final static boolean DRAW_BOUNDING = false;\n \n /** Draws the bounding box and the bounding boxes of the children (for debug purposes).\n * The boxes will only be drawn if {@link Expression#DRAW_BOUNDING DRAW_BOUNDING} is set to true.\n * @param canvas The canvas to draw on\n */\n protected void drawBoundingBoxes(Canvas canvas)\n {\n // Check if we should draw the bounding boxes\n if(!DRAW_BOUNDING) return;\n\n // Draw the bounding boxes\n Paint paint = new Paint();\n paint.setColor(0x4400ff00);\n canvas.drawRect(getBoundingBox(), paint);\n paint.setColor(0x44ff0000);\n for(int i = 0; i < getChildCount(); ++i)\n canvas.drawRect(getChildBoundingBox(i), paint);\n }\n \n /** The name of the XML root element */\n public static final String XML_ROOT = \"root\";\n\n /** The current version of the XML structure */\n public static final int XML_VERSION = 1;\n \n /** Creates an empty XML document that can be used for the {@link Expression#writeToXML(Document, Element) writeToXML()} method\n * @return The created document \n * @throws ParserConfigurationException If something goes wrong while creating the document */\n public static Document createXMLDocument() throws ParserConfigurationException\n {\n // Create an empty document\n DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder builder = builderFactory.newDocumentBuilder();\n Document doc = builder.newDocument();\n \n // Create a root element\n Element root = doc.createElement(XML_ROOT);\n root.setAttribute(\"version\", Integer.toString(XML_VERSION));\n doc.appendChild(root);\n \n // Return the document\n return doc;\n }\n \n /** Serialize current instance in a XML document in a specified element. \n * @param doc The XML document\n * @param parent The parent XML element\n */\n public void writeToXML(Document doc, Element parent)\n {\n Log.w(\"XML\", \"not a writable element yet\");\n parent.appendChild(doc.createElement(Empty.NAME));\n }\n \n /**\n * Checks if all children have been fully filled in, and also their children and so on recursively down the tree.\n * @return returns true if all children of this MathObject have been filled in.\n */\n public boolean isCompleted()\n {\n for(Expression child : children)\n {\n if(!child.isCompleted())\n return false;\n }\n \n return true;\n }\n}", "public class Symbol extends Expression\n{\n /**\n * Cached mathematical symbolic constant for the mathematical <tt>-1</tt> in\n * order to speed up helpers and parsers so they don't need to make this\n * symbolic constant themselves.\n */\n public static final Symbol M_ONE = new Symbol(-1);\n /**\n * Cached mathematical symbolic constant for the mathematical <tt>0</tt> in\n * order to speed up helpers and parsers so they don't need to make this\n * symbolic constant themselves.\n */\n public static final Symbol ZERO = new Symbol();\n /**\n * Cached mathematical symbolic constant for the mathematical <tt>1</tt> in\n * order to speed up helpers and parsers so they don't need to make this\n * symbolic constant themselves.\n */\n public static final Symbol ONE = new Symbol(1);\n /**\n * Cached mathematical symbolic constant for the mathematical <tt>10</tt> in\n * order to speed up helpers and parsers so they don't need to make this\n * symbolic constant themselves.\n */\n public static final Symbol TEN = new Symbol(10);\n \n /** The factor of this constant */\n private double factor = 0;\n /** The power of the E constant */\n private long ePow = 0;\n /** The power of the PI constant */\n private long piPow = 0;\n /** The power of the imaginary unit */\n private long iPow = 0;\n /** The powers of the variables */\n private long varPows[] = new long[VAR_POWS_LENGTH];\n \n /**\n * Maximum supported number of variable powers. Specifying arrays with more\n * elements than {@code VAR_POWS_LENGTH} will be accepted, but only the\n * first {@code VAR_POWS_LENGTH} elements will be copied.\n */\n public static final int VAR_POWS_LENGTH = 26;\n \n /** The paint that is used to draw the factor and the constants */\n protected Paint paint = new Paint();\n \n /** Superscript character lookup table */\n private final static char[] SUPERSCRIPT = new char[] {'\\u2070', '\\u00b9', '\\u00b2', '\\u00b3','\\u2074','\\u2075','\\u2076','\\u2077', '\\u2078', '\\u2079'};\n\n /** Default constructor */\n public Symbol()\n { \n this(0);\n }\n \n /**\n * Simple constructor with a factor just for simplicity.\n * @param factor The base number\n */\n public Symbol(double factor)\n {\n this(factor, 0, 0, 0);\n }\n \n /** Construct mathematical constant using specified values for simplicity.\n * @param factor The base number\n * @param ePow The Euler power\n * @param piPow The pi power\n * @param iPow The imaginary power\n */\n public Symbol(double factor, long ePow, long piPow, long iPow)\n {\n this(factor, ePow, piPow, iPow, new long[0]);\n }\n \n /** Construct mathematical constant using specified values.\n * @param factor The base number\n * @param ePow The Euler power\n * @param piPow The pi power\n * @param iPow The imaginary power\n * @param varPows The first <tt>varPows.length</tt> powers for the variables (may be <tt>null</tt>)\n */\n public Symbol(double factor, long ePow, long piPow, long iPow, long[] varPows)\n {\n initPaints();\n setFactor(factor);\n this.ePow = ePow;\n this.piPow = piPow;\n this.iPow = iPow;\n if(varPows != null)\n {\n // arraycopy is safer and more efficient.\n System.arraycopy(varPows, 0, this.varPows, 0, Math.min(VAR_POWS_LENGTH, Math.min(varPows.length, this.varPows.length)));\n }\n }\n \n /** Returns a symbol that simply consists out of the given variable\n * @param var The variable that should be put in the symbol\n * @return The symbol with the given variable */\n public static Symbol createVarSymbol(char var)\n {\n Symbol out = new Symbol(1);\n out.setVarPow(var, 1);\n return out;\n }\n \n /** Initialises the paints */\n private void initPaints()\n {\n paint.setAntiAlias(true);\n paint.setTypeface(TypefaceHolder.dejavuSans);\n }\n\n /**\n * Helper method for appending literals.\n * @param sb The {@link StringBuilder} to append the string to\n * @param c The character of the symbol\n * @param pow The power of the symbol\n */\n private static void appendLit(StringBuilder sb, char c, long pow)\n {\n if(pow != 0)\n {\n sb.append(c);\n if(pow != 1)\n {\n if(pow < 0)\n {\n sb.append('\\u207b');\n pow *= -1;\n }\n long num = pow;\n StringBuilder sb2 = new StringBuilder();\n while (num > 0)\n {\n sb2.append(SUPERSCRIPT[(int) (num % 10)]);\n num /= 10;\n }\n sb.append(sb2.reverse());\n }\n }\n }\n \n /** Calculates the size of this {@link Symbol} when using the given font size\n * @param fontSize The font size\n * @return The size of this {@link Symbol}\n */\n protected Rect getSize(float fontSize)\n {\n // Set the text size\n paint.setTextSize(fontSize);\n \n // Calculate the total width and the height of the text\n Rect out = new Rect(0, 0, 0, 0);\n Rect bounds = new Rect();\n String str = toString();\n str = str.substring(1, str.length() - 1);\n paint.getTextBounds(str, 0, str.length(), bounds); \n out.right = bounds.width();\n out.bottom = bounds.height();\n return out;\n }\n\n /** Adds padding to the given size rectangle\n * @param size The size where the padding should be added to\n * @return The size with the padding\n */\n protected Rect sizeAddPadding(Rect size)\n {\n // Copy the rectangle\n Rect out = new Rect(size);\n \n // Add the padding\n out.inset(-(int)(Expression.lineWidth * 2.5), -(int)(Expression.lineWidth * 2.5));\n out.offsetTo(0, 0);\n \n // Return the result\n return out;\n }\n \n /** Calculates the right text size for the given level\n * @param lvl The level\n * @return The right text size for the given level */\n protected float findTextSize(int lvl)\n {\n return defaultHeight * (float) Math.pow(2.0 / 3.0, Math.min(lvl, MAX_LEVEL));\n }\n\n @Override\n public Rect[] calculateOperatorBoundingBoxes()\n {\n // Find the right text size and return the bounding box for it\n return new Rect[]{ sizeAddPadding(getSize(findTextSize(level))) };\n }\n\n @Override\n public Rect calculateChildBoundingBox(int index) throws IndexOutOfBoundsException\n {\n // Will always throw an error since constants do not have children\n checkChildIndex(index);\n return null;\n }\n \n public void draw(Canvas canvas)\n {\n // Draw the bounding boxes\n drawBoundingBoxes(canvas);\n \n // Get the text size and the bounding box\n final float textSize = findTextSize(level);\n Rect textBounding = getSize(textSize);\n Rect totalBounding = sizeAddPadding(textBounding);\n\n // Set the text size and colour\n paint.setTextSize(textSize);\n paint.setColor(getColor());\n \n // Translate the canvas\n canvas.save();\n canvas.translate((totalBounding.width() - textBounding.width()) / 2, (totalBounding.height() - textBounding.height()) / 2);\n\n String str = toString();\n str = str.substring(1, str.length() - 1);\n Rect bounds = new Rect();\n paint.getTextBounds(str, 0, str.length(), bounds);\n canvas.drawText(str, -bounds.left, textBounding.height() - bounds.height() - bounds.top, paint);\n \n // Restore the canvas translation\n canvas.restore();\n }\n \n /**\n * Check whether the current instance and <tt>o</tt> are identical. It is\n * heavily called by unit test cases, so do not remove this method!\n * @param o the instance to compare with\n * @return <tt>true</tt> when equal, <tt>false</tt> otherwise.\n */\n public boolean equals(Object o)\n {\n if(!(o instanceof Symbol))\n return false;\n Symbol c = (Symbol) o;\n\n return c.factor == factor && c.ePow == ePow && c.piPow == piPow && c.iPow == iPow && Arrays.equals(c.varPows, varPows);\n }\n \n /**\n * Gives the constant as a string\n * @return The constant as a string\n */\n @Override\n public String toString()\n {\n StringBuilder sb = new StringBuilder();\n\n if(symbolVisible())\n sb.append(factor == -1 ? '-' : (factor == 1 ? \"\" : doubleToString(factor)) );\n else\n sb.append(doubleToString(factor));\n \n if(factor != 0)\n {\n appendLit(sb, '\\u03c0', piPow);\n appendLit(sb, 'e', ePow);\n appendLit(sb, '\\u03b9', iPow);\n for(int i = 0; i < varPows.length; i++)\n appendLit(sb, (char) (i + 'a'), varPows[i]);\n }\n return \"(\" + sb.toString() + \")\";\n }\n \n /** Converts a <tt>double</tt> to a string, dropping <tt>\".0\"</tt> if necessary.\n * Also returns, for example, <tt>\"0.002\"</tt> instead of <tt>\"2.0E-3\"</tt>.\n * @param x The <tt>double</tt> to convert\n * @return The <tt>double</tt> as a string */\n private String doubleToString(double x)\n {\n // Convert the double to a string\n String str = Double.toString(x);\n \n // Search for an 'E'\n final int ePos = str.indexOf('E');\n if(ePos != -1)\n {\n // Determine the amount of zeros and whether they need to be appended or prepended\n int zeros = Integer.parseInt(str.substring(ePos + 1));\n final boolean append = zeros >= 0;\n if(!append)\n zeros = (-zeros) - 1;\n \n // Remember the part before the 'E'\n String before = str.substring(0, ePos);\n final int dotPos = before.indexOf('.');\n if(dotPos != -1)\n {\n String tmp = before.substring(dotPos + 1);\n while(tmp.endsWith(\"0\"))\n tmp = tmp.substring(0, tmp.length() - 1);\n before = before.substring(0, dotPos) + tmp;\n \n if(append)\n zeros -= tmp.length();\n if(zeros < 0)\n before = before.substring(0, before.length() + zeros) + '.' + before.substring(before.length() + zeros);\n }\n boolean negative = before.startsWith(\"-\");\n if(negative)\n before = before.substring(1);\n \n // Prepend/append the zeros\n while(zeros > 0)\n {\n if(append)\n before += '0';\n else\n before = '0' + before;\n --zeros;\n }\n if(zeros == 0 && !append)\n before = \"0.\" + before;\n \n // Put back the minus sign\n if(negative)\n before = '-' + before;\n \n // Remember the result\n str = before;\n }\n \n // Chop off unnecessary '.' and '0'\n while(str.contains(\".\") && (str.endsWith(\".\") || str.endsWith(\"0\")))\n str = str.substring(0, str.length() - 1);\n \n // Return the string\n return str;\n }\n\n /**\n * Checks whether only {@code factor != 0}.\n * \n * @return <tt>true</tt> if all other variables equal <tt>0</tt>.\n * <tt>false</tt> otherwise.\n */\n public boolean isFactorOnly()\n {\n for(int i = 0; i < varPows.length; ++i)\n {\n if(varPows[i] != 0)\n {\n return false;\n }\n }\n return ePow == 0 && piPow == 0 && iPow == 0;\n }\n\n /** Retrieve the factor\n * @return The base number */\n public double getFactor()\n { return factor; }\n\n /** Assign the new factor to <tt>factor</tt>\n * @param factor the new <tt>factor</tt> */\n public void setFactor(double factor)\n {\n // Round the factor to 6 decimals\n double decimals = factor > 0 ? factor - Math.floor(factor) : factor - Math.ceil(factor);\n decimals = Math.round(decimals * 1000000) / 1000000.0;\n \n // Set the factor\n this.factor = (factor > 0 ? Math.floor(factor) : Math.ceil(factor)) + decimals;\n }\n \n /**\n * Invert the current factor and return the new value.\n * @return <tt>-</tt>{@link factor}\n */\n public double invertFactor()\n {\n return this.factor = -factor;\n }\n\n /** Get the current power for <tt>pi</tt>\n * @return The current power for <tt>pi</tt> */\n public long getPiPow()\n { return piPow; }\n\n /** Set the new power for <tt>pi</tt>\n * @param piPow the new power for <tt>pi</tt> */\n public void setPiPow(long piPow)\n { this.piPow = piPow; }\n\n /** Get the current power for <tt>e</tt>\n * @return The current power for <tt>e</tt> */\n public long getEPow()\n { return ePow; }\n\n /** Set the new power for <tt>e</tt>\n * @param ePow the new power for <tt>e</tt> */\n public void setEPow(long ePow)\n { this.ePow = ePow; }\n\n /** Get the current power for <tt>i</tt>\n * @return The current power for <tt>i</tt> */\n public long getIPow()\n { return iPow; }\n\n /** Set the new power for <tt>i</tt>\n * @param iPow the new power for <tt>i</tt> */\n public void setIPow(long iPow)\n { this.iPow = iPow; }\n\n /** Get the current power for the given variable\n * @param index The variable index\n * @return The current power for the given variable */\n public long getVarPow(int index)\n { return varPows[index]; }\n\n /** Set the new power for the given variable\n * @param index The variable index\n * @param pow the new power for the variable */\n public void setVarPow(int index, long pow)\n { varPows[index] = pow; }\n \n public void setVarPow(char index, long pow)\n { setVarPow(index > 'Z' ? index - 'a' : index - 'A', pow); }\n \n public int getVarCount()\n {\n int count = 0;\n for (int i = 0; i < varPows.length; ++i)\n {\n if (varPows[i] != 0)\n ++count;\n }\n return count;\n }\n \n /** The amount of variables that this symbol supports */\n public int varPowCount()\n { return varPows.length; }\n \n /**\n * Raises the current symbol to the given power. That is, all powers are multiplied with the given power.\n * @param power The power to multiply the current powers with.\n * @return True if successful, or false otherwise (e.g. when one of the powers wouldn't be an integer).\n */\n public boolean tryRaisePower(double power)\n {\n try\n {\n // Try multiplying the powers\n long newPiPow = tryMultiplyWithIntegerResult(piPow, power);\n long newEPow = tryMultiplyWithIntegerResult(ePow, power);\n long newIPow = tryMultiplyWithIntegerResult(iPow, power);\n long[] newVarPows = new long[varPows.length];\n for(int i = 0; i < varPows.length; ++i)\n {\n newVarPows[i] = tryMultiplyWithIntegerResult(varPows[i], power);\n }\n\n // If we've come here, all powers could be multiplied successfully and we can use the new powers\n piPow = newPiPow;\n ePow = newEPow;\n iPow = newIPow;\n varPows = newVarPows;\n\n // We have successfully raised the symbol to a power\n return true;\n }\n catch(Exception exc)\n {\n return false;\n }\n }\n\n /**\n * Reset all numerical values to new specified values.\n * @param factor The new factor\n * @param ePow The new euler power\n * @param piPow The new pi power\n * @param iPow The new imaginary power\n */\n public void set(double factor, long ePow, long piPow, long iPow)\n {\n setFactor(factor);\n setEPow(ePow);\n setPiPow(piPow);\n setIPow(iPow);\n }\n\n /** Returns whether or not some symbols (i.e. variables or the constants pi, e, i) are visible (i.e. their power != 0)\n * @return True if one or more symbols are visible, false otherwise */\n public boolean symbolVisible()\n {\n if((piPow | ePow | iPow) != 0)\n return true;\n for(int i = 0; i < varPows.length; ++i)\n {\n if(varPows[i] != 0)\n return true;\n }\n return false;\n }\n \n /** The XML element name */\n public static final String NAME = \"constant\";\n /** The factor XML element attribute */\n public static final String ATTR_FACTOR = \"factor\";\n /** The E constant XML element attribute */\n public static final String ATTR_E = \"eulers_number\";\n /** The PI constant XML element attribute */\n public static final String ATTR_PI = \"pi\";\n /** The I constant XML element attribute */\n public static final String ATTR_I = \"imaginary_unit\";\n /** The prefix for a variable XML element attribute (followed by the name of the variable) */\n public static final String ATTR_VAR = \"var_\";\n \n @Override\n public void writeToXML(Document doc, Element el)\n {\n Element e = doc.createElement(NAME);\n e.setAttribute(ATTR_FACTOR, String.valueOf(factor));\n e.setAttribute(ATTR_E, String.valueOf(ePow));\n e.setAttribute(ATTR_PI, String.valueOf(piPow));\n e.setAttribute(ATTR_I, String.valueOf(iPow));\n for(int i = 0; i < varPows.length; i++)\n {\n if(varPows[i] != 0)\n e.setAttribute(ATTR_VAR + (char) ('a' + i), String.valueOf(varPows[i]));\n }\n el.appendChild(e);\n }\n\n /** The precision for determining roundoff errors in the powers. */\n private static final double EPSILON = 0.0000001;\n\n /**\n * Tries to multiply the given integer and real number to get an integer result.\n * Throws an exception if the result is not an integer.\n * @param integer The integer to multiply with the real value.\n * @param real The real value to multiply with the integer.\n * @return The multiplied value.\n * @throws Exception When the result is not an integer.\n */\n private long tryMultiplyWithIntegerResult(long integer, double real) throws Exception\n {\n double result = integer * real;\n long resultAsInteger = Math.round(result);\n if(Math.abs(result - resultAsInteger) >= EPSILON)\n throw new Exception(\"Multiplying \" + Long.toString(integer) + \" and \" + Double.toString(real) + \" does not give an integer.\");\n return resultAsInteger;\n }\n}" ]
import java.util.ArrayList; import org.teaminfty.math_dragon.R; import org.teaminfty.math_dragon.view.MathSymbolEditor; import org.teaminfty.math_dragon.view.ShowcaseViewDialog; import org.teaminfty.math_dragon.view.ShowcaseViewDialogs; import org.teaminfty.math_dragon.view.MathSymbolEditor.EditingSymbol; import org.teaminfty.math_dragon.view.math.Expression; import org.teaminfty.math_dragon.view.math.Symbol; import android.app.Activity; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ToggleButton;
package org.teaminfty.math_dragon.view.fragments; public class FragmentKeyboard extends DialogFragment implements MathSymbolEditor.OnStateChangeListener, MathSymbolEditor.OnScrollToListener, Tutorial { /** The {@link MathSymbolEditor} in this fragment */ private MathSymbolEditor mathSymbolEditor = null; /** A {@link Expression} we saved for later to set to {@link FragmentKeyboard#mathSymbolEditor mathSymbolEditor} */
private Expression exprForLater = null;
4
Ahmed-Abdelmeged/ADAS
app/src/main/java/com/example/mego/adas/accidents/ui/AccidentFragment.java
[ "public class AccidentAdapterRecycler extends RecyclerView.Adapter<AccidentAdapterRecycler.AccidentViewHolder> {\n\n /**\n * An on-click handler that we've defined to make it easy for an Activity to interface with\n * our RecyclerView\n */\n final private AccidentClickCallBacks mOnClickListener;\n\n /**\n * List to hold accidents object\n */\n private ArrayList<Accident> accidentList = new ArrayList<>();\n\n\n /**\n * Constructor for GreenAdapter that accepts a number of items to display and the specification\n * for the ListItemClickListener.\n *\n * @param listener Listener for list item clicks\n */\n public AccidentAdapterRecycler(AccidentClickCallBacks listener) {\n mOnClickListener = listener;\n }\n\n @Override\n public AccidentAdapterRecycler.AccidentViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n\n Context context = viewGroup.getContext();\n int layoutIdForListItem = R.layout.item_accident;\n LayoutInflater inflater = LayoutInflater.from(context);\n boolean shouldAttachToParentImmediately = false;\n\n View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);\n\n return new AccidentViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(AccidentAdapterRecycler.AccidentViewHolder holder, int position) {\n\n //get the current accident to extract DataSend from it\n Accident currentAccident = accidentList.get(position);\n\n assert currentAccident != null;\n String date = currentAccident.getDate();\n holder.dateTextView.setText(date);\n\n String time = currentAccident.getTime();\n holder.timeTextView.setText(time);\n\n String accidentTitle = currentAccident.getAccidentTitle();\n holder.accidentTitleTextView.setText(accidentTitle + \" \" + (position + 1));\n\n double longitude = currentAccident.getAccidentLongitude();\n double latitude = currentAccident.getAccidentLatitude();\n String accidentPosition = \"lng: \" + longitude + \" ,lat: \" + latitude;\n holder.accidentPositionTextView.setText(accidentPosition);\n\n }\n\n @Override\n public int getItemCount() {\n if (accidentList == null) return 0;\n return accidentList.size();\n }\n\n /**\n * Cache of the children views for a list item.\n */\n class AccidentViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n\n //set the current accident date\n TextView dateTextView;\n\n //set the current step time\n TextView timeTextView;\n\n //setup the accident title\n TextView accidentTitleTextView;\n\n //setup the accident position\n TextView accidentPositionTextView;\n\n\n AccidentViewHolder(View itemView) {\n super(itemView);\n\n dateTextView = itemView.findViewById(R.id.accident_date_text_view);\n timeTextView = itemView.findViewById(R.id.accident_time_text_view);\n accidentTitleTextView = itemView.findViewById(R.id.accident_name_textView);\n accidentPositionTextView = itemView.findViewById(R.id.accident_position_textView);\n\n itemView.setOnClickListener(this);\n }\n\n /**\n * Called whenever a user clicks on an item in the list.\n *\n * @param v The View that was clicked\n */\n @Override\n public void onClick(View v) {\n mOnClickListener.onAccidentClick(\n accidentList.get(getAdapterPosition()).getAccidentId());\n }\n }\n\n\n public void setAccidents(List<Accident> accidents) {\n accidentList.addAll(accidents);\n notifyDataSetChanged();\n }\n\n public void clearAccidents() {\n accidentList.clear();\n notifyDataSetChanged();\n }\n\n public void addAccident(Accident accident) {\n accidentList.add(accident);\n notifyDataSetChanged();\n }\n\n}", "public interface AccidentClickCallBacks {\n void onAccidentClick(String accidentID);\n}", "public class AccidentViewModel extends AndroidViewModel {\n\n private AccidentRepository repository;\n\n public AccidentViewModel(Application application) {\n super(application);\n repository = new AccidentRepository(application);\n }\n\n public void addAccidents(List<Accident> accidents) {\n repository.insertAccidents(accidents)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new CompletableObserver() {\n @Override\n public void onSubscribe(@NonNull Disposable d) {\n\n }\n\n @Override\n public void onComplete() {\n Timber.e(\"Accidents inserted successfully\");\n }\n\n @Override\n public void onError(@NonNull Throwable e) {\n Timber.e(\"Error inserting accidents\");\n }\n });\n }\n\n public void addAccident(Accident accident) {\n repository.insertAccident(accident)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new CompletableObserver() {\n @Override\n public void onSubscribe(Disposable d) {\n\n }\n\n @Override\n public void onComplete() {\n Timber.e(\"Accident inserted successfully\");\n }\n\n @Override\n public void onError(Throwable e) {\n Timber.e(\"Error inserting accident\");\n }\n });\n }\n\n public void deleteAccidents(List<Accident> accidents) {\n repository.deleteAccidents(accidents)\n .subscribeOn(Schedulers.io())\n .observeOn(AndroidSchedulers.mainThread())\n .subscribe(new CompletableObserver() {\n @Override\n public void onSubscribe(@NonNull Disposable d) {\n\n }\n\n @Override\n public void onComplete() {\n Timber.e(\"Accidents deleted successfully\");\n }\n\n @Override\n public void onError(@NonNull Throwable e) {\n Timber.e(\"Error deleting accidents\");\n }\n });\n }\n\n public LiveData<List<Accident>> getAccidents() {\n return repository.getAccidents();\n }\n\n public LiveData<Accident> getAccident(String accidentId) {\n return repository.getAccident(accidentId);\n }\n}", "public class AuthenticationUtilities {\n\n /**\n * Default value for the current user\n */\n private static final String USER_DEFAULT_UID = null;\n private static final String USER_DEFAULT_NAME = null;\n private static final String USER_DEFAULT_EMAIL = null;\n private static final String USER_DEFAULT_PHONE = null;\n private static final String USER_DEFAULT_LOCATION = null;\n\n /**\n * Constants for the user uid that will store in the sharped preference to load user data in each fragment\n */\n private static final String USER_UID = \"user_uid\";\n private static final String USER_NAME = \"user_name\";\n private static final String USER_EMAIL = \"user_email\";\n private static final String USER_PHONE = \"user_phone\";\n private static final String USER_LOCATION = \"user_location\";\n\n /**\n * Helper method to validate the email\n */\n public static boolean isEmailValid(CharSequence email) {\n return (email != null && Patterns.EMAIL_ADDRESS.matcher(email).matches());\n }\n\n /**\n * Helper method to validate the password\n */\n public static boolean isPasswordValid(CharSequence password) {\n return password.length() >= 6;\n }\n\n /**\n * Helper method to validate the phone number\n */\n public static boolean isPhoneNumberValid(CharSequence phoneNumber) {\n boolean isGoodPhone = false;\n if (!Pattern.matches(\"[a-zA-Z]+\", phoneNumber)) {\n isGoodPhone = !(phoneNumber.length() < 5 || phoneNumber.length() > 14);\n } else {\n isGoodPhone = false;\n }\n return isGoodPhone;\n }\n\n /**\n * Helper Method to hide the keyboard\n */\n public static void hideKeyboard(Activity activity) {\n View view = activity.getCurrentFocus();\n if (view != null) {\n ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE)).\n hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);\n }\n }\n\n /**\n * Helper method to set the current user\n */\n synchronized public static void setCurrentUser(String uid, String name\n , String email, String phoneNumber, String location, Context context) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);\n\n SharedPreferences.Editor editor = preferences.edit();\n\n editor.putString(USER_UID, uid);\n editor.putString(USER_NAME, name);\n editor.putString(USER_EMAIL, email);\n editor.putString(USER_PHONE, phoneNumber);\n editor.putString(USER_LOCATION, location);\n editor.apply();\n }\n\n /**\n * Helper method to get the current user\n */\n public static User getCurrentUser(Context context) {\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n String userUid = sharedPreferences.getString(USER_UID, USER_DEFAULT_UID);\n String userName = sharedPreferences.getString(USER_NAME, USER_DEFAULT_NAME);\n String userLocation = sharedPreferences.getString(USER_LOCATION, USER_DEFAULT_LOCATION);\n String userPhone = sharedPreferences.getString(USER_PHONE, USER_DEFAULT_PHONE);\n String userEmail = sharedPreferences.getString(USER_EMAIL, USER_DEFAULT_EMAIL);\n return new User(userEmail, userPhone, userLocation, userName, userUid);\n }\n\n /**\n * Helper Method to set the current user location\n */\n synchronized public static void setCurrentUserLocation(Context context, String location) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = preferences.edit();\n editor.putString(USER_LOCATION, location);\n editor.apply();\n }\n\n /**\n * Helper Method to set the current user name\n */\n synchronized public static void setCurrentUserName(Context context, String name) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = preferences.edit();\n editor.putString(USER_NAME, name);\n editor.apply();\n }\n\n /**\n * Helper Method to set the current user phone\n */\n synchronized public static void setCurrentUserPhone(Context context, String phone) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = preferences.edit();\n editor.putString(USER_PHONE, phone);\n editor.apply();\n }\n\n /**\n * Helper method to clear current user\n */\n synchronized public static void clearCurrentUser(Context context) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = preferences.edit();\n\n editor.putString(USER_UID, null);\n editor.putString(USER_NAME, null);\n editor.putString(USER_EMAIL, null);\n editor.putString(USER_PHONE, null);\n editor.putString(USER_LOCATION, null);\n editor.apply();\n }\n}", "public class User {\n\n private String email;\n private String phoneNumber;\n private String location;\n private String fullName;\n private HashMap<String, Object> timestampJoined;\n private String userUid;\n private boolean isPhoneVerified;\n private String devicePushToken;\n\n\n /**\n * User constructor for now user\n *\n * @param email\n * @param phoneNumber\n * @param location\n * @param fullName\n */\n public User(String email, String phoneNumber, String location, String fullName\n , HashMap<String, Object> timestampJoined, boolean isPhoneVerified, String devicePushToken) {\n this.email = email;\n this.phoneNumber = phoneNumber;\n this.location = location;\n this.fullName = fullName;\n this.timestampJoined = timestampJoined;\n this.isPhoneVerified = isPhoneVerified;\n this.devicePushToken = devicePushToken;\n }\n\n /**\n * User constructor for verify user\n *\n * @param email\n * @param phoneNumber\n * @param location\n * @param fullName\n * @param userUid\n */\n public User(String email, String phoneNumber, String location, String fullName, String userUid) {\n this.email = email;\n this.phoneNumber = phoneNumber;\n this.location = location;\n this.fullName = fullName;\n this.userUid = userUid;\n }\n\n /**\n * empty constructor\n */\n public User() {\n }\n\n public String getEmail() {\n return email;\n }\n\n public String getPhoneNumber() {\n return phoneNumber;\n }\n\n public String getLocation() {\n return location;\n }\n\n public String getFullName() {\n return fullName;\n }\n\n public HashMap<String, Object> getTimestampJoined() {\n return timestampJoined;\n }\n\n public String getUserUid() {\n return userUid;\n }\n\n public boolean isPhoneVerified() {\n return isPhoneVerified;\n }\n\n public void setPhoneVerified(boolean phoneVerified) {\n isPhoneVerified = phoneVerified;\n }\n\n public void setUserUid(String userUid) {\n this.userUid = userUid;\n }\n\n public String getDevicePushToken() {\n return devicePushToken;\n }\n\n public void setDevicePushToken(String devicePushToken) {\n this.devicePushToken = devicePushToken;\n }\n\n @Override\n public String toString() {\n return \"User: \" + userUid + \" Name: \" + fullName + \" Email: \" + email +\n \" Phone: \" + phoneNumber + \" Location: \" + location;\n }\n}", "@Entity(tableName = \"accidents\")\npublic class Accident {\n\n @PrimaryKey\n private String accidentId;\n\n private String date;\n private String time;\n\n @ColumnInfo(name = \"accident_title\")\n private String accidentTitle;\n @ColumnInfo(name = \"accident_longitude\")\n private double accidentLongitude;\n @ColumnInfo(name = \"accident_latitude\")\n private double accidentLatitude;\n\n /**\n * Required public constructor\n */\n @Ignore\n public Accident() {\n }\n\n /**\n * Use the constructor to create new Accident\n *\n * @param date\n * @param time\n * @param accidentTitle\n * @param accidentLongitude\n * @param accidentLatitude\n * @param accidentId\n */\n public Accident(String date, String time, String accidentTitle, double accidentLongitude,\n double accidentLatitude, String accidentId) {\n this.date = date;\n this.time = time;\n this.accidentTitle = accidentTitle;\n this.accidentLongitude = accidentLongitude;\n this.accidentLatitude = accidentLatitude;\n this.accidentId = accidentId;\n }\n\n public String getDate() {\n return date;\n }\n\n public String getTime() {\n return time;\n }\n\n public String getAccidentTitle() {\n return accidentTitle;\n }\n\n public double getAccidentLongitude() {\n return accidentLongitude;\n }\n\n public double getAccidentLatitude() {\n return accidentLatitude;\n }\n\n public String getAccidentId() {\n return accidentId;\n }\n\n public void setAccidentId(String accidentId) {\n this.accidentId = accidentId;\n }\n}", "public final class Constants {\n\n /**\n * Key for get teh video item bundle extra\n */\n public static final String KEY_ITEM_VIDEO = \"item_video\";\n\n /**\n * key for get the accident id key bundle extra\n */\n public static final String ACCIDENT_ID_KEY = \"accident_id\";\n\n /**\n * Google Client API Key\n */\n public static final String API_KEY = \"AIzaSyBKyxvJIHYfhjsvINFgF3fwvCiViQ5Ie7c\";\n\n /**\n * directions Constants that get from the html instructions\n * to determine the photo that will show in the list\n * and send the car direction vay bluetooth\n */\n public static final String DIRECTION_TURN_RIGHT = \"Turn right\";\n public static final String DIRECTION_TURN_LEFT = \"Turn left\";\n public static final String DIRECTION_HEAD = \"Head\";\n public static final String DIRECTION_SLIGHT_RIGHT = \"Slight right\";\n public static final String DIRECTION_SLIGHT_LEFT = \"Slight right\";\n public static final String DIRECTION_KEEP_LEFT = \"Keep left\";\n public static final String DIRECTION_KEEP_RIGHT = \"Keep right\";\n public static final String DIRECTION_MAKE_U_TURN = \"Make a U-turn\";\n public static final String DIRECTION_MERGE = \"Merge\";\n public static final String DIRECTION_ROUNDABOUT = \"roundabout\";\n public static final String DIRECTION_SHARP_RIGHT = \"Sharp right\";\n public static final String DIRECTION_SHARP_LEFT = \"Sharp left\";\n\n /**\n * Firebase database reference Constants for the directions\n */\n public static final String FIREBASE_DIRECTIONS = \"directions\";\n\n public static final String FIREBASE_START_LOCATION = \"startLocation\";\n public static final String FIREBASE_GOING_LOCATION = \"goingLocation\";\n public static final String FIREBASE_CURRENT_LOCATION = \"currentLocation\";\n\n public static final String FIREBASE_LEG_DISTANCE_TEXT = \"legDistance\";\n public static final String FIREBASE_LEG_DURATION_TEXT = \"legDuration\";\n\n public static final String FIREBASE_LEG_OVERVIEW_POLYLINE = \"legOverViewPolyline\";\n\n public static final String FIREBASE_STEPS = \"steps\";\n\n /**\n * Firebase database reference Constants for the videos\n */\n public static final String FIREBASE_LIVE_STREAMING_VIDEO_ID = \"liveStreamingVideoID\";\n\n\n /**\n * Constants to determine if there is a current streaming or not\n */\n public static final String LIVE_STREAMING_NO_LIVE_VIDEO = \"no live video\";\n\n /**\n * Firebase database reference Constants for the car\n */\n public static final String FIREBASE_CAR = \"car\";\n\n public static final String FIREBASE_CONNECTION_STATE = \"connectionState\";\n public static final String FIREBASE_ACCIDENT_STATE = \"accidentState\";\n public static final String FIREBASE_START_STATE = \"startState\";\n public static final String FIREBASE_LOCK_STATE = \"lockState\";\n public static final String FIREBASE_LIGHTS_STATE = \"lightsState\";\n\n public static final String FIREBASE_MAPPING_SERVICES = \"mappingServices\";\n\n public static final String FIREBASE_ACCIDENTS = \"accidents\";\n\n public static final String FIREBASE_SENSORES_VALUES = \"sensorsValues\";\n\n public static final String FIREBASE_USERS = \"users\";\n public static final String FIREBASE_USER_INFO = \"userInfo\";\n\n public static final String FIREBASE_USER_PLAYLIST_ID = \"playlistId\";\n\n\n /**\n * Facebook Uri for the team\n */\n public static final String FACEBOOK_URI_AHMED_ABD_ELMEGED = \"https://www.facebook.com/ven.rto\";\n public static final String FACEBOOK_URI_HUSSAM_MOSTAFA = \"https://www.facebook.com/hussam.mostafa.1994\";\n public static final String FACEBOOK_URI_DOAA_ELSHAZLY = \"https://www.facebook.com/doaa.elshazly.12\";\n\n\n /**\n * Constants for no live video\n */\n public static final String NO_LIVE_VIDEO = \"no live video\";\n\n /**\n * Constants for verify phone number\n */\n public static final String FIREBASE_IS_VERIFIED_PHONE = \"phoneVerified\";\n public static final String FIREBASE_USER_PHONE = \"phoneNumber\";\n\n /**\n * Constants for firebase storage user photo\n */\n public static final String FIREBASE_USER_IMAGE = \"userImage\";\n\n /**\n * Constants for update current user\n */\n public static final String FIREBASE_USER_LOCATION = \"location\";\n public static final String FIREBASE_USER_NAME = \"fullName\";\n\n /**\n * Constants for user device token to use it for FCM\n */\n public static final String FIREBASE_DEVICE_TOKEN = \"devicePushToken\";\n\n /**\n * Key for get the phone number extra when sign up\n */\n public static final String VERIFY_NUMBER_INTENT_EXTRA_KEY = \"verify_number_intent_extra\";\n\n /**\n * Keys for get the JSON objects form FCM\n */\n public static final String FCM_LONGITUDE = \"longitude\";\n public static final String FCM_LATITIDE = \"latitude\";\n public static final String FCM_TITLE = \"title\";\n public static final String FCM_SOUND = \"sound\";\n public static final String FCM_STATE = \"state\";\n\n /**\n * Keys for get the longitude and latitude for the accident fcm notification\n */\n public static final String FCM_LONGITUDE_EXTRA = \"fcm_longitude_extra\";\n public static final String FCM_LATITUDE_EXTRA = \"fcm_latitude_extra\";\n\n}", "public class NetworkUtil {\n /**\n * Helper method to check the internet connection isAvailableInternetConnection\n */\n public static boolean isAvailableInternetConnection(Context context) {\n ConnectivityManager connectivityManager = (ConnectivityManager)\n context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();\n return networkInfo != null && networkInfo.isConnected();\n }\n}" ]
import android.arch.lifecycle.LifecycleFragment; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import com.example.mego.adas.R; import com.example.mego.adas.accidents.adapter.AccidentAdapterRecycler; import com.example.mego.adas.accidents.adapter.AccidentClickCallBacks; import com.example.mego.adas.accidents.viewmodel.AccidentViewModel; import com.example.mego.adas.auth.AuthenticationUtilities; import com.example.mego.adas.auth.User; import com.example.mego.adas.accidents.db.entity.Accident; import com.example.mego.adas.utils.Constants; import com.example.mego.adas.utils.NetworkUtil; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; import java.util.List;
/* * Copyright (c) 2017 Ahmed-Abdelmeged * * github: https://github.com/Ahmed-Abdelmeged * email: ahmed.abdelmeged.vm@gamil.com * Facebook: https://www.facebook.com/ven.rto * Twitter: https://twitter.com/A_K_Abd_Elmeged * * 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 com.example.mego.adas.accidents.ui; /** * A simple {@link Fragment} subclass. * <p> * to show list of accidents */ public class AccidentFragment extends LifecycleFragment implements AccidentClickCallBacks { /** * UI Elements */ private RecyclerView accidentsRecycler; private ProgressBar loadingBar; private TextView emptyText; /** * adapter for accidents list */ private AccidentAdapterRecycler accidentAdapterRecycler; private AccidentFragment accidentFragment; private AccidentViewModel viewModel; private List<Accident> currentAccdeints = new ArrayList<>(); /** * Firebase objects * to specific part of the database */ private FirebaseDatabase mFirebaseDatabase; private DatabaseReference accidentsDatabaseReference; private ChildEventListener accidentsEventListener; public AccidentFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_accident, container, false); initializeScreen(rootView); accidentFragment = (AccidentFragment) getFragmentManager().findFragmentById(R.id.fragment_container); accidentAdapterRecycler = new AccidentAdapterRecycler(this); viewModel = ViewModelProviders.of(this).get(AccidentViewModel.class); LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); accidentsRecycler.setLayoutManager(layoutManager); accidentsRecycler.setHasFixedSize(true); accidentsRecycler.setAdapter(accidentAdapterRecycler); //set up the firebase mFirebaseDatabase = FirebaseDatabase.getInstance(); //get the current user uid User currentUser = AuthenticationUtilities.getCurrentUser(getContext()); String uid = currentUser.getUserUid(); //get the references for the childes
accidentsDatabaseReference = mFirebaseDatabase.getReference().child(Constants.FIREBASE_USERS)
6
jpaoletti/jPOS-Presentation-Manager
modules/pm_struts/src/org/jpos/ee/pm/struts/actions/ActionSupport.java
[ "public class PMMessage {\n private String key;\n private String message;\n private String arg0;\n private String arg1;\n private String arg2;\n private String arg3;\n \n /**\n * Constructor with a key\n * \n * @param key The key\n */\n public PMMessage(String key){\n \n }\n\n /**\n * String representation\n * @return\n */\n @Override\n public String toString() {\n return \"PMMessage{\" + \"key=\" + key + \", message=\" + message + '}';\n }\n\n /**\n * Helper constructor\n * @param key\n * @param message\n */\n public PMMessage(String key, String message) {\n super();\n this.message = message;\n }\n\n /**\n * Helper constructor\n * @param key\n * @param message\n * @param arg0\n */\n public PMMessage(String key, String message, String arg0) {\n super();\n this.message = message;\n this.arg0 = arg0;\n }\n\n /**\n * Helper constructor\n * @param key\n * @param message\n * @param arg0\n * @param arg1\n */\n public PMMessage(String key, String message, String arg0, String arg1) {\n super();\n this.message = message;\n this.arg0 = arg0;\n this.arg1 = arg1;\n }\n\n /**\n * Helper constructor\n * @param key\n * @param message\n * @param arg0\n * @param arg1\n * @param arg2\n */\n public PMMessage(String key, String message, String arg0, String arg1, String arg2) {\n super();\n this.message = message;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.arg2 = arg2;\n }\n\n /**\n * Helper constructor\n * @param key\n * @param message\n * @param arg0\n * @param arg1\n * @param arg2\n * @param arg3\n */\n public PMMessage(String key, String message, String arg0, String arg1, String arg2, String arg3) {\n super();\n this.message = message;\n this.arg0 = arg0;\n this.arg1 = arg1;\n this.arg2 = arg2;\n this.arg3 = arg3;\n }\n\n /**\n * @param message the message to set\n */\n public void setMessage(String message) {\n this.message = message;\n }\n\n /**\n * @return the message\n */\n public String getMessage() {\n return message;\n }\n\n /**\n * @param arg0 the arg0 to set\n */\n public void setArg0(String arg0) {\n this.arg0 = arg0;\n }\n\n /**\n * @return the arg0\n */\n public String getArg0() {\n return arg0;\n }\n\n /**\n * @param arg1 the arg1 to set\n */\n public void setArg1(String arg1) {\n this.arg1 = arg1;\n }\n\n /**\n * @return the arg1\n */\n public String getArg1() {\n return arg1;\n }\n\n /**\n * @param arg2 the arg2 to set\n */\n public void setArg2(String arg2) {\n this.arg2 = arg2;\n }\n\n /**\n * @return the arg2\n */\n public String getArg2() {\n return arg2;\n }\n\n /**\n * @param arg3 the arg3 to set\n */\n public void setArg3(String arg3) {\n this.arg3 = arg3;\n }\n\n /**\n * @return the arg3\n */\n public String getArg3() {\n return arg3;\n }\n\n /**\n * @param key the key to set\n */\n public void setKey(String key) {\n this.key = key;\n }\n\n /**\n * @return the key\n */\n public String getKey() {\n return key;\n }\n}", "public class PMUnauthorizedException extends PMException {\n private static final long serialVersionUID = -1484727708001646301L;\n\n}", "public class PresentationManager extends Observable {\n\n /** Hash value for parameter encrypt */\n public static String HASH = \"abcde54321poiuy96356abcde54321poiuy96356\";\n /** Singleton */\n public static PresentationManager pm;\n private static Long sessionIdSeed = 0L;\n private Configuration cfg;\n private static final String TAB = \" \";\n private static final String ERR = \" ==>\";\n private Map<Object, Entity> entities;\n private Map<String, MenuItemLocation> locations;\n private Map<Object, Monitor> monitors;\n private List<ExternalConverters> externalConverters;\n private PersistenceManager persistenceManager;\n private boolean error;\n private Log log;\n private PMService service;\n private final Map<String, PMSession> sessions = new HashMap<String, PMSession>();\n private Timer sessionChecker;\n\n /**\n * Initialize the Presentation Manager\n * @param cfg Configuration from bean\n * @param log Logger from bean\n * @param service Bean\n * @return\n */\n public boolean initialize(Configuration cfg, Log log, PMService service) {\n notifyObservers();\n this.cfg = cfg;\n error = false;\n this.log = log;\n this.service = service;\n\n LogEvent evt = getLog().createInfo();\n evt.addMessage(\"startup\", \"Presentation Manager activated\");\n try {\n evt.addMessage(TAB + \"<configuration>\");\n\n try {\n Class.forName(getDefaultDataAccess());\n logItem(evt, \"Default Data Access\", getDefaultDataAccess(), \"*\");\n } catch (Exception e) {\n logItem(evt, \"Default Data Access\", getDefaultDataAccess(), \"?\");\n }\n\n logItem(evt, \"Template\", getTemplate(), \"*\");\n logItem(evt, \"Menu\", getMenu(), \"*\");\n logItem(evt, \"Application version\", getAppversion(), \"*\");\n logItem(evt, \"Title\", getTitle(), \"*\");\n logItem(evt, \"Subtitle\", getSubtitle(), \"*\");\n logItem(evt, \"Contact\", getContact(), \"*\");\n logItem(evt, \"Login Required\", Boolean.toString(isLoginRequired()), \"*\");\n logItem(evt, \"Default Converter\", getDefaultConverterClass(), \"*\");\n\n final String tmp = cfg.get(\"persistence-manager\", \"org.jpos.ee.pm.core.PersistenceManagerVoid\");\n try {\n setPersistenceManager((PersistenceManager) newInstance(tmp));\n logItem(evt, \"Persistance Manager\", getPersistenceManager().getClass().getName(), \"*\");\n } catch (Exception e) {\n error = true;\n logItem(evt, \"Persistance Manager\", tmp, \"?\");\n }\n evt.addMessage(TAB + \"<configuration>\");\n\n loadEntities(cfg, evt);\n loadMonitors(cfg, evt);\n loadConverters(cfg, evt);\n loadLocations(evt);\n createSessionChecker();\n } catch (Exception exception) {\n getLog().error(exception);\n error = true;\n }\n if (error) {\n evt.addMessage(\"error\", \"One or more errors were found. Unable to start jPOS-PM\");\n }\n Logger.log(evt);\n return !error;\n }\n\n public String getTitle() {\n return cfg.get(\"title\", \"pm.title\");\n }\n\n public String getTemplate() {\n return cfg.get(\"template\", \"default\");\n }\n\n public boolean isDebug() {\n return cfg.getBoolean(\"debug\");\n }\n\n public String getAppversion() {\n return cfg.get(\"appversion\", \"1.0.0\");\n }\n\n /**\n * If debug flag is active, create a debug information log\n * \n * @param invoquer The invoquer of the debug\n * @param o Object to log\n */\n public void debug(Object invoquer, Object o) {\n if (!isDebug()) {\n return;\n }\n LogEvent evt = getLog().createDebug();\n evt.addMessage(\"[\" + invoquer.getClass().getName() + \"]\");\n evt.addMessage(o);\n Logger.log(evt);\n }\n\n protected String getDefaultConverterClass() {\n return getCfg().get(\"default-converter\");\n }\n\n private void loadMonitors(Configuration cfg, LogEvent evt) {\n PMParser parser = new MonitorParser();\n evt.addMessage(TAB + \"<monitors>\");\n Map<Object, Monitor> result = new HashMap<Object, Monitor>();\n String[] ss = cfg.getAll(\"monitor\");\n for (Integer i = 0; i < ss.length; i++) {\n try {\n Monitor m = (Monitor) parser.parseFile(ss[i]);\n result.put(m.getId(), m);\n result.put(i, m);\n m.getSource().init();\n Thread thread = new Thread(m);\n m.setThread(thread);\n thread.start();\n logItem(evt, m.getId(), m.getSource().getClass().getName(), \"*\");\n } catch (Exception exception) {\n getLog().error(exception);\n logItem(evt, ss[i], null, \"!\");\n }\n }\n monitors = result;\n evt.addMessage(TAB + \"</monitors>\");\n }\n\n /**\n * Formatting helper for startup\n * @param evt The event\n * @param s1 Text\n * @param s2 Extra description\n * @param symbol Status symbol\n */\n public static void logItem(LogEvent evt, String s1, String s2, String symbol) {\n evt.addMessage(String.format(\"%s%s(%s) %-25s %s\", TAB, TAB, symbol, s1, (s2 != null) ? s2 : \"\"));\n }\n\n private void loadLocations(LogEvent evt) {\n evt.addMessage(TAB + \"<locations>\");\n MenuItemLocationsParser parser = new MenuItemLocationsParser(evt, \"cfg/pm.locations.xml\");\n locations = parser.getLocations();\n if (locations == null || locations.isEmpty()) {\n evt.addMessage(TAB + TAB + ERR + \"No location defined!\");\n error = true;\n }\n if (parser.hasError()) {\n error = true;\n }\n evt.addMessage(TAB + \"</locations>\");\n }\n\n private void loadEntities(Configuration cfg, LogEvent evt) {\n EntityParser parser = new EntityParser();\n evt.addMessage(TAB + \"<entities>\");\n if (entities == null) {\n entities = new HashMap<Object, Entity>();\n } else {\n entities.clear();\n }\n String[] ss = cfg.getAll(\"entity\");\n for (Integer i = 0; i < ss.length; i++) {\n try {\n Entity e = (Entity) parser.parseFile(ss[i]);\n try {\n Class.forName(e.getClazz());\n entities.put(e.getId(), e);\n entities.put(i, e);\n if (e.isWeak()) {\n logItem(evt, e.getId(), e.getClazz(), \"\\u00b7\");\n } else {\n logItem(evt, e.getId(), e.getClazz(), \"*\");\n }\n\n } catch (ClassNotFoundException cnte) {\n logItem(evt, e.getId(), e.getClazz(), \"?\");\n error = true;\n }\n } catch (Exception exception) {\n getLog().error(exception);\n logItem(evt, ss[i], \"???\", \"!\");\n error = true;\n }\n }\n evt.addMessage(TAB + \"</entities>\");\n }\n\n /**\n * Return the list of weak entities of the given entity.\n * @param e The strong entity\n * @return The list of weak entities\n */\n protected List<Entity> weakEntities(Entity e) {\n List<Entity> res = new ArrayList<Entity>();\n for (Entity entity : getEntities().values()) {\n if (entity.getOwner() != null && entity.getOwner().getEntityId().compareTo(e.getId()) == 0) {\n res.add(entity);\n }\n }\n if (res.isEmpty()) {\n return null;\n } else {\n return res;\n }\n }\n\n /**\n * Return the entity of the given id\n * @param id Entity id\n * @return The entity\n */\n public Entity getEntity(String id) {\n Entity e = getEntities().get(id);\n if (e == null) {\n return null;\n }\n if (e.getExtendz() != null && e.getExtendzEntity() == null) {\n e.setExtendzEntity(this.getEntity(e.getExtendz()));\n }\n return e;\n }\n\n /**\n * Return the location of the given id\n * @param id The location id\n * @return The MenuItemLocation\n */\n public MenuItemLocation getLocation(String id) {\n return locations.get(id);\n }\n\n /**\n * Return the monitor of the given id\n * @param id The monitor id\n * @return The monitor\n */\n public Monitor getMonitor(String id) {\n return getMonitors().get(id);\n }\n\n /**Create and fill a new Entity Container\n * @param id Entity id\n * @return The container\n */\n public EntityContainer newEntityContainer(String id) {\n Entity e = lookupEntity(id);\n if (e == null) {\n return null;\n }\n e.setWeaks(weakEntities(e));\n return new EntityContainer(e, HASH);\n }\n\n /**Looks for an Entity with the given id*/\n private Entity lookupEntity(String sid) {\n for (Integer i = 0; i < getEntities().size(); i++) {\n Entity e = getEntities().get(i);\n if (e != null && sid.compareTo(EntityContainer.buildId(HASH, e.getId())) == 0) {\n return getEntity(e.getId());\n }\n }\n return null;\n }\n\n\n /* Getters */\n /**\n * Getter for contact\n * @return\n */\n public String getContact() {\n return cfg.get(\"contact\", \"jeronimo.paoletti@gmail.com\");\n }\n\n /**\n * Getter for default data access\n * @return\n */\n public String getDefaultDataAccess() {\n return cfg.get(\"default-data-access\", \"org.jpos.ee.pm.core.DataAccessVoid\");\n }\n\n /**\n * Getter for entities map\n * @return\n */\n public Map<Object, Entity> getEntities() {\n return entities;\n }\n\n /**\n * Getter for location map\n * @return\n */\n public Map<String, MenuItemLocation> getLocations() {\n return locations;\n }\n\n /**\n * Getter for log\n * @return\n */\n public Log getLog() {\n return log;\n }\n\n /**\n * Getter for login required\n * @return\n */\n public boolean isLoginRequired() {\n return cfg.getBoolean(\"login-required\", true);\n }\n\n /**\n * Getter for monitor map\n * @return\n */\n public Map<Object, Monitor> getMonitors() {\n return monitors;\n }\n\n /**\n * Getter for persistanteManager\n * @return\n */\n public PersistenceManager getPersistenceManager() {\n return persistenceManager;\n }\n\n /**\n * Setter for persistenceManager\n * @param persistenceManager\n */\n public void setPersistenceManager(PersistenceManager persistenceManager) {\n this.persistenceManager = persistenceManager;\n }\n\n /**\n * Getter for singleton pm\n * @return\n */\n public static PresentationManager getPm() {\n return pm;\n }\n\n /**\n * Getter for bean \n * @return\n */\n public PMService getService() {\n return service;\n }\n\n /* Loggin helpers*/\n /**\n * Generate an info entry on the local logger\n * @param o Object to log\n */\n public void info(Object o) {\n LogEvent evt = getLog().createInfo();\n evt.addMessage(o);\n Logger.log(evt);\n }\n\n /**Generate a warn entry on the local logger\n * @param o Object to log\n */\n public void warn(Object o) {\n LogEvent evt = getLog().createWarn();\n evt.addMessage(o);\n Logger.log(evt);\n }\n\n /**Generate an error entry on the local logger\n * @param o Object to log\n */\n public void error(Object o) {\n LogEvent evt = getLog().createError();\n evt.addMessage(o);\n Logger.log(evt);\n }\n\n /* Helpers for bean management */\n /**Getter for an object property value as String\n * @param obj The object\n * @param propertyName The property\n * @return The value of the property of the object as string\n * */\n public String getAsString(Object obj, String propertyName) {\n Object o = get(obj, propertyName);\n if (o != null) {\n return o.toString();\n } else {\n return \"\";\n }\n }\n\n /**Getter for an object property value\n * @param obj The object\n * @param propertyName The property\n * @return The value of the property of the object\n * */\n public Object get(Object obj, String propertyName) {\n try {\n if (obj != null && propertyName != null) {\n return PropertyUtils.getNestedProperty(obj, propertyName);\n }\n } catch (NullPointerException e) {\n // OK to happen\n } catch (NestedNullException e) {\n // Hmm... that's fine too\n } catch (Exception e) {\n // Now I don't like it.\n error(e);\n return \"-undefined-\";\n }\n return null;\n }\n\n /**Setter for an object property value\n * @param obj The object\n * @param name The property name\n * @param value The value to set\n * */\n public void set(Object obj, String name, Object value) {\n try {\n PropertyUtils.setNestedProperty(obj, name, value);\n } catch (Exception e) {\n error(e);\n }\n }\n\n /**\n * Creates a new instance object of the given class.\n * @param clazz The Class of the new Object\n * @return The new Object or null on any error.\n */\n public Object newInstance(String clazz) {\n try {\n return getService().getFactory().newInstance(clazz);\n } catch (Exception e) {\n error(e);\n return null;\n }\n }\n\n private void loadConverters(Configuration cfg, LogEvent evt) {\n PMParser parser = new ExternalConverterParser();\n evt.addMessage(TAB + \"<external-converters>\");\n externalConverters = new ArrayList<ExternalConverters>();\n String[] ss = cfg.getAll(\"external-converters\");\n for (Integer i = 0; i < ss.length; i++) {\n try {\n ExternalConverters ec = (ExternalConverters) parser.parseFile(ss[i]);\n externalConverters.add(ec);\n logItem(evt, ss[i], null, \"*\");\n } catch (Exception exception) {\n getLog().error(exception);\n logItem(evt, ss[i], null, \"!\");\n }\n }\n evt.addMessage(TAB + \"</external-converters>\");\n }\n\n public Converter findExternalConverter(String id) {\n for (ExternalConverters ecs : externalConverters) {\n ConverterWrapper w = ecs.getWrapper(id);\n if (w != null) {\n return w.getConverter();\n }\n }\n return null;\n }\n\n /**\n * Creates a new session with the given id\n * @param sessionId The new session id. Must be unique.\n * @throws PMException on already defined session\n * @return New session\n */\n public PMSession registerSession(String sessionId) throws PMException {\n synchronized (sessions) {\n if (sessions.containsKey(sessionId)) {\n throw new PMException(\"Session already defined\");\n }\n sessions.put(sessionId, new PMSession(sessionId));\n return getSession(sessionId);\n }\n }\n\n /**\n * Return the session for the given id\n * @param sessionId The id of the wanted session\n * @return The session\n */\n public PMSession getSession(String sessionId) {\n final PMSession s = sessions.get(sessionId);\n if (s != null) {\n s.setLastAccess(new Date());\n }\n return s;\n }\n\n /**\n * Getter for the session map.\n * @return Sessions\n */\n public Map<String, PMSession> getSessions() {\n return sessions;\n }\n\n /**\n * Removes the given id session \n */\n public void removeSession(String sessionId) {\n sessions.remove(sessionId);\n }\n\n public Configuration getCfg() {\n return cfg;\n }\n\n public String getSubtitle() {\n return cfg.get(\"subtitle\", \"pm.subtitle\");\n }\n\n private void createSessionChecker() {\n final Long timeout = cfg.getLong(\"session-timeout\", 60 * 60) * 1000;\n final int interval = cfg.getInt(\"session-check-interval\", 60 * 5) * 1000;\n sessionChecker = new Timer();\n sessionChecker.schedule(new TimerTask() {\n\n @Override\n public void run() {\n synchronized (sessions) {\n List<String> toRemove = new ArrayList<String>();\n for (Map.Entry<String, PMSession> entry : sessions.entrySet()) {\n if (entry.getValue().getLastAccess().getTime() + timeout < System.currentTimeMillis()) {\n toRemove.add(entry.getKey());\n }\n }\n for (String session : toRemove) {\n removeSession(session);\n }\n }\n }\n }, 0, interval);\n }\n\n public String getCopyright() {\n return cfg.get(\"copyright\", \"jpos.org\");\n }\n\n public String getMenu() {\n return cfg.get(\"menu\", \"cfg/pm.menu.xml\");\n }\n\n public static synchronized String newSessionId() {\n sessionIdSeed++;\n return sessionIdSeed.toString();\n }\n\n /**\n * Returns the internacionalized string for the given key\n */\n public static String getMessage(String key, Object... params) {\n try {\n ResourceBundle bundle = ResourceBundle.getBundle(\"org.jpos.ee.ApplicationResource\");\n String string = bundle.getString(key);\n if (params != null) {\n for (int i = 0; i < params.length; i++) {\n String param = (params[i] == null) ? \"\" : params[i].toString();\n string = string.replaceAll(\"\\\\{\" + i + \"\\\\}\", param);\n }\n }\n return string;\n } catch (Exception e) {\n return key;\n }\n }\n\n public Converter getDefaultConverter() {\n try {\n if (getDefaultConverterClass() != null && !\"\".equals(getDefaultConverterClass().trim())) {\n return (Converter) newInstance(getDefaultConverterClass());\n }\n } catch (Exception e) {\n }\n return null;\n }\n}", "public class PMEntitySupport extends EntitySupport {\r\n\r\n public static final String PMSESSION = \"pmsession\";\r\n public static String PM_ID = \"pmid\";\r\n public static final String LAST_PM_ID = \"last_pmid\";\r\n private String context_path;\r\n private static PMEntitySupport instance;\r\n private HttpServletRequest request;\r\n\r\n /**\r\n * Singleton getter\r\n * @return The PMEntitySupport\r\n */\r\n public synchronized static PMEntitySupport getInstance() {\r\n if (instance == null) {\r\n instance = new PMEntitySupport();\r\n }\r\n return instance;\r\n }\r\n\r\n /**\r\n * Return the container that is in the given request\r\n *\r\n * @param request The request\r\n * @return The container\r\n */\r\n public EntityContainer getContainer() throws PMStrutsException {\r\n if (request == null) {\r\n throw new PMStrutsException(\"request.not.found\");\r\n }\r\n String pmid = (String) request.getAttribute(PM_ID);\r\n return getPMSession().getContainer(pmid);\r\n }\r\n\r\n public PMSession getPMSession() throws PMStrutsException {\r\n if (request == null) {\r\n throw new PMStrutsException(\"request.not.found\");\r\n }\r\n return (PMSession) request.getSession().getAttribute(PMSESSION);\r\n }\r\n\r\n /**\r\n * Inserts the container entity into the request\r\n *\r\n * @param request The request\r\n * @return The entity\r\n * @throws PMStrutsException when the request was not setted\r\n */\r\n public Entity getEntity() throws PMStrutsException {\r\n EntityContainer container = getContainer();\r\n if (container != null) {\r\n return container.getEntity();\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Inserts the container list into the request\r\n * @param request The request\r\n * @return The list\r\n * @throws PMStrutsException when request has no container\r\n */\r\n public PaginatedList getList() throws PMStrutsException {\r\n EntityContainer container = getContainer();\r\n if (container == null) {\r\n throw new PMStrutsException(\"container.not.found\");\r\n }\r\n PaginatedList list = container.getList();\r\n return list;\r\n }\r\n\r\n /**\r\n * Insert the container selected instance into the request\r\n * @param request The request\r\n * @return The list\r\n * @throws PMStrutsException when request has no container\r\n */\r\n public Object getSelected() throws PMStrutsException {\r\n EntityContainer container = getContainer();\r\n if (container == null) {\r\n throw new PMStrutsException(\"container.not.found\");\r\n }\r\n Object r = container.getSelected().getInstance();\r\n return r;\r\n }\r\n\r\n /**\r\n * Returns the filter applied\r\n * \r\n * @return The filter\r\n * @throws PMStrutsException when request has no container\r\n */\r\n public EntityFilter getFilter() throws PMStrutsException {\r\n EntityContainer container = getContainer();\r\n if (container == null) {\r\n throw new PMStrutsException(\"container.not.found\");\r\n }\r\n return container.getFilter();\r\n }\r\n\r\n /**\r\n * Setter for context path\r\n *\r\n * @param context_path The context_path\r\n */\r\n public void setContext_path(String context_path) {\r\n this.context_path = context_path;\r\n }\r\n\r\n /**\r\n * Getter for context path\r\n * \r\n * @return The context_path\r\n */\r\n public String getContext_path() {\r\n return context_path;\r\n }\r\n\r\n public HttpServletRequest getRequest() {\r\n return request;\r\n }\r\n\r\n public void setRequest(HttpServletRequest request) {\r\n this.request = request;\r\n }\r\n\r\n public Integer getListTotalDigits() {\r\n try {\r\n return (getList().getTotal() == null || getList().getTotal() == 0) ? 1 : (int) Math.log10(getList().getTotal()) + 1;\r\n } catch (PMStrutsException ex) {\r\n return 0;\r\n }\r\n }\r\n\r\n public String getNavigationList(final EntityContainer container) {\r\n final StringBuilder sb = new StringBuilder();\r\n if (container != null) {\r\n sb.append(getNavigationList(container.getOwner()));\r\n sb.append(\"&nbsp; &gt; &nbsp;\");\r\n sb.append(\"<a href='\");\r\n sb.append(getContext_path());\r\n sb.append(\"/\");\r\n sb.append(container.getOperation().getId());\r\n sb.append(\".do?pmid=\");\r\n sb.append(container.getEntity().getId()).append(\" >\");\r\n sb.append(container.getSelected().getInstance());\r\n sb.append(\"</a>\");\r\n }\r\n return sb.toString();\r\n }\r\n}\r", "public class PMForwardException extends PMException {\n /**\n * Constructor\n * \n * @param key The mapping key to forward\n */\n public PMForwardException(String key) {\n super(key);\n }\n\n private static final long serialVersionUID = 8043873501146882128L;\n}", "public class PMStrutsContext extends PMContext {\n\n public static final String PM_MAPPINGS = \"PM_MAPPINGS\";\n public static final String PM_ACTION_FORM = \"PM_ACTION_FORM\";\n public static final String PM_HTTP_REQUEST = \"PM_HTTP_REQUEST\";\n public static final String PM_HTTP_RESPONSE = \"PM_HTTP_RESPONSE\";\n public static final String CONTINUE = \"continue\";\n public static final String SUCCESS = \"success\";\n public static final String FAILURE = \"failure\";\n public static final String USER = \"user\";\n public static final String DENIED = \"denied\";\n public static final String STRUTS_LOGIN = \"login\";\n public static final String PM_LIST = \"PMLIST\";\n public static final String ENTITY = \"entity\";\n public static final String REPORT = \"report\";\n public static final String LOGGER_NAME = \"Q2\";\n public static final String ACCESS_COUNT = \"accessCount\";\n public static final String ENTITY_INSTANCE = \"entity_instance\";\n public static final String ENTITY_SUPPORT = \"es\";\n public static final String CONTEXT_PATH = \"context_path\";\n public static final String MENU = \"menu\";\n public static final String FINISH = \"finish\";\n public static final String OPERATION = \"operation\";\n public static final String OPERATIONS = \"operations\";\n public static final String ITEM_OPERATIONS = \"item_operations\";\n public static final String PM_ID = \"pmid\";\n public static final String PM_RID = \"pmrid\";\n public static final String LAST_PM_ID = \"last_pmid\";\n public static final String MODIFIED_OWNER_COLLECTION = \"moc\";\n public static final String PM_MONITOR_CONTINUE = \"PM_MONITOR_CONTINUE\";\n public static final String PM_MONITOR = \"PM_MONITOR\";\n\n public PMStrutsContext(String sessionId) {\n super(sessionId);\n }\n\n /**\n * @return the mapping\n */\n public ActionMapping getMapping() {\n return (ActionMapping) get(PM_MAPPINGS);\n }\n\n /**\n * @param mapping the mapping to set\n */\n public void setMapping(ActionMapping mapping) {\n put(PM_MAPPINGS, mapping);\n }\n\n /**\n * @return the form\n */\n public ActionForm getForm() {\n return (ActionForm) get(PM_ACTION_FORM);\n }\n\n /**\n * @param form the form to set\n */\n public void setForm(ActionForm form) {\n put(PM_ACTION_FORM, form);\n }\n\n /**\n * @return the request\n */\n public HttpServletRequest getRequest() {\n return (HttpServletRequest) get(PM_HTTP_REQUEST);\n }\n\n /**\n * @param request the request to set\n */\n public void setRequest(HttpServletRequest request) {\n put(PM_HTTP_REQUEST, request);\n }\n\n /**\n * @return the response\n */\n public HttpServletResponse getResponse() {\n return (HttpServletResponse) get(PM_HTTP_RESPONSE);\n }\n\n /**\n * @param response the response to set\n */\n public void setResponse(HttpServletResponse response) {\n put(PM_HTTP_RESPONSE, response);\n }\n\n /* ActionForwards Helpers */\n /**\n * Helper for success action forward\n * @return success action forward\n */\n public ActionForward successful() {\n return getMapping().findForward(SUCCESS);\n }\n\n /**\n * Helper for continue action forward\n * @return continue action forward\n */\n public ActionForward go() {\n return getMapping().findForward(CONTINUE);\n }\n\n /**\n * Helper for deny action forward\n * @return deny action forward\n */\n public ActionForward deny() {\n return getMapping().findForward(DENIED);\n }\n\n /**\n * Retrieve the http session\n * @return The session\n */\n public HttpSession getSession() {\n return getRequest().getSession();\n }\n\n /**\n * Getter for the entity support helper object\n * @return The entity support\n */\n public PMEntitySupport getEntitySupport() {\n PMEntitySupport r = (PMEntitySupport) getRequest().getSession().getAttribute(ENTITY_SUPPORT);\n return r;\n }\n\n private String getPmId() {\n return (String) getRequest().getAttribute(PM_ID);\n }\n\n public String getTmpName() throws PMException {\n Field field = (Field) get(Constants.PM_FIELD);\n return \"tmp_\" + getEntity().getId() + \"_\" + field.getId();\n }\n\n public List<?> getTmpList() {\n try {\n final List<?> r = (List<?>) getSession().getAttribute(getTmpName());\n return r;\n } catch (PMException ex) {\n getPresentationManager().error(ex);\n return null;\n }\n }\n}", "public class PMStrutsService extends PMService implements Constants {\n\n @Override\n protected void initService() throws Exception {\n super.initService();\n if (getDefaultConverter() == null) {\n setDefaultConverter(new DefaultStrutsConverter());\n }\n }\n}" ]
import org.jpos.ee.pm.core.PMUnauthorizedException; import org.jpos.ee.pm.core.PresentationManager; import org.jpos.ee.pm.struts.PMEntitySupport; import org.jpos.ee.pm.struts.PMForwardException; import org.jpos.ee.pm.struts.PMStrutsContext; import org.jpos.ee.pm.struts.PMStrutsService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.jpos.ee.Constants; import org.jpos.ee.pm.core.PMException; import org.jpos.ee.pm.core.PMMessage;
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2010 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.ee.pm.struts.actions; /** * A super class for all actions with some helpers and generic stuff * * @author jpaoletti */ public abstract class ActionSupport extends Action implements Constants { public static final String CONTINUE = "continue"; public static final String SUCCESS = "success"; public static final String FAILURE = "failure"; public static final String USER = "user"; public static final String DENIED = "denied"; public static final String STRUTS_LOGIN = "login"; protected abstract void doExecute(PMStrutsContext ctx) throws PMException; /**Forces execute to check if any user is logged in*/ protected boolean checkUser() { return true; } protected boolean prepare(PMStrutsContext ctx) throws PMException { if(checkUser() && ctx.getPMSession()==null){ //Force logout final PMEntitySupport es = PMEntitySupport.getInstance(); ctx.getSession().invalidate(); es.setContext_path(ctx.getRequest().getContextPath()); ctx.getSession().setAttribute(ENTITY_SUPPORT, es); ctx.getRequest().setAttribute("reload", 1); throw new PMUnauthorizedException(); } return true; } @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PMStrutsContext ctx = (PMStrutsContext) request.getAttribute(PM_CONTEXT); ctx.setMapping(mapping); ctx.setForm(form); try { boolean step = prepare(ctx); if (step) { excecute(ctx); } return mapping.findForward(SUCCESS); } catch (PMForwardException e) { return mapping.findForward(e.getKey()); } catch (PMUnauthorizedException e) { return mapping.findForward(STRUTS_LOGIN); } catch (PMException e) { ctx.getPresentationManager().debug(this, e); if (e.getKey() != null) { ctx.getErrors().add(new PMMessage(ActionMessages.GLOBAL_MESSAGE, e.getKey())); } ActionErrors errors = new ActionErrors(); for (PMMessage msg : ctx.getErrors()) { errors.add(msg.getKey(), new ActionMessage(msg.getMessage(), msg.getArg0(), msg.getArg1(), msg.getArg2(), msg.getArg3())); } saveErrors(request, errors); return mapping.findForward(FAILURE); } } protected void excecute(PMStrutsContext ctx) throws PMException { doExecute(ctx); } protected PMStrutsService getPMService() throws PMException { try {
return (PMStrutsService) PresentationManager.pm.getService();
2
yunnet/kafkaEagle
src/main/java/org/smartloli/kafka/eagle/core/factory/ZkServiceImpl.java
[ "public class AlarmDomain {\n\n\tprivate String group = \"\";\n\tprivate String topics = \"\";\n\tprivate long lag = 0L;\n\tprivate String owners = \"\";\n\tprivate String modifyDate = \"\";\n\n\tpublic String getGroup() {\n\t\treturn group;\n\t}\n\n\tpublic void setGroup(String group) {\n\t\tthis.group = group;\n\t}\n\n\tpublic String getTopics() {\n\t\treturn topics;\n\t}\n\n\tpublic void setTopics(String topics) {\n\t\tthis.topics = topics;\n\t}\n\n\tpublic String getOwners() {\n\t\treturn owners;\n\t}\n\n\tpublic void setOwners(String owners) {\n\t\tthis.owners = owners;\n\t}\n\n\tpublic long getLag() {\n\t\treturn lag;\n\t}\n\n\tpublic void setLag(long lag) {\n\t\tthis.lag = lag;\n\t}\n\n\tpublic String getModifyDate() {\n\t\treturn modifyDate;\n\t}\n\n\tpublic void setModifyDate(String modifyDate) {\n\t\tthis.modifyDate = modifyDate;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new Gson().toJson(this);\n\t}\n\n}", "public class OffsetsLiteDomain {\n\n\tprivate String group = \"\";\n\tprivate String topic = \"\";\n\tprivate long logSize = 0L;\n\tprivate long offsets = 0L;\n\tprivate long lag = 0L;\n\tprivate String created = \"\";\n\n\tpublic String getGroup() {\n\t\treturn group;\n\t}\n\n\tpublic void setGroup(String group) {\n\t\tthis.group = group;\n\t}\n\n\tpublic String getTopic() {\n\t\treturn topic;\n\t}\n\n\tpublic void setTopic(String topic) {\n\t\tthis.topic = topic;\n\t}\n\n\tpublic long getLogSize() {\n\t\treturn logSize;\n\t}\n\n\tpublic void setLogSize(long logSize) {\n\t\tthis.logSize = logSize;\n\t}\n\n\tpublic long getOffsets() {\n\t\treturn offsets;\n\t}\n\n\tpublic void setOffsets(long offsets) {\n\t\tthis.offsets = offsets;\n\t}\n\n\tpublic long getLag() {\n\t\treturn lag;\n\t}\n\n\tpublic void setLag(long lag) {\n\t\tthis.lag = lag;\n\t}\n\n\tpublic String getCreated() {\n\t\treturn created;\n\t}\n\n\tpublic void setCreated(String created) {\n\t\tthis.created = created;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new Gson().toJson(this);\n\t}\n\n}", "public class CalendarUtils {\n\n\t/**\n\t * Convert time mill into ? day ? hour ? min ? sec.\n\t * \n\t * @param timeMill\n\t * Time mill.\n\t * @return Character,from \"3600 sec\" to \"0 Day 1 Hour 0 Min 0 Sec\".\n\t */\n\tpublic static String convertTimeMill2Date(long timeMill) {\n\t\tlong day = timeMill / (3600 * 24);\n\t\tlong hour = (timeMill - 3600 * 24 * day) / (60 * 60);\n\t\tlong min = (timeMill - 3600 * 24 * day - 3600 * hour) / 60;\n\t\tlong sec = timeMill - 3600 * 24 * day - 3600 * hour - 60 * min;\n\t\treturn day + \"Day\" + hour + \"Hour\" + min + \"min\" + sec + \"sec\";\n\t}\n\n\t/**\n\t * Convert unix time to date,default is yyyy-MM-dd HH:mm:ss.\n\t * \n\t * @param unixtime\n\t * @return Date String.\n\t */\n\tpublic static String convertUnixTime(long unixtime) {\n\t\tString formatter = \"yyyy-MM-dd HH:mm:ss\";\n\t\treturn convertUnixTime(unixtime, formatter);\n\t}\n\n\t/**\n\t * Convert unix time to formatter date.\n\t * \n\t * @param unixtime\n\t * @param formatter\n\t * @return Date String.\n\t */\n\tpublic static String convertUnixTime(long unixtime, String formatter) {\n\t\tSimpleDateFormat df = new SimpleDateFormat(formatter);\n\t\treturn df.format(new Date(unixtime));\n\t}\n\n\t/**\n\t * Convert unix time to date,default is yyyy-MM-dd HH:mm:ss.\n\t * \n\t * @param unixTime\n\t * @return 1907-01-01 00:00:00\n\t */\n\tpublic static String convertUnixTime2Date(long unixtime) {\n\t\tSimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\treturn df.format(new Date(unixtime));\n\t}\n\n\t/** Get the date of the day,accurate to seconds. */\n\tpublic static String getDate() {\n\t\tSimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\t\treturn df.format(new Date());\n\t}\n\n\t/** Get custom date,like yyyy/mm/dd etc. */\n\tpublic static String getCustomDate(String formatter) {\n\t\tSimpleDateFormat df = new SimpleDateFormat(formatter);\n\t\treturn df.format(new Date());\n\t}\n\n}", "public final class SystemConfigUtils {\n\tprivate static Properties mConfig;\n\n\tprivate static final Logger LOG = LoggerFactory.getLogger(SystemConfigUtils.class);\n\tstatic {\n\t\tmConfig = new Properties();\n\t\tgetReources(\"system-config.properties\");\n\t}\n\n\t/** Load profiles from different operate systems. */\n\tprivate static void getReources(String name) {\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tString osName = System.getProperties().getProperty(\"os.name\");\n\t\t\t\tif (osName.contains(\"Mac\") || osName.contains(\"Win\")) {\n\t\t\t\t\tmConfig.load(SystemConfigUtils.class.getClassLoader().getResourceAsStream(name));\n\t\t\t\t} else {\n\t\t\t\t\tmConfig.load(new FileInputStream(System.getProperty(\"user.dir\") + \"/conf/\" + name));\n\t\t\t\t}\n\t\t\t} catch (Exception ex) {\n\t\t\t\tex.printStackTrace();\n\t\t\t}\n\t\t\tLOG.info(\"Successfully loaded default properties.\");\n\n\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\tLOG.debug(\"SystemConfig looks like this ...\");\n\n\t\t\t\tString key = null;\n\t\t\t\tEnumeration<Object> keys = mConfig.keys();\n\t\t\t\twhile (keys.hasMoreElements()) {\n\t\t\t\t\tkey = (String) keys.nextElement();\n\t\t\t\t\tLOG.debug(key + \"=\" + mConfig.getProperty(key));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tLOG.error(\"Load system name has error,msg is \" + e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Retrieve a property as a boolean ... defaults to false if not present.\n\t */\n\tpublic static boolean getBooleanProperty(String name) {\n\t\treturn getBooleanProperty(name, false);\n\t}\n\n\t/**\n\t * Retrieve a property as a boolean with specified default if not present.\n\t */\n\tpublic static boolean getBooleanProperty(String name, boolean defaultValue) {\n\t\tString value = SystemConfigUtils.getProperty(name);\n\t\tif (value == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\treturn Boolean.valueOf(value).booleanValue();\n\t}\n\n\t/** Retrieve a property as a boolean array. */\n\tpublic static boolean[] getBooleanPropertyArray(String name, boolean[] defaultValue, String splitStr) {\n\t\tString value = SystemConfigUtils.getProperty(name);\n\t\tif (value == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\ttry {\n\t\t\tString[] propertyArray = value.split(splitStr);\n\t\t\tboolean[] result = new boolean[propertyArray.length];\n\t\t\tfor (int i = 0; i < propertyArray.length; i++) {\n\t\t\t\tresult[i] = Boolean.valueOf(propertyArray[i]).booleanValue();\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (NumberFormatException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/** Retrieve a property as a int,defaults to 0 if not present. */\n\tpublic static int getIntProperty(String name) {\n\t\treturn getIntProperty(name, 0);\n\t}\n\n\t/** Retrieve a property as a int. */\n\tpublic static int getIntProperty(String name, int defaultValue) {\n\t\tString value = SystemConfigUtils.getProperty(name);\n\t\tif (value == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\ttry {\n\t\t\treturn Integer.parseInt(value);\n\t\t} catch (NumberFormatException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/** Retrieve a property as a int array. */\n\tpublic static int[] getIntPropertyArray(String name, int[] defaultValue, String splitStr) {\n\t\tString value = SystemConfigUtils.getProperty(name);\n\t\tif (value == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\ttry {\n\t\t\tString[] propertyArray = value.split(splitStr);\n\t\t\tint[] result = new int[propertyArray.length];\n\t\t\tfor (int i = 0; i < propertyArray.length; i++) {\n\t\t\t\tresult[i] = Integer.parseInt(propertyArray[i]);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/** Retrieve a property as a long,defaults to 0L if not present. */\n\tpublic static Long getLongProperty(String name) {\n\t\treturn getLongProperty(name, 0L);\n\t}\n\n\t/** Retrieve a property as a long. */\n\tpublic static Long getLongProperty(String name, Long defaultValue) {\n\t\tString value = SystemConfigUtils.getProperty(name);\n\t\tif (value == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\ttry {\n\t\t\treturn Long.parseLong(value);\n\t\t} catch (NumberFormatException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/** Retrieve a property value. */\n\tpublic static String getProperty(String key) {\n\t\treturn mConfig.getProperty(key);\n\t}\n\n\t/**\n\t * Retrieve a property value & default value.\n\t * \n\t * @param key\n\t * Retrieve key\n\t * @param defaultValue\n\t * Return default retrieve value\n\t * @return String.\n\t */\n\tpublic static String getProperty(String key, String defaultValue) {\n\t\tLOG.debug(\"Fetching property [\" + key + \"=\" + mConfig.getProperty(key) + \"]\");\n\t\tString value = SystemConfigUtils.getProperty(key);\n\t\tif (value == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\treturn value;\n\t}\n\n\t/** Retrieve a property as a array. */\n\tpublic static String[] getPropertyArray(String name, String[] defaultValue, String splitStr) {\n\t\tString value = SystemConfigUtils.getProperty(name);\n\t\tif (value == null) {\n\t\t\treturn defaultValue;\n\t\t}\n\t\ttry {\n\t\t\tString[] propertyArray = value.split(splitStr);\n\t\t\treturn propertyArray;\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/** Retrieve a property as a array,no default value. */\n\tpublic static String[] getPropertyArray(String name, String splitStr) {\n\t\tString value = SystemConfigUtils.getProperty(name);\n\t\tif (value == null) {\n\t\t\treturn null;\n\t\t}\n\t\ttry {\n\t\t\tString[] propertyArray = value.split(splitStr);\n\t\t\treturn propertyArray;\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/** Retrieve map property keys. */\n\tpublic static Map<String, String> getPropertyMap(String name) {\n\t\tString[] maps = getPropertyArray(name, \",\");\n\t\tMap<String, String> map = new HashMap<String, String>();\n\t\ttry {\n\t\t\tfor (String str : maps) {\n\t\t\t\tString[] array = str.split(\":\");\n\t\t\t\tif (array.length > 1) {\n\t\t\t\t\tmap.put(array[0], array[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tLOG.error(\"Get PropertyMap info has error,key is :\" + name);\n\t\t}\n\t\treturn map;\n\t}\n\n\t/** Retrieve all property keys. */\n\tpublic static Enumeration<Object> keys() {\n\t\treturn mConfig.keys();\n\t}\n\n\t/**\n\t * Reload special property file.\n\t * \n\t * @param name\n\t * System configure name.\n\t */\n\tpublic static void reload(String name) {\n\t\tmConfig.clear();\n\t\tgetReources(name);\n\t}\n\n\t/** Construction method. */\n\tprivate SystemConfigUtils() {\n\t}\n}", "public final class ZKPoolUtils {\n\n\tprivate final static Logger LOG = LoggerFactory.getLogger(ZKPoolUtils.class);\n\tprivate static ZKPoolUtils instance = null;\n\t/** Zookeeper client connection pool. */\n\tprivate static Map<String, Vector<ZkClient>> zkCliPools = new HashMap<>();\n\t/** Set pool max size. */\n\tprivate final static int zkCliPoolSize = SystemConfigUtils.getIntProperty(\"kafka.zk.limit.size\");\n\t/** Serializer Zookeeper client pool. */\n\tprivate static Map<String, Vector<ZkClient>> zkCliPoolsSerializer = new HashMap<>();\n\n\tprivate static Map<String, String> clusterAliass = new HashMap<>();\n\n\t/** Init ZkClient pool numbers. */\n\tstatic {\n\t\tfor (String clusterAlias : SystemConfigUtils.getPropertyArray(\"kafka.eagle.zk.cluster.alias\", \",\")) {\n\t\t\tclusterAliass.put(clusterAlias, SystemConfigUtils.getProperty(clusterAlias + \".zk.list\"));\n\t\t}\n\t\tfor (Entry<String, String> entry : clusterAliass.entrySet()) {\n\t\t\tVector<ZkClient> zkCliPool = new Vector<ZkClient>(zkCliPoolSize);\n\t\t\tVector<ZkClient> zkCliPoolSerializer = new Vector<ZkClient>(zkCliPoolSize);\n\t\t\tZkClient zkc = null;\n\t\t\tZkClient zkSerializer = null;\n\t\t\tfor (int i = 0; i < zkCliPoolSize; i++) {\n\t\t\t\ttry {\n\t\t\t\t\tzkc = new ZkClient(entry.getValue());\n\t\t\t\t\tzkCliPool.add(zkc);\n\n\t\t\t\t\tzkSerializer = new ZkClient(entry.getValue(), Integer.MAX_VALUE, 100000, ZKStringSerializer$.MODULE$);\n\t\t\t\t\tzkCliPoolSerializer.add(zkSerializer);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tLOG.error(ex.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t\tzkCliPools.put(entry.getKey(), zkCliPool);\n\t\t\tzkCliPoolsSerializer.put(entry.getKey(), zkCliPoolSerializer);\n\t\t}\n\n\t}\n\n\t/** Single model get ZkClient object. */\n\tpublic synchronized static ZKPoolUtils getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new ZKPoolUtils();\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/** Reback pool one of ZkClient object. */\n\tpublic synchronized ZkClient getZkClient(String clusterAlias) {\n\t\tVector<ZkClient> zkCliPool = zkCliPools.get(clusterAlias);\n\t\tZkClient zkc = null;\n\t\ttry {\n\t\t\tif (zkCliPool.size() > 0) {\n\t\t\t\tzkc = zkCliPool.get(0);\n\t\t\t\tzkCliPool.remove(0);\n\t\t\t\tString osName = System.getProperties().getProperty(\"os.name\");\n\t\t\t\tif (osName.contains(\"Linux\")) {\n\t\t\t\t\tLOG.debug(\"Get pool,and available size [\" + zkCliPool.size() + \"]\");\n\t\t\t\t} else {\n\t\t\t\t\tLOG.info(\"Get pool,and available size [\" + zkCliPool.size() + \"]\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (int i = 0; i < zkCliPoolSize; i++) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tzkc = new ZkClient(clusterAliass.get(clusterAlias));\n\t\t\t\t\t\tzkCliPool.add(zkc);\n\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\tLOG.error(ex.getMessage());\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tzkc = zkCliPool.get(0);\n\t\t\t\tzkCliPool.remove(0);\n\t\t\t\tString osName = System.getProperties().getProperty(\"os.name\");\n\t\t\t\tif (osName.contains(\"Linux\")) {\n\t\t\t\t\tLOG.debug(\"Get pool,and available size [\" + zkCliPool.size() + \"]\");\n\t\t\t\t} else {\n\t\t\t\t\tLOG.warn(\"Get pool,and available size [\" + zkCliPool.size() + \"]\");\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tLOG.error(\"ZK init has error,msg is \" + e.getMessage());\n\t\t}\n\t\treturn zkc;\n\t}\n\n\t/** Get zk client by serializer. */\n\tpublic synchronized ZkClient getZkClientSerializer(String clusterAlias) {\n\t\tVector<ZkClient> zkCliPoolSerializer = zkCliPoolsSerializer.get(clusterAlias);\n\t\tZkClient zkSerializer = null;\n\t\tif (zkCliPoolSerializer.size() > 0) {\n\t\t\tZkClient zkc = zkCliPoolSerializer.get(0);\n\t\t\tzkCliPoolSerializer.remove(0);\n\t\t\tString osName = System.getProperties().getProperty(\"os.name\");\n\t\t\tif (osName.contains(\"Linux\")) {\n\t\t\t\tLOG.debug(\"Get poolZKSerializer,and available size [\" + zkCliPoolSerializer.size() + \"]\");\n\t\t\t} else {\n\t\t\t\tLOG.info(\"Get poolZKSerializer,and available size [\" + zkCliPoolSerializer.size() + \"]\");\n\t\t\t}\n\t\t\treturn zkc;\n\t\t} else {\n\t\t\tfor (int i = 0; i < zkCliPoolSize; i++) {\n\t\t\t\ttry {\n\t\t\t\t\tzkSerializer = new ZkClient(clusterAliass.get(clusterAlias), Integer.MAX_VALUE, 100000, ZKStringSerializer$.MODULE$);\n\t\t\t\t\tzkCliPoolSerializer.add(zkSerializer);\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.error(e.getMessage());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tZkClient zkc = zkCliPoolSerializer.get(0);\n\t\t\tzkCliPoolSerializer.remove(0);\n\t\t\tString osName = System.getProperties().getProperty(\"os.name\");\n\t\t\tif (osName.contains(\"Linux\")) {\n\t\t\t\tLOG.debug(\"get poolZKSerializer,and available size [\" + zkCliPoolSerializer.size() + \"]\");\n\t\t\t} else {\n\t\t\t\tLOG.warn(\"get poolZKSerializer,and available size [\" + zkCliPoolSerializer.size() + \"]\");\n\t\t\t}\n\t\t\treturn zkc;\n\t\t}\n\t}\n\n\t/** Release ZkClient object. */\n\tpublic synchronized void release(String clusterAlias, ZkClient zkc) {\n\t\tVector<ZkClient> zkCliPool = zkCliPools.get(clusterAlias);\n\t\tif (zkCliPool.size() < zkCliPoolSize) {\n\t\t\tzkCliPool.add(zkc);\n\t\t}\n\t\tString osName = System.getProperties().getProperty(\"os.name\");\n\t\tif (osName.contains(\"Linux\")) {\n\t\t\tLOG.debug(\"Release pool,and available size [\" + zkCliPool.size() + \"]\");\n\t\t} else {\n\t\t\tLOG.info(\"Release pool,and available size [\" + zkCliPool.size() + \"]\");\n\t\t}\n\t}\n\n\t/** Release ZkClient Serializer object. */\n\tpublic synchronized void releaseZKSerializer(String clusterAlias, ZkClient zkc) {\n\t\tVector<ZkClient> zkCliPoolSerializer = zkCliPoolsSerializer.get(clusterAlias);\n\t\tif (zkCliPoolSerializer.size() < zkCliPoolSize) {\n\t\t\tzkCliPoolSerializer.add(zkc);\n\t\t}\n\t\tString osName = System.getProperties().getProperty(\"os.name\");\n\t\tif (osName.contains(\"Linux\")) {\n\t\t\tLOG.debug(\"Release poolZKSerializer,and available size [\" + zkCliPoolSerializer.size() + \"]\");\n\t\t} else {\n\t\t\tLOG.info(\"Release poolZKSerializer,and available size [\" + zkCliPoolSerializer.size() + \"]\");\n\t\t}\n\t}\n\n\t/** Construction method. */\n\tprivate ZKPoolUtils() {\n\t}\n\n}" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import org.I0Itec.zkclient.ZkClient; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smartloli.kafka.eagle.common.domain.AlarmDomain; import org.smartloli.kafka.eagle.common.domain.OffsetsLiteDomain; import org.smartloli.kafka.eagle.common.util.CalendarUtils; import org.smartloli.kafka.eagle.common.util.SystemConfigUtils; import org.smartloli.kafka.eagle.common.util.ZKPoolUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import kafka.utils.ZkUtils; import scala.Option; import scala.Tuple2; import scala.collection.JavaConversions; import scala.collection.Seq;
/** Zookeeper ls command. */ public String ls(String clusterAlias, String cmd) { String target = ""; ZkClient zkc = zkPool.getZkClient(clusterAlias); boolean status = ZkUtils.apply(zkc, false).pathExists(cmd); if (status) { target = zkc.getChildren(cmd).toString(); } if (zkc != null) { zkPool.release(clusterAlias, zkc); zkc = null; } return target; } /** * Remove the metadata information in the Ke root directory in zookeeper, * with group and topic as the only sign. * * @param group * Consumer group. * @param topic * Consumer topic. * @param theme * Consumer theme. */ public void remove(String clusterAlias, String group, String topic, String theme) { if (zkc == null) { zkc = zkPool.getZkClient(clusterAlias); } String path = theme + "/" + group + "/" + topic; if (ZkUtils.apply(zkc, false).pathExists(KE_ROOT_PATH + "/" + path)) { ZkUtils.apply(zkc, false).deletePath(KE_ROOT_PATH + "/" + path); } if (zkc != null) { zkPool.release(clusterAlias, zkc); zkc = null; } } /** * Get zookeeper health status. * * @param host * Zookeeper host * @param port * Zookeeper port * @return String. */ public String status(String host, String port) { String target = ""; Socket sock = null; try { String tmp = ""; if (port.contains("/")) { tmp = port.split("/")[0]; } else { tmp = port; } sock = new Socket(host, Integer.parseInt(tmp)); } catch (Exception e) { LOG.error("Socket[" + host + ":" + port + "] connect refused"); return "death"; } BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes()); outstream.flush(); sock.shutdownOutput(); reader = new BufferedReader(new InputStreamReader(sock.getInputStream())); String line; while ((line = reader.readLine()) != null) { if (line.indexOf("Mode: ") != -1) { target = line.replaceAll("Mode: ", "").trim(); } } } catch (Exception ex) { LOG.error("Read ZK buffer has error,msg is " + ex.getMessage()); return "death"; } finally { try { sock.close(); if (reader != null) { reader.close(); } } catch (Exception ex) { LOG.error("Close read has error,msg is " + ex.getMessage()); } } return target; } /** * Update metadata information in ke root path in zookeeper. * * @param data * Update datasets. * @param path * Update datasets path. */ private void update(String clusterAlias, String data, String path) { if (zkc == null) { zkc = zkPool.getZkClient(clusterAlias); } if (!ZkUtils.apply(zkc, false).pathExists(KE_ROOT_PATH + "/" + path)) { ZkUtils.apply(zkc, false).createPersistentPath(KE_ROOT_PATH + "/" + path, "", ZkUtils.apply(zkc, false).DefaultAcls()); } if (ZkUtils.apply(zkc, false).pathExists(KE_ROOT_PATH + "/" + path)) { ZkUtils.apply(zkc, false).updatePersistentPath(KE_ROOT_PATH + "/" + path, data, ZkUtils.apply(zkc, false).DefaultAcls()); } if (zkc != null) { zkPool.release(clusterAlias, zkc); zkc = null; } } /** Get zookeeper cluster information. */ public String zkCluster(String clusterAlias) {
String[] zks = SystemConfigUtils.getPropertyArray(clusterAlias + ".zk.list", ",");
3
zznate/intravert-ug
src/main/java/io/teknek/intravert/service/DefaultRequestProcessor.java
[ "public interface Action {\n void doAction(Operation operation, Response response, RequestContext request, ApplicationContext application);\n}", "public class ActionFactory {\n \n public static final String CREATE_SESSION = \"createsession\";\n public static final String LOAD_SESSION = \"loadsession\";\n public static final String SET_KEYSPACE = \"setkeyspace\";\n public static final String GET_KEYSPACE = \"getkeyspace\";\n public static final String CREATE_FILTER = \"createfilter\";\n public static final String UPSERT = \"upsert\";\n public static final String CREATE_KEYSPACE = \"createkeyspace\";\n public static final String CREATE_COLUMN_FAMILY =\"createcolumnfamily\";\n public static final String SLICE =\"slice\";\n private Map<String,Action> actions;\n \n public ActionFactory(){\n actions = new HashMap<String,Action>();\n actions.put(CREATE_SESSION, new SaveSessionAction());\n actions.put(LOAD_SESSION, new LoadSessionAction());\n actions.put(SET_KEYSPACE, new SetKeyspaceAction()); \n actions.put(GET_KEYSPACE, new GetKeyspaceAction());\n actions.put(CREATE_FILTER, new CreateFilterAction());\n actions.put(UPSERT, new UpsertAction());\n actions.put(CREATE_KEYSPACE, new CreateKeyspaceAction());\n actions.put(CREATE_COLUMN_FAMILY, new CreateColumnFamilyAction());\n actions.put(SLICE, new SliceAction());\n }\n \n public Action findAction(String operation){\n Action a = actions.get(operation);\n if (a == null)\n throw new IllegalArgumentException(\"Do not know what to do with \" + operation);\n return a;\n }\n}", "public class Operation {\n private String type;\n private String id;\n private Map<String,Object> arguments;\n \n public Operation(){\n arguments = new HashMap<String,Object>();\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public Map<String, Object> getArguments() {\n return arguments;\n }\n\n public void setArguments(Map<String, Object> arguments) {\n this.arguments = arguments;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n \n public Operation withId(String id){\n setId(id);\n return this;\n }\n \n public Operation withType(String type){\n setType(type);\n return this;\n }\n \n public Operation withArguments(Map<String,Object> arguments){\n setArguments(arguments);\n return this;\n }\n \n public Map<String,Object> withArgument(String name, Object value){\n arguments.put(name, value);\n return arguments;\n }\n}", "public class Request {\n private List<Operation> operations;\n \n public Request(){\n operations = new ArrayList<Operation>();\n }\n\n public List<Operation> getOperations() {\n return operations;\n }\n\n public void setOperations(List<Operation> operations) {\n this.operations = operations;\n }\n \n}", "public class Response {\n private String exceptionMessage;\n private String exceptionId;\n private LinkedHashMap<String,Object> results;\n private LinkedHashMap<String,Object> metaData;\n \n public Response(){\n results = new LinkedHashMap<String,Object>();\n metaData = new LinkedHashMap<String,Object>();\n }\n\n public String getExceptionMessage() {\n return exceptionMessage;\n }\n\n public void setExceptionMessage(String exceptionMessage) {\n this.exceptionMessage = exceptionMessage;\n }\n\n public String getExceptionId() {\n return exceptionId;\n }\n\n public void setExceptionId(String exceptionId) {\n this.exceptionId = exceptionId;\n }\n\n public Map<String, Object> getResults() {\n return results;\n }\n\n public void setResults(LinkedHashMap<String, Object> results) {\n this.results = results;\n }\n\n public Map<String, Object> getMetaData() {\n return metaData;\n }\n\n public void setMetaData(LinkedHashMap<String, Object> metaData) {\n this.metaData = metaData;\n }\n \n}" ]
import io.teknek.intravert.action.Action; import io.teknek.intravert.action.ActionFactory; import io.teknek.intravert.model.Operation; import io.teknek.intravert.model.Request; import io.teknek.intravert.model.Response;
package io.teknek.intravert.service; public class DefaultRequestProcessor implements RequestProcessor { private ActionFactory actionFatory = new ActionFactory(); @Override public void process(Request request, Response response, RequestContext requestContext, ApplicationContext application) { for (int i = 0; i < request.getOperations().size(); i++) { Operation operation = null; try { operation = request.getOperations().get(i);
Action action = actionFatory.findAction(operation.getType());
0
caseydavenport/biermacht
src/com/biermacht/brews/database/DatabaseAPI.java
[ "public class ItemNotFoundException extends Exception {\n public ItemNotFoundException() {\n }\n\n //Constructor that accepts a message\n public ItemNotFoundException(String message) {\n super(message);\n }\n}", "public abstract class Ingredient implements Parcelable {\n\n // Beer XML 1.0 Required Fields (To be inherited) =================\n // ================================================================\n private String name; // Ingredient name\n private int version; // bXML Version being used\n public double amount; // Amount in beerXML standard units\n public int time; // Time ingredient is used - units vary based on use\n\n // Custom Fields ==================================================\n // ================================================================\n private long id; // Lookup ID for database\n private long ownerId; // ID of recipe that contains this\n private double inventory; // Amount in inventory (standard units)\n private long databaseId; // Which virtual database to store this in\n\n // Static values =================================================\n // ===============================================================\n public static final String FERMENTABLE = \"Fermentable\";\n public static final String HOP = \"Hop\";\n public static final String YEAST = \"Yeast\";\n public static final String MISC = \"Misc\";\n public static final String WATER = \"Water\";\n public static final String PLACEHOLDER = \"Placeholder\";\n\n // Ingredient uses\n public static final String USE_BOIL = \"Boil\";\n public static final String USE_MASH = \"Mash\";\n public static final String USE_PRIMARY = \"Primary\";\n public static final String USE_SECONDARY = \"Secondary\";\n public static final String USE_BOTTLING = \"Bottling\";\n public static final String USE_DRY_HOP = \"Dry Hop\";\n public static final String USE_FIRST_WORT = \"First Wort\";\n public static final String USE_AROMA = \"Aroma\";\n public static final String USE_OTHER = \"other\";\n\n // Public constructors\n public Ingredient(String name) {\n this.name = name;\n this.id = Constants.INVALID_ID;\n this.ownerId = Constants.INVALID_ID;\n this.databaseId = Constants.DATABASE_USER_RECIPES;\n this.amount = 0;\n this.time = 0;\n this.inventory = 0;\n }\n\n public Ingredient(Parcel p) {\n name = p.readString();\n version = p.readInt();\n amount = p.readDouble();\n id = p.readLong();\n ownerId = p.readLong();\n inventory = p.readDouble();\n databaseId = p.readLong();\n time = p.readInt();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Should be called by all sub-classes\n p.writeString(name);\n p.writeInt(version);\n p.writeDouble(amount);\n p.writeLong(id);\n p.writeLong(ownerId);\n p.writeDouble(inventory);\n p.writeLong(databaseId);\n p.writeInt(time);\n }\n\n public static final Parcelable.Creator<Ingredient> CREATOR =\n new Parcelable.Creator<Ingredient>() {\n @Override\n public Ingredient createFromParcel(Parcel p) {\n Ingredient i = null;\n try {\n i = new Hop(p);\n } catch (Exception e) {\n Log.d(\"Ingredient\", \"Not a hop\");\n }\n try {\n i = new Misc(p);\n } catch (Exception e) {\n Log.d(\"Ingredient\", \"Not a Misc\");\n }\n try {\n i = new Fermentable(p);\n } catch (Exception e) {\n Log.d(\"Ingredient\", \"Not a Fermentable\");\n }\n try {\n i = new Yeast(p);\n } catch (Exception e) {\n Log.d(\"Ingredient\", \"Not a Yeast\");\n }\n\n return i;\n }\n\n @Override\n public Ingredient[] newArray(int size) {\n return new Ingredient[]{};\n }\n };\n\n // Abstract methods of Ingredient\n public abstract String getType();\n\n public abstract String getShortDescription();\n\n public abstract void setShortDescription(String description);\n\n // Get beerXML 1.0 Units\n public abstract String getBeerXmlStandardUnits();\n\n // Get display units\n public abstract String getDisplayUnits();\n\n // Set display units\n public abstract void setDisplayUnits(String s);\n\n // Returns display amount\n public abstract double getDisplayAmount();\n\n // Takes display amount\n public abstract void setDisplayAmount(double amt);\n\n // Returns amount in units specified by beerXML 1.0\n public abstract double getBeerXmlStandardAmount();\n\n // Takes amount in beerXML 1.0 units\n public abstract void setBeerXmlStandardAmount(double amt);\n\n public abstract int hashCode();\n\n public abstract boolean equals(Object o);\n\n public abstract int compareTo(Ingredient other);\n\n public abstract void setTime(int time);\n\n public abstract int getTime();\n\n @Override\n public String toString() {\n return name;\n }\n\n public String getUse() {\n return Ingredient.USE_OTHER;\n }\n\n public long getDatabaseId() {\n return this.databaseId;\n }\n\n public void setDatabaseId(long i) {\n this.databaseId = i;\n }\n\n public double getBeerXmlStandardInventory() {\n return this.inventory;\n }\n\n public void setBeerXmlStandardInventory(double d) {\n this.inventory = d;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public long getOwnerId() {\n return ownerId;\n }\n\n public void setOwnerId(long ownerId) {\n this.ownerId = ownerId;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public int getVersion() {\n return version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n}", "public class BeerStyle implements Parcelable {\n\n // Categories based on beerXMl standard\n private String name;\n private String category;\n private Integer version;\n private String categoryNumber;\n private String styleLetter;\n private String styleGuide;\n private String type;\n private String notes;\n private String profile;\n private String ingredients;\n private String examples;\n\n // Reccomended values\n private double MinOg;\n private double MaxOg;\n private double MinFg;\n private double MaxFg;\n private double MinIbu;\n private double MaxIbu;\n private double minColor;\n private double maxColor;\n private double minAbv;\n private double maxAbv;\n\n // More\n private long ownerId;\n\n // Defines\n public static String TYPE_ALE = \"Ale\";\n public static String TYPE_LAGER = \"Lager\";\n public static String TYPE_MEAD = \"Mead\";\n public static String TYPE_WHEAT = \"Wheat\";\n public static String TYPE_MIXED = \"Mixed\";\n public static String TYPE_CIDER = \"Cider\";\n\n public BeerStyle(String name) {\n setName(name);\n setType(\"\");\n setCategory(\"\");\n setStyleLetter(\"\");\n setNotes(\"\");\n setExamples(\"\");\n setIngredients(\"\");\n setProfile(\"\");\n setStyleGuide(\"\");\n setCategoryNumber(\"\");\n setVersion(1);\n setOwnerId(- 1);\n\n this.MinOg = 1;\n this.MaxOg = 2;\n this.MinFg = 1;\n this.MaxFg = 2;\n this.MinIbu = 0;\n this.MaxIbu = 200;\n this.minColor = 0;\n this.maxColor = 100;\n this.minAbv = 0;\n this.maxAbv = 100;\n }\n\n public BeerStyle(Parcel p) {\n // Categories based on beerXMl standard\n name = p.readString();\n category = p.readString();\n version = p.readInt();\n categoryNumber = p.readString();\n styleLetter = p.readString();\n styleGuide = p.readString();\n type = p.readString();\n notes = p.readString();\n profile = p.readString();\n ingredients = p.readString();\n examples = p.readString();\n MinOg = p.readDouble();\n MaxOg = p.readDouble();\n MinFg = p.readDouble();\n MaxFg = p.readDouble();\n MinIbu = p.readDouble();\n MaxIbu = p.readDouble();\n minColor = p.readDouble();\n maxColor = p.readDouble();\n minAbv = p.readDouble();\n maxAbv = p.readDouble();\n ownerId = p.readLong();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Categories based on beerXMl standard\n p.writeString(name);\n p.writeString(category);\n p.writeInt(version);\n p.writeString(categoryNumber);\n p.writeString(styleLetter);\n p.writeString(styleGuide);\n p.writeString(type);\n p.writeString(notes);\n p.writeString(profile);\n p.writeString(ingredients);\n p.writeString(examples);\n p.writeDouble(MinOg);\n p.writeDouble(MaxOg);\n p.writeDouble(MinFg);\n p.writeDouble(MaxFg);\n p.writeDouble(MinIbu);\n p.writeDouble(MaxIbu);\n p.writeDouble(minColor);\n p.writeDouble(maxColor);\n p.writeDouble(minAbv);\n p.writeDouble(maxAbv);\n p.writeLong(ownerId);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<BeerStyle> CREATOR =\n new Parcelable.Creator<BeerStyle>() {\n @Override\n public BeerStyle createFromParcel(Parcel p) {\n return new BeerStyle(p);\n }\n\n @Override\n public BeerStyle[] newArray(int size) {\n return new BeerStyle[]{};\n }\n };\n\n @Override\n public boolean equals(Object o) {\n // Fist make sure its a BeerStyle\n if (! (o instanceof BeerStyle)) {\n return false;\n }\n\n // Based only off the name\n if (this.toString().equals(o.toString())) {\n return true;\n }\n else {\n return false;\n }\n\n }\n\n public String toString() {\n return name;\n }\n\n public void setOwnerId(long i) {\n this.ownerId = i;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setMinCarb(double d) {\n // TODO\n }\n\n public void setMaxCarb(double d) {\n // TODO\n }\n\n public void setName(String s) {\n this.name = s;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setType(String s) {\n this.type = s;\n }\n\n public void setCategory(String s) {\n this.category = s;\n }\n\n public void setStyleLetter(String s) {\n this.styleLetter = s;\n }\n\n public void setNotes(String s) {\n this.notes = s;\n }\n\n public void setExamples(String s) {\n this.examples = s;\n }\n\n public void setProfile(String s) {\n this.profile = s;\n }\n\n public void setCategoryNumber(String s) {\n this.categoryNumber = s;\n }\n\n public void setStyleGuide(String s) {\n this.styleGuide = s;\n }\n\n public void setIngredients(String s) {\n this.ingredients = s;\n }\n\n public void setVersion(int i) {\n this.version = i;\n }\n\n // Methods for getting individual mins and maxes\n public double getMinOg() {\n return MinOg;\n }\n\n public void setMinOg(double minGrav) {\n this.MinOg = minGrav;\n }\n\n public double getMaxOg() {\n return MaxOg;\n }\n\n public void setMaxOg(double maxGrav) {\n this.MaxOg = maxGrav;\n }\n\n public double getMinIbu() {\n return MinIbu;\n }\n\n public void setMinIbu(double MinIbu) {\n this.MinIbu = MinIbu;\n }\n\n public double getMaxIbu() {\n return MaxIbu;\n }\n\n public void setMaxIbu(double MaxIbu) {\n this.MaxIbu = MaxIbu;\n }\n\n public double getMinColor() {\n return minColor;\n }\n\n public void setMinColor(double minColor) {\n this.minColor = minColor;\n }\n\n public double getMaxColor() {\n return maxColor;\n }\n\n public void setMaxColor(double maxColor) {\n this.maxColor = maxColor;\n }\n\n public double getAverageColor() {\n return (this.minColor + this.maxColor) / 2;\n }\n\n public double getMinAbv() {\n return minAbv;\n }\n\n public void setMinAbv(double minAbv) {\n this.minAbv = minAbv;\n }\n\n public double getMaxAbv() {\n return maxAbv;\n }\n\n public void setMaxAbv(double maxAbv) {\n this.maxAbv = maxAbv;\n }\n\n public double getMaxFg() {\n return MaxFg;\n }\n\n public void setMaxFg(double MaxFg) {\n this.MaxFg = MaxFg;\n }\n\n public double getMinFg() {\n return MinFg;\n }\n\n public void setMinFg(double MinFg) {\n this.MinFg = MinFg;\n }\n\n public String getCategory() {\n return this.category;\n }\n\n public String getCatNum() {\n return this.categoryNumber;\n }\n\n public String getStyleLetter() {\n return this.styleLetter;\n }\n\n public String getStyleGuide() {\n return this.styleGuide;\n }\n\n public String getType() {\n return this.type;\n }\n\n public double getMinCarb() {\n return 0; // TODO\n }\n\n public double getMaxCarb() {\n return 0; // TODO\n }\n\n public String getNotes() {\n // Return the string without any newlines or tabs.\n return this.notes.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getProfile() {\n return this.profile.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getIngredients() {\n return this.ingredients.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getExamples() {\n return this.examples.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n}", "public class MashProfile implements Parcelable {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // profile name\n private Integer version; // XML Version -- 1\n private double grainTemp; // Grain temp in C\n private ArrayList<MashStep> mashSteps; // List of steps\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double tunTemp; // TUN Temperature in C\n private double spargeTemp; // Sparge Temp in C\n private double pH; // pH of water\n private double tunWeight; // Weight of TUN in kG\n private double tunSpecificHeat; // Specific heat of TUN\n private String notes; // Notes\n private Boolean equipAdj; // Adjust for heating of equip?\n\n // Custom Fields ==================================================\n // ================================================================\n private long id; // id for use in database\n private long ownerId; // id for parent recipe\n private String mashType; // one of infusion, decoction, temperature\n private String spargeType; // one of batch, fly\n private Recipe recipe; // Recipe which owns this mash.\n\n // Static values =================================================\n // ===============================================================\n public static String MASH_TYPE_INFUSION = \"Infusion\";\n public static String MASH_TYPE_DECOCTION = \"Decoction\";\n public static String MASH_TYPE_TEMPERATURE = \"Temperature\";\n public static String MASH_TYPE_BIAB = \"BIAB\";\n public static String SPARGE_TYPE_BATCH = \"Batch\";\n public static String SPARGE_TYPE_FLY = \"Fly\";\n public static String SPARGE_TYPE_BIAB = \"BIAB\";\n\n // Basic Constructor\n public MashProfile(Recipe r) {\n this.setName(\"New Mash Profile\");\n this.setVersion(1);\n this.setBeerXmlStandardGrainTemp(20);\n this.mashSteps = new ArrayList<MashStep>();\n this.setBeerXmlStandardTunTemp(20);\n this.setBeerXmlStandardSpargeTemp(75.5555);\n this.setpH(7);\n this.setBeerXmlStandardTunWeight(0);\n this.setBeerXmlStandardTunSpecHeat(0);\n this.setEquipmentAdjust(false);\n this.setNotes(\"\");\n this.id = - 1;\n this.ownerId = - 1;\n this.mashType = MASH_TYPE_INFUSION;\n this.spargeType = SPARGE_TYPE_BATCH;\n this.recipe = r;\n }\n\n public MashProfile() {\n this(new Recipe());\n }\n\n public MashProfile(Parcel p) {\n name = p.readString();\n version = p.readInt();\n grainTemp = p.readDouble();\n\n mashSteps = new ArrayList<MashStep>();\n p.readTypedList(mashSteps, MashStep.CREATOR);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n tunTemp = p.readDouble();\n spargeTemp = p.readDouble();\n pH = p.readDouble();\n tunWeight = p.readDouble();\n tunSpecificHeat = p.readDouble();\n notes = p.readString();\n equipAdj = (p.readInt() > 0 ? true : false);\n\n // Custom Fields ==================================================\n // ================================================================\n id = p.readLong();\n ownerId = p.readLong();\n mashType = p.readString();\n spargeType = p.readString();\n // Don't read recipe because it recurses.\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n p.writeString(name); // profile name\n p.writeInt(version); // XML Version -- 1\n p.writeDouble(grainTemp); // Grain temp in C\n p.writeTypedList(mashSteps); // List of steps\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(tunTemp); // TUN Temperature in C\n p.writeDouble(spargeTemp); // Sparge Temp in C\n p.writeDouble(pH); // pH of water\n p.writeDouble(tunWeight); // Weight of TUN in kG\n p.writeDouble(tunSpecificHeat); // Specific heat of TUN\n p.writeString(notes); // Notes\n p.writeInt(equipAdj ? 1 : 0); // Adjust for heating of equip?\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(id); // id for use in database\n p.writeLong(ownerId); // id for parent recipe\n p.writeString(mashType);\n p.writeString(spargeType);\n // Don't write recipe because it recurses.\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<MashProfile> CREATOR =\n new Parcelable.Creator<MashProfile>() {\n @Override\n public MashProfile createFromParcel(Parcel p) {\n return new MashProfile(p);\n }\n\n @Override\n public MashProfile[] newArray(int size) {\n return new MashProfile[size];\n }\n };\n\n @Override\n public String toString() {\n return this.name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (! (o instanceof MashProfile)) {\n return false;\n }\n\n MashProfile other = (MashProfile) o;\n if (this.hashCode() != other.hashCode()) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int hc = this.name.hashCode();\n for (MashStep m : this.mashSteps) {\n hc ^= m.hashCode();\n }\n return hc;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setVersion(Integer v) {\n this.version = v;\n }\n\n public Integer getVersion() {\n return this.version;\n }\n\n public void setBeerXmlStandardGrainTemp(double temp) {\n this.grainTemp = temp;\n }\n\n public void setDisplayGrainTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.grainTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.grainTemp = temp;\n }\n }\n\n public double getBeerXmlStandardGrainTemp() {\n return this.grainTemp;\n }\n\n public double getDisplayGrainTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.grainTemp);\n }\n else {\n return this.grainTemp;\n }\n }\n\n public String getMashType() {\n return this.mashType;\n }\n\n public String getSpargeType() {\n return this.spargeType;\n }\n\n public void setMashType(String s) {\n this.mashType = s;\n }\n\n public void setSpargeType(String s) {\n Log.d(\"MashProfile\", \"Sparge type set: \" + s);\n this.spargeType = s;\n }\n\n public void setBeerXmlStandardTunTemp(double temp) {\n this.tunTemp = temp;\n }\n\n public void setDisplayTunTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.tunTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.tunTemp = temp;\n }\n }\n\n public double getBeerXmlStandardTunTemp() {\n return this.tunTemp;\n }\n\n public double getDisplayTunTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.tunTemp);\n }\n else {\n return this.tunTemp;\n }\n }\n\n public void setBeerXmlStandardSpargeTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.spargeTemp = temp;\n }\n }\n\n public void setDisplaySpargeTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.spargeTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.spargeTemp = temp;\n }\n }\n\n public double getDisplaySpargeTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.spargeTemp);\n }\n else {\n return this.spargeTemp;\n }\n }\n\n public double getBeerXmlStandardSpargeTemp() {\n return this.spargeTemp;\n }\n\n public void setpH(double pH) {\n this.pH = pH;\n }\n\n public double getpH() {\n return this.pH;\n }\n\n public void setBeerXmlStandardTunWeight(double weight) {\n this.tunWeight = weight;\n }\n\n public void setDisplayTunWeight(double weight) {\n if (Units.getWeightUnits().equals(Units.POUNDS)) {\n this.tunWeight = Units.poundsToKilos(weight);\n }\n else {\n this.tunWeight = weight;\n }\n }\n\n public double getBeerXmlStandardTunWeight() {\n return this.tunWeight;\n }\n\n public double getDisplayTunWeight() {\n if (Units.getWeightUnits().equals(Units.POUNDS)) {\n return Units.kilosToPounds(this.tunWeight);\n }\n else {\n return this.tunWeight;\n }\n }\n\n public void setBeerXmlStandardTunSpecHeat(double heat) {\n this.tunSpecificHeat = heat;\n }\n\n public double getBeerXmlStandardTunSpecHeat() {\n // Cal / (g * C)\n return this.tunSpecificHeat;\n }\n\n public void setEquipmentAdjust(boolean adj) {\n this.equipAdj = adj;\n }\n\n public Boolean getEquipmentAdjust() {\n return this.equipAdj;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public long getId() {\n return this.id;\n }\n\n public void setOwnerId(long id) {\n this.ownerId = id;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setNotes(String s) {\n this.notes = s;\n }\n\n public String getNotes() {\n return this.notes;\n }\n\n public int getNumberOfSteps() {\n return this.mashSteps.size();\n }\n\n public void setRecipe(Recipe r) {\n this.recipe = r;\n for (MashStep m : this.mashSteps) {\n m.setRecipe(this.recipe);\n }\n }\n\n public ArrayList<MashStep> getMashStepList() {\n return this.mashSteps;\n }\n\n public void clearMashSteps() {\n this.mashSteps = new ArrayList<MashStep>();\n }\n\n /**\n * Sets mash step list to given list. Assumes list is in the desired order and overrides orders\n * if reorder set to true\n *\n * @param list\n */\n public void setMashStepList(ArrayList<MashStep> list) {\n this.mashSteps = list;\n for (MashStep s : this.mashSteps) {\n s.setRecipe(this.recipe);\n }\n Collections.sort(this.mashSteps, new FromDatabaseMashStepComparator());\n }\n\n /**\n * Removes the given step, returns true if success\n *\n * @param step\n * @return\n */\n public boolean removeMashStep(MashStep step) {\n return this.mashSteps.remove(step);\n }\n\n public MashStep removeMashStep(int order) {\n return this.mashSteps.remove(order);\n }\n\n public void addMashStep(MashStep step) {\n step.setRecipe(this.recipe);\n this.mashSteps.add(step);\n }\n\n public void addMashStep(int order, MashStep step) {\n step.setRecipe(this.recipe);\n this.mashSteps.add(order, step);\n }\n\n public void save(Context c, long database) {\n Log.d(\"MashProfile\", \"Saving \" + name + \" to database \" + database);\n if (this.id < 0) {\n // We haven't yet saved this. Add it to the database.\n new DatabaseAPI(c).addMashProfile(database, this, this.getOwnerId());\n }\n else {\n // Already exists. Update it.\n new DatabaseAPI(c).updateMashProfile(this, this.getOwnerId(), database);\n }\n }\n\n public void delete(Context c, long database) {\n new DatabaseAPI(c).deleteMashProfileFromDatabase(this, database);\n }\n}", "public class MashStep implements Parcelable {\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // profile name\n private int version; // XML Version -- 1\n private String type; // infusion, temp, decoc\n private double infuseAmount; // Amount\n private double stepTemp; // Temp for this step in C\n private double stepTime; // Time for this step\n\n // ================================================================\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double rampTime; // Time to ramp temp\n private double endTemp; // Final temp for long steps\n private String description; // Description of step\n private double waterToGrainRatio; // Water to grain ratio (L/kg)\n private double decoctAmount; // Amount of mash to decoct. (L)\n\n // ================================================================\n // Custom Fields ==================================================\n // ================================================================\n private long ownerId; // id for parent mash profile\n private long id; // id for use in database\n public int order; // Order in step list\n private double infuseTemp; // Temperature of infuse water\n private boolean calcInfuseTemp; // Auto calculate the infusion temperature if true.\n private boolean calcInfuseAmt; // Auto calculate the infusion amount if true.\n private boolean calcDecoctAmt; // Auto calculate the amount to decoct if true.\n private Recipe recipe; // Reference to the recipe that owns this mash.\n\n // ================================================================\n // Static values ==================================================\n // ================================================================\n public static String INFUSION = \"Infusion\";\n public static String TEMPERATURE = \"Temperature\";\n public static String DECOCTION = \"Decoction\";\n\n // Basic Constructor\n public MashStep(Recipe r) {\n this.setName(\"Mash Step (\" + (r.getMashProfile().getMashStepList().size() + 1) + \")\");\n this.setVersion(1);\n this.setType(MashStep.INFUSION);\n this.setDisplayInfuseAmount(0);\n this.setBeerXmlStandardStepTemp(65.555556);\n this.setStepTime(60);\n this.setRampTime(0);\n this.setBeerXmlStandardEndTemp(0.0);\n this.setDescription(\"\");\n this.setBeerXmlStandardWaterToGrainRatio(2.60793889);\n this.infuseTemp = 0.0;\n this.id = - 1;\n this.ownerId = - 1;\n this.order = 1;\n this.decoctAmount = 0;\n this.calcInfuseAmt = true;\n this.calcInfuseTemp = true;\n this.calcDecoctAmt = true;\n this.recipe = r;\n }\n\n // Only use this when we don't have a mash profile to\n // use!\n public MashStep() {\n this(new Recipe());\n }\n\n public MashStep(Parcel p) {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n name = p.readString();\n version = p.readInt();\n type = p.readString();\n infuseAmount = p.readDouble();\n stepTemp = p.readDouble();\n stepTime = p.readDouble();\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n rampTime = p.readDouble();\n endTemp = p.readDouble();\n description = p.readString();\n waterToGrainRatio = p.readDouble();\n decoctAmount = p.readDouble();\n\n // Custom Fields ==================================================\n // ================================================================\n ownerId = p.readLong();\n id = p.readLong();\n order = p.readInt();\n infuseTemp = p.readDouble();\n calcInfuseTemp = p.readInt() == 0 ? false : true;\n calcInfuseAmt = p.readInt() == 0 ? false : true;\n calcDecoctAmt = p.readInt() == 0 ? false : true;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n p.writeString(name); // profile name\n p.writeInt(version); // XML Version -- 1\n p.writeString(type); // infusion, temp, decoc\n p.writeDouble(infuseAmount); // Amount\n p.writeDouble(stepTemp); // Temp for this step in C\n p.writeDouble(stepTime); // Time for this step\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(rampTime); // Time to ramp temp\n p.writeDouble(endTemp); // Final temp for long steps\n p.writeString(description); // Description of step\n p.writeDouble(waterToGrainRatio); // Water to grain ratio (L/kg)\n p.writeDouble(decoctAmount); // Amount of water to decoct.\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(ownerId); // id for parent mash profile\n p.writeLong(id); // id for use in database\n p.writeInt(order); // Order in step list\n p.writeDouble(infuseTemp);\n p.writeInt(calcInfuseTemp ? 1 : 0);\n p.writeInt(calcInfuseAmt ? 1 : 0);\n p.writeInt(calcDecoctAmt ? 1 : 0);\n }\n\n public static final Parcelable.Creator<MashStep> CREATOR =\n new Parcelable.Creator<MashStep>() {\n @Override\n public MashStep createFromParcel(Parcel p) {\n return new MashStep(p);\n }\n\n @Override\n public MashStep[] newArray(int size) {\n return new MashStep[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public boolean equals(Object o) {\n // Non-MashStep objects cannot equal a MashStep.\n if (! (o instanceof MashStep)) {\n return false;\n }\n\n // Comparing to a MashStep - cast the given Object.\n MashStep other = (MashStep) o;\n\n // Both are MashStep objects - compare important fields.\n if (! this.getName().equals(other.getName())) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getName() + \" != \" + other.getName());\n return false;\n }\n else if (this.getStepTime() != other.getStepTime()) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getStepTime() + \" != \" + other.getStepTime());\n return false;\n }\n else if (this.getBeerXmlStandardStepTemp() != other.getBeerXmlStandardStepTemp()) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getBeerXmlStandardStepTemp() + \" != \" + other.getBeerXmlStandardStepTemp());\n return false;\n }\n else if (! this.getType().equals(other.getType())) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getType() + \" != \" + other.getType());\n return false;\n }\n\n // All index fields match - these objects are equal.\n return true;\n }\n\n @Override\n public String toString() {\n return this.name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public int getVersion() {\n return this.version;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getType() {\n return this.type;\n }\n\n public double getDisplayDecoctAmount() {\n // If we are autocalculating.\n if (this.calcDecoctAmt) {\n return this.calculateDecoctAmount();\n }\n\n // We're not auto-calculating.\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.decoctAmount);\n }\n else {\n return this.decoctAmount;\n }\n }\n\n public void setDisplayDecoctAmount(double amt) {\n Log.d(\"MashStep\", \"Setting display decoction amount: \" + amt);\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.decoctAmount = Units.gallonsToLiters(amt);\n }\n else {\n this.decoctAmount = amt;\n }\n }\n\n public void setBeerXmlDecoctAmount(double amt) {\n this.decoctAmount = amt;\n }\n\n public double getBeerXmlDecoctAmount() {\n return this.decoctAmount;\n }\n\n public void setDisplayInfuseAmount(double amt) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.infuseAmount = Units.gallonsToLiters(amt);\n }\n else {\n this.infuseAmount = amt;\n }\n }\n\n public double getDisplayAmount() {\n if (this.getType().equals(DECOCTION)) {\n Log.d(\"MashStep\", \"Returning display decoction amount: \" + this.getDisplayDecoctAmount());\n return this.getDisplayDecoctAmount();\n }\n else if (this.getType().equals(INFUSION)) {\n Log.d(\"MashStep\", \"Returning display infusion amount: \" + this.getDisplayInfuseAmount());\n return this.getDisplayInfuseAmount();\n }\n else if (this.getType().equals(TEMPERATURE)) {\n Log.d(\"MashStep\", \"Temperature mash, returning 0 for display amount\");\n return 0;\n }\n Log.d(\"MashStep\", \"Invalid type: \" + this.getType() + \". Returning -1 for display amount\");\n return - 1;\n }\n\n public double getDisplayInfuseAmount() {\n // No infuse amount for decoction steps. Ever.\n if (this.getType().equals(MashStep.DECOCTION)) {\n return 0;\n }\n\n // If we are autocalculating.\n if (this.calcInfuseAmt) {\n return this.calculateInfuseAmount();\n }\n\n // If we're not auto-calculating.\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.infuseAmount);\n }\n else {\n return this.infuseAmount;\n }\n }\n\n /* Calculates the infusion amount based on\n /* water to grain ratio, water temp, water to add,\n /* and the step temperature.\n /* Also sets this.infuseAmount to the correct value. */\n public double calculateInfuseAmount() {\n // We perform different calculations if this is the initial infusion.\n double amt = - 1;\n if (this.firstInList() &&\n ! this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n // Initial infusion for a non-biab mash. Water is constant * amount of grain.\n amt = this.getBeerXmlStandardWaterToGrainRatio() * this.getBeerXmlStandardMashWeight();\n }\n else if (this.firstInList() &&\n this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n // Initial infusion for a BIAB mash.\n // Water is boil volume + grain absorption.\n amt = this.recipe.getBeerXmlStandardBoilSize();\n\n // Estimate ~1 liter per kg absobtion.\n // TODO: Get this from equipment profile.\n amt += this.getBeerXmlStandardMashWeight();\n }\n else {\n // The actual temperature of the water being infused.\n double actualInfuseTemp = calcInfuseTemp ? calculateBXSInfuseTemp() : getBeerXmlStandardInfuseTemp();\n\n // Not initial infusion. Calculate water to add to reach appropriate temp.\n try {\n amt = (this.getBeerXmlStandardStepTemp() - getPreviousStep().getBeerXmlStandardStepTemp());\n } catch (Exception e) {\n e.printStackTrace();\n }\n amt = amt * (.41 * this.getBeerXmlStandardMashWeight() + this.getBXSTotalWaterInMash());\n amt = amt / (actualInfuseTemp - this.getBeerXmlStandardStepTemp());\n }\n\n // Set BXL amount so that database is consistent.\n this.infuseAmount = amt;\n\n // Use appropriate units.\n if (Units.getVolumeUnits().equals(Units.LITERS)) {\n return amt;\n }\n else {\n return Units.litersToGallons(amt);\n }\n }\n\n /* Calculates the decoction amount */\n public double calculateDecoctAmount() {\n Log.d(\"MashStep\", \"Auto-calculating decoct amount\");\n /**\n * F = (TS – TI) / (TB – TI – X)\n *\n * Where f is the fraction, TS is the target step temperature, TI is the initial (current) temperature,\n * TB is the temperature of the boiling mash and X is an equipment dependent parameter (typically 18F or 10C).\n */\n double target = this.getBeerXmlStandardStepTemp();\n double initial = 0;\n try {\n initial = this.getPreviousStep().getBeerXmlStandardStepTemp();\n } catch (Exception e) {\n // Attempted to calculate decoct amount for first step in MashProfile. This isn't\n // allowed (the first step must be an infusion step). Handle this\n // somewhat gracefully, as this can occur temporarily during recipe formulation.\n e.printStackTrace();\n return 0;\n }\n double boiling = 99; // Boiling temperature of mash (C).\n double X = 10; // TODO: Equipment factor - accounts for heat absorbtion of mash tun.\n double grainDensity = .43; // .43kg / 1L\n double waterVolume = getBXSTotalWaterInMash(); // L\n double grainMass = (waterVolume / waterToGrainRatio); // kg\n double grainVolume = grainMass / grainDensity; // L\n double totalVolume = waterVolume + grainVolume; // L\n\n // This calculates the ratio of \"mash to boil\" / \"mash to leave in tun\".\n double fraction = (target - initial) / (boiling - initial - X);\n\n // Convert this ratio to \"Mash to boil\" / \"Total Mash\"\n fraction = (fraction) / (1 + fraction);\n\n // Return the fraction of mash, adjusted for the selected units.\n if (Units.getUnitSystem().equals(Units.METRIC)) {\n return fraction * totalVolume; // Return Liters of mash.\n }\n else {\n return fraction * Units.litersToGallons(totalVolume); // Return Gallons of mash.\n }\n }\n\n /**\n * Calculates the infusion temperature for both initial infusion, and water adds.\n * http://www.howtobrew.com/section3/chapter16-3.html\n */\n public double calculateInfuseTemp() {\n // We perform different calculations if this is the initial infusion.\n double temp = 0;\n if (this.firstInList()) {\n // Initial infusion.\n // TODO: For now, we don't have equipment so we combine tun / grain temp for calculation.\n double tunTemp = .7 * this.recipe.getMashProfile().getBeerXmlStandardGrainTemp() +\n .3 * this.recipe.getMashProfile().getBeerXmlStandardTunTemp();\n temp = (.41) / (this.getBeerXmlStandardWaterToGrainRatio());\n temp = temp * (this.getBeerXmlStandardStepTemp() - tunTemp) + this.getBeerXmlStandardStepTemp();\n }\n else {\n // Not initial infusion. Assume boiling water to make\n // calculation easier. If the next step has a LOWER temperature,\n // use room temperature water (72F).\n try {\n if (getPreviousStep().getBeerXmlStandardStepTemp() < this.getBeerXmlStandardStepTemp()) {\n temp = 100;\n }\n else {\n temp = 22.2222;\n }\n } catch (Exception e) {\n temp = - 1;\n }\n }\n\n // Set the infuse temperature.\n this.infuseTemp = temp;\n\n // Use appropriate units.\n if (Units.getTemperatureUnits().equals(Units.CELSIUS)) {\n return temp;\n }\n else {\n return Units.celsiusToFahrenheit(temp);\n }\n }\n\n private double calculateBXSInfuseTemp() {\n if (Units.getTemperatureUnits().equals(Units.CELSIUS)) {\n return this.calculateInfuseTemp();\n }\n else {\n return Units.fahrenheitToCelsius(this.calculateInfuseTemp());\n }\n }\n\n public boolean firstInList() {\n return this.getOrder() == 0;\n }\n\n public void setBeerXmlStandardInfuseAmount(double amt) {\n this.infuseAmount = amt;\n }\n\n public double getBeerXmlStandardInfuseAmount() {\n if (this.calcInfuseAmt) {\n calculateInfuseAmount();\n }\n return this.infuseAmount;\n }\n\n public double getDisplayInfuseTemp() {\n if (this.calcInfuseTemp) {\n return Math.round(this.calculateInfuseTemp());\n }\n\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Math.round(Units.celsiusToFahrenheit(this.infuseTemp));\n }\n else {\n return Math.round(this.infuseTemp);\n }\n }\n\n public void setDisplayInfuseTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.infuseTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.infuseTemp = d;\n }\n }\n\n public double getBeerXmlStandardInfuseTemp() {\n return this.infuseTemp;\n }\n\n public void setBeerXmlStandardInfuseTemp(double d) {\n this.infuseTemp = d;\n }\n\n public void setAutoCalcInfuseTemp(boolean b) {\n this.calcInfuseTemp = b;\n }\n\n public void setAutoCalcInfuseAmt(boolean b) {\n this.calcInfuseAmt = b;\n }\n\n public void setAutoCalcDecoctAmt(boolean b) {\n this.calcDecoctAmt = b;\n }\n\n public boolean getAutoCalcDecoctAmt() {\n return this.calcDecoctAmt;\n }\n\n public boolean getAutoCalcInfuseTemp() {\n return this.calcInfuseTemp;\n }\n\n public boolean getAutoCalcInfuseAmt() {\n return this.calcInfuseAmt;\n }\n\n public void setDisplayStepTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.stepTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.stepTemp = temp;\n }\n }\n\n public double getDisplayStepTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.stepTemp);\n }\n else {\n return this.stepTemp;\n }\n }\n\n public void setBeerXmlStandardStepTemp(double temp) {\n this.stepTemp = temp;\n }\n\n public double getBeerXmlStandardStepTemp() {\n return this.stepTemp;\n }\n\n public double getBeerXmlStandardWaterToGrainRatio() {\n // If this is the first in the list, use the configured value.\n // Otherwise, we need to calculate it based on the water added.\n if (this.firstInList() && ! this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n return this.waterToGrainRatio;\n }\n return (this.getBeerXmlStandardInfuseAmount() + this.getBXSTotalWaterInMash()) / this.getBeerXmlStandardMashWeight();\n }\n\n public double getDisplayWaterToGrainRatio() {\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n return Units.LPKGtoQPLB(getBeerXmlStandardWaterToGrainRatio());\n }\n else {\n return getBeerXmlStandardWaterToGrainRatio();\n }\n }\n\n public void setBeerXmlStandardWaterToGrainRatio(double d) {\n // Don't update if less than 0. Impossible value.\n if (d <= 0) {\n return;\n }\n this.waterToGrainRatio = d;\n }\n\n public void setDisplayWaterToGrainRatio(double d) {\n if (d <= 0) {\n return;\n }\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n this.waterToGrainRatio = Units.QPLBtoLPKG(d);\n }\n else {\n this.waterToGrainRatio = d;\n }\n }\n\n public void setOrder(int i) {\n // Order is privately used for ordering mash steps\n // when they are received from the database. Once they\n // are out of the db, we use the order in the list as the order.\n // When saved, the orders will be updated in the database.\n this.order = i;\n }\n\n public int getOrder() {\n return this.recipe.getMashProfile().getMashStepList().indexOf(this);\n }\n\n public void setDescription(String s) {\n this.description = s;\n }\n\n public String getDescription() {\n return this.description;\n }\n\n public void setStepTime(double time) {\n this.stepTime = time;\n }\n\n public double getStepTime() {\n return this.stepTime;\n }\n\n public void setRampTime(double time) {\n this.rampTime = time;\n }\n\n public double getRampTime() {\n return this.rampTime;\n }\n\n public void setBeerXmlStandardEndTemp(double temp) {\n this.endTemp = temp;\n }\n\n public double getBeerXmlStandardEndTemp() {\n return this.endTemp;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public long getId() {\n return this.id;\n }\n\n public void setOwnerId(long id) {\n this.ownerId = id;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setRecipe(Recipe r) {\n this.recipe = r;\n }\n\n public Recipe getRecipe() {\n return this.recipe;\n }\n\n public double getBeerXmlStandardMashWeight() {\n // If there are no ingredients for this recipe yet, we need to use something!\n // Fake it, assume 12 pounds of grain by default.\n double weight = BrewCalculator.TotalBeerXmlMashWeight(this.recipe);\n return weight == 0 ? Units.poundsToKilos(12) : weight;\n }\n\n public MashStep getPreviousStep() throws Exception {\n if (this.firstInList()) {\n throw new Exception(); // TODO: This should throw a specific exception.\n }\n\n int idx = this.recipe.getMashProfile().getMashStepList().indexOf(this);\n return this.recipe.getMashProfile().getMashStepList().get(idx - 1);\n }\n\n public double getBXSTotalWaterInMash() {\n double amt = 0;\n\n for (MashStep step : this.recipe.getMashProfile().getMashStepList()) {\n if (step.equals(this)) {\n break;\n }\n amt += step.getBeerXmlStandardInfuseAmount();\n }\n Log.d(\"MashStep\", \"Step \" + this.getName() + \" has \" + Units.litersToGallons(amt) + \" gal in mash.\");\n return amt;\n }\n}", "public class Recipe implements Parcelable {\n // ===============================================================\n // Static values =================================================\n // ===============================================================\n public static final String EXTRACT = \"Extract\";\n public static final String ALL_GRAIN = \"All Grain\";\n public static final String PARTIAL_MASH = \"Partial Mash\";\n public static final int STAGE_PRIMARY = 1;\n public static final int STAGE_SECONDARY = 2;\n public static final int STAGE_TERTIARY = 3;\n public static final Parcelable.Creator<Recipe> CREATOR =\n new Parcelable.Creator<Recipe>() {\n @Override\n public Recipe createFromParcel(Parcel p) {\n return new Recipe(p);\n }\n\n @Override\n public Recipe[] newArray(int size) {\n return new Recipe[]{};\n }\n };\n\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // Recipe name\n private int version; // XML Version -- 1\n private String type; // Extract, Grain, Mash\n private BeerStyle style; // Stout, Pilsner, etc.\n private String brewer; // Brewer's name\n private double batchSize; // Target size (L)\n private double boilSize; // Pre-boil vol (L)\n private int boilTime; // In Minutes\n private double efficiency; // 100 for extract\n private ArrayList<Hop> hops; // Hops used\n private ArrayList<Fermentable> fermentables; // Fermentables used\n private ArrayList<Yeast> yeasts; // Yeasts used\n private ArrayList<Misc> miscs; // Misc ingredients used\n private ArrayList<Water> waters; // Waters used\n private MashProfile mashProfile; // Mash profile for non-extracts\n\n // ================================================================\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double OG; // Original Gravity\n private double FG; // Final Gravity\n private int fermentationStages; // # of Fermentation stages\n private int primaryAge; // Time in primary in days\n private double primaryTemp; // Temp in primary in C\n private int secondaryAge; // Time in Secondary in days\n private double secondaryTemp; // Temp in secondary in C\n private int tertiaryAge; // Time in tertiary in days\n private double tertiaryTemp; // Temp in tertiary in C\n private String tasteNotes; // Taste notes\n private int tasteRating; // Taste score out of 50\n private int bottleAge; // Bottle age in days\n private double bottleTemp; // Bottle temp in C\n private boolean isForceCarbonated;// True if force carb is used\n private double carbonation; // Volumes of carbonation\n private String brewDate; // Date brewed\n private String primingSugarName; // Name of sugar for priming\n private double primingSugarEquiv; // Equivalent amount of priming sugar to be used\n private double kegPrimingFactor; // factor - use less sugar when kegging vs bottles\n private double carbonationTemp; // Carbonation temperature in C\n private int calories; // Calories (KiloCals)\n private String lastModified; // Date last modified in database.\n\n // ================================================================\n // Custom Fields ==================================================\n // ================================================================\n private long id; // id for use in database\n private String notes; // User input notes\n private int batchTime; // Total length in weeks\n private double ABV; // Alcohol by volume\n private double bitterness; // Bitterness in IBU\n private double color; // Color - SRM\n private InstructionGenerator instructionGenerator;\n private double measuredOG; // Brew day stat: measured OG\n private double measuredFG; // Brew stat: measured FG\n private double measuredVol; // Measured final volume (L) of batch.\n private double steepTemp; // Temperature to steep grains.\n\n // ================================================================\n // Fields for auto-calculation ====================================\n // ================================================================\n private boolean calculateBoilVolume; // Calculate the boil volume automatically\n private boolean calculateStrikeVolume; // Calculate strike vol automatically\n private boolean calculateStrikeTemp; // Calculate strike temp automatically\n\n // Public constructors\n public Recipe(String s) {\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n this.name = s;\n this.setVersion(1);\n this.setType(ALL_GRAIN);\n this.style = Constants.BEERSTYLE_OTHER;\n this.setBrewer(\"Unknown Brewer\");\n this.setDisplayBatchSize(5);\n this.setDisplayBoilSize(2.5);\n this.setBoilTime(60);\n this.setEfficiency(70);\n this.hops = new ArrayList<Hop>();\n this.fermentables = new ArrayList<Fermentable>();\n this.yeasts = new ArrayList<Yeast>();\n this.miscs = new ArrayList<Misc>();\n this.waters = new ArrayList<Water>();\n this.mashProfile = new MashProfile(this);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n this.OG = 1;\n this.setFG(1);\n this.setFermentationStages(1);\n this.primaryAge = 14;\n this.secondaryAge = 0;\n this.tertiaryAge = 0;\n this.primaryTemp = 21;\n this.secondaryTemp = 21;\n this.tertiaryTemp = 21;\n this.bottleAge = 14;\n this.brewDate = \"\";\n\n // Custom Fields ==================================================\n // ================================================================\n this.id = - 1;\n this.notes = \"\";\n this.tasteNotes = \"\";\n this.batchTime = 60;\n this.ABV = 0;\n this.bitterness = 0;\n this.color = 0;\n this.instructionGenerator = new InstructionGenerator(this);\n this.measuredOG = 0;\n this.measuredFG = 0;\n this.measuredVol = 0;\n this.steepTemp = Units.fahrenheitToCelsius(155);\n this.lastModified = new SimpleDateFormat(Constants.LAST_MODIFIED_DATE_FMT).format(new Date());\n\n // Fields for auto-calculation ====================================\n // ================================================================\n calculateBoilVolume = true;\n calculateStrikeVolume = false;\n calculateStrikeTemp = false;\n\n update();\n }\n\n // Constructor with no arguments!\n public Recipe() {\n this(\"New Recipe\");\n }\n\n public Recipe(Parcel p) {\n hops = new ArrayList<Hop>();\n fermentables = new ArrayList<Fermentable>();\n yeasts = new ArrayList<Yeast>();\n miscs = new ArrayList<Misc>();\n waters = new ArrayList<Water>();\n\n name = p.readString(); // Recipe name\n version = p.readInt(); // XML Version -- 1\n type = p.readString(); // Extract, Grain, Mash\n style = p.readParcelable(BeerStyle.class.getClassLoader()); // Stout, Pilsner, etc.\n brewer = p.readString(); // Brewer's name\n batchSize = p.readDouble();\n boilSize = p.readDouble();\n boilTime = p.readInt(); // In Minutes\n efficiency = p.readDouble(); // 100 for extract\n p.readTypedList(hops, Hop.CREATOR); // Hops used\n p.readTypedList(fermentables, Fermentable.CREATOR); // Fermentables used\n p.readTypedList(yeasts, Yeast.CREATOR); // Yeasts used\n p.readTypedList(miscs, Misc.CREATOR); // Misc ingredients used\n p.readTypedList(waters, Water.CREATOR); // Waters used\n mashProfile = p.readParcelable(MashProfile.class.getClassLoader()); // Mash profile for non-extracts\n mashProfile.setRecipe(this);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n OG = p.readDouble(); // Original Gravity\n FG = p.readDouble(); // Final Gravity\n fermentationStages = p.readInt(); // # of Fermentation stages\n primaryAge = p.readInt(); // Time in primary in days\n primaryTemp = p.readDouble(); // Temp in primary in C\n secondaryAge = p.readInt(); // Time in Secondary in days\n secondaryTemp = p.readDouble(); // Temp in secondary in C\n tertiaryAge = p.readInt(); // Time in tertiary in days\n tertiaryTemp = p.readDouble(); // Temp in tertiary in C\n tasteNotes = p.readString(); // Taste notes\n tasteRating = p.readInt(); // Taste score out of 50\n bottleAge = p.readInt(); // Bottle age in days\n bottleTemp = p.readDouble(); // Bottle temp in C\n isForceCarbonated = p.readInt() > 0; // True if force carb is used\n carbonation = p.readDouble(); // Volumes of carbonation\n brewDate = p.readString(); // Date brewed\n primingSugarName = p.readString(); // Name of sugar for priming\n primingSugarEquiv = p.readDouble(); // Equivalent amount of priming sugar to be used\n kegPrimingFactor = p.readDouble(); // factor - use less sugar when kegging vs bottles\n carbonationTemp = p.readDouble(); // Carbonation temperature in C\n calories = p.readInt();\n lastModified = p.readString();\n\n // Custom Fields ==================================================\n // ================================================================\n id = p.readLong(); // id for use in database\n notes = p.readString(); // User input notes\n batchTime = p.readInt(); // Total length in weeks\n ABV = p.readDouble(); // Alcohol by volume\n bitterness = p.readDouble(); // Bitterness in IBU\n color = p.readDouble(); // Color - SRM\n // Instruction generator not included in parcel\n measuredOG = p.readDouble(); // Brew day stat: measured OG\n measuredFG = p.readDouble(); // Brew stat: measured FG\n measuredVol = p.readDouble(); // Brew stat: measured volume\n steepTemp = p.readDouble(); // Temperature to steep grains for extract recipes.\n\n // Fields for auto-calculation ====================================\n // ================================================================\n calculateBoilVolume = p.readInt() > 0;\n calculateStrikeVolume = p.readInt() > 0;\n calculateStrikeTemp = p.readInt() > 0;\n\n // Create instruction generator\n instructionGenerator = new InstructionGenerator(this);\n update();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n p.writeString(name); // Recipe name\n p.writeInt(version); // XML Version -- 1\n p.writeString(type); // Extract, Grain, Mash\n p.writeParcelable(style, flags); // Stout, Pilsner, etc.\n p.writeString(brewer); // Brewer's name\n p.writeDouble(batchSize); // Target size (L)\n p.writeDouble(boilSize); // Pre-boil vol (L)\n p.writeInt(boilTime); // In Minutes\n p.writeDouble(efficiency); // 100 for extract\n p.writeTypedList(hops); // Hops used\n p.writeTypedList(fermentables); // Fermentables used\n p.writeTypedList(yeasts); // Yeasts used\n p.writeTypedList(miscs); // Misc ingredients used\n p.writeTypedList(waters); // Waters used\n p.writeParcelable(mashProfile, flags); // Mash profile for non-extracts\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(OG); // Original Gravity\n p.writeDouble(FG); // Final Gravity\n p.writeInt(fermentationStages); // # of Fermentation stages\n p.writeInt(primaryAge); // Time in primary in days\n p.writeDouble(primaryTemp); // Temp in primary in C\n p.writeInt(secondaryAge); // Time in Secondary in days\n p.writeDouble(secondaryTemp); // Temp in secondary in C\n p.writeInt(tertiaryAge); // Time in tertiary in days\n p.writeDouble(tertiaryTemp); // Temp in tertiary in C\n p.writeString(tasteNotes); // Taste notes\n p.writeInt(tasteRating); // Taste score out of 50\n p.writeInt(bottleAge); // Bottle age in days\n p.writeDouble(bottleTemp); // Bottle temp in C\n p.writeInt(isForceCarbonated ? 1 : 0); // True if force carb is used\n p.writeDouble(carbonation); // Volumes of carbonation\n p.writeString(brewDate); // Date brewed\n p.writeString(primingSugarName); // Name of sugar for priming\n p.writeDouble(primingSugarEquiv); // Equivalent amount of priming sugar to be used\n p.writeDouble(kegPrimingFactor); // factor - use less sugar when kegging vs bottles\n p.writeDouble(carbonationTemp); // Carbonation temperature in C\n p.writeInt(calories); // Calories (KiloCals)\n p.writeString(lastModified);\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(id); // id for use in database\n p.writeString(notes); // User input notes\n p.writeInt(batchTime); // Total length in weeks\n p.writeDouble(ABV); // Alcohol by volume\n p.writeDouble(bitterness); // Bitterness in IBU\n p.writeDouble(color); // Color - SRM\n // Instruction generator not included in parcel\n p.writeDouble(measuredOG); // Brew day stat: measured OG\n p.writeDouble(measuredFG); // Brew stat: measured FG\n p.writeDouble(measuredVol); // Brew stat: measured volume\n p.writeDouble(steepTemp); // Steep temperature for extract recipes.\n\n // Fields for auto-calculation ====================================\n // ================================================================\n p.writeInt(calculateBoilVolume ? 1 : 0);\n p.writeInt(calculateStrikeVolume ? 1 : 0);\n p.writeInt(calculateStrikeTemp ? 1 : 0);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n /**\n * Recipe objects are identified by the recipe name and the recipe's ID, as used when stored in\n * the database. If a recipe has not been stored in the database, it will not necessarily have a\n * unique ID.\n */\n @Override\n public boolean equals(Object o) {\n // If the given object is not a Recipe, it cannot be equal.\n if (! (o instanceof Recipe)) {\n return false;\n }\n\n // The given object is a recipe - cast it.\n Recipe other = (Recipe) o;\n\n // Check index fields.\n if (! other.getRecipeName().equals(this.getRecipeName())) {\n // If the given recipe does not have the same name, it is not equal.\n return false;\n }\n else if (other.getId() != this.getId()) {\n // If the given recipe does not have the same ID, it is not equal.\n return false;\n }\n\n // Otherwise, the two recipes are equal.\n return true;\n }\n\n @Override\n public String toString() {\n return this.getRecipeName();\n }\n\n // Public methods\n public void update() {\n setColor(BrewCalculator.Color(this));\n setOG(BrewCalculator.OriginalGravity(this));\n setBitterness(BrewCalculator.Bitterness(this));\n setFG(BrewCalculator.FinalGravity(this));\n setABV(BrewCalculator.AlcoholByVolume(this));\n this.instructionGenerator.generate();\n }\n\n public String getRecipeName() {\n return this.name;\n }\n\n public void setRecipeName(String name) {\n this.name = name;\n }\n\n public void addIngredient(Ingredient i) {\n Log.d(getRecipeName() + \"::addIngredient\", \"Adding ingredient: \" + i.getName());\n if (i.getType().equals(Ingredient.HOP)) {\n addHop(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n addFermentable(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n addMisc(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n addYeast(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n addWater(i);\n }\n\n update();\n }\n\n public void removeIngredientWithId(long id) {\n for (Ingredient i : getIngredientList()) {\n if (i.getId() == id) {\n Log.d(\"Recipe\", \"Removing ingredient \" + i.getName());\n removeIngredient(i);\n }\n }\n }\n\n public void removeIngredient(Ingredient i) {\n if (i.getType().equals(Ingredient.HOP)) {\n hops.remove(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n fermentables.remove(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n miscs.remove(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n yeasts.remove(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n waters.remove(i);\n }\n\n if (getIngredientList().contains(i)) {\n Log.d(\"Recipe\", \"Failed to remove ingredient\");\n }\n else {\n Log.d(\"Recipe\", \"Successfully removed ingredient\");\n }\n\n update();\n }\n\n public MashProfile getMashProfile() {\n return this.mashProfile;\n }\n\n public void setMashProfile(MashProfile profile) {\n this.mashProfile = profile;\n this.mashProfile.setRecipe(this);\n update();\n }\n\n public String getNotes() {\n return notes;\n }\n\n public void setNotes(String notes) {\n this.notes = notes;\n }\n\n public BeerStyle getStyle() {\n return style;\n }\n\n public void setStyle(BeerStyle beerStyle) {\n this.style = beerStyle;\n }\n\n public ArrayList<Ingredient> getIngredientList() {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n list.addAll(hops);\n list.addAll(fermentables);\n list.addAll(yeasts);\n list.addAll(miscs);\n list.addAll(waters);\n\n Collections.sort(list, new RecipeIngredientsComparator());\n return list;\n }\n\n public void setIngredientsList(ArrayList<Ingredient> ingredientsList) {\n\n for (Ingredient i : ingredientsList) {\n if (i.getType().equals(Ingredient.HOP)) {\n addHop(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n addFermentable(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n addMisc(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n addYeast(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n addWater(i);\n }\n }\n\n update();\n }\n\n private void addWater(Ingredient i) {\n Water w = (Water) i;\n waters.add(w);\n }\n\n private void addYeast(Ingredient i) {\n Yeast y = (Yeast) i;\n yeasts.add(y);\n }\n\n private void addMisc(Ingredient i) {\n Misc m = (Misc) i;\n miscs.add(m);\n }\n\n private void addFermentable(Ingredient i) {\n Log.d(getRecipeName() + \"::addFermentable\", \"Adding fermentable: \" + i.getName());\n Fermentable f = (Fermentable) i;\n this.fermentables.add(f);\n }\n\n private void addHop(Ingredient i) {\n Hop h = (Hop) i;\n this.hops.add(h);\n }\n\n public ArrayList<Instruction> getInstructionList() {\n return this.instructionGenerator.getInstructions();\n }\n\n public double getOG() {\n return OG;\n }\n\n public void setOG(double gravity) {\n gravity = (double) Math.round(gravity * 1000) / 1000;\n this.OG = gravity;\n }\n\n public double getBitterness() {\n bitterness = (double) Math.round(bitterness * 10) / 10;\n return bitterness;\n }\n\n public void setBitterness(double bitterness) {\n bitterness = (double) Math.round(bitterness * 10) / 10;\n this.bitterness = bitterness;\n }\n\n public double getColor() {\n color = (double) Math.round(color * 10) / 10;\n return color;\n }\n\n public void setColor(double color) {\n color = (double) Math.round(color * 10) / 10;\n this.color = color;\n }\n\n public double getABV() {\n ABV = (double) Math.round(ABV * 10) / 10;\n return ABV;\n }\n\n public void setABV(double aBV) {\n ABV = (double) Math.round(ABV * 10) / 10;\n ABV = aBV;\n }\n\n public int getBatchTime() {\n return batchTime;\n }\n\n public void setBatchTime(int batchTime) {\n this.batchTime = batchTime;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getVolumeUnits() {\n return Units.getVolumeUnits();\n }\n\n public double getDisplayBatchSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.batchSize);\n }\n else {\n return this.batchSize;\n }\n }\n\n public void setDisplayBatchSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.batchSize = Units.gallonsToLiters(size);\n }\n else {\n this.batchSize = size;\n }\n }\n\n public double getDisplayMeasuredBatchSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.measuredVol);\n }\n else {\n return this.measuredVol;\n }\n }\n\n public void setDisplayMeasuredBatchSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.measuredVol = Units.gallonsToLiters(size);\n }\n else {\n this.measuredVol = size;\n }\n }\n\n public double getBeerXmlStandardBatchSize() {\n return this.batchSize;\n }\n\n public void setBeerXmlStandardBatchSize(double v) {\n this.batchSize = v;\n }\n\n public double getBeerXmlMeasuredBatchSize() {\n return this.measuredVol;\n }\n\n public void setBeerXmlMeasuredBatchSize(double d) {\n this.measuredVol = d;\n }\n\n public int getBoilTime() {\n return boilTime;\n }\n\n public void setBoilTime(int boilTime) {\n this.boilTime = boilTime;\n }\n\n public double getEfficiency() {\n if (this.getType().equals(EXTRACT)) {\n return 100;\n }\n return efficiency;\n }\n\n public void setEfficiency(double efficiency) {\n this.efficiency = efficiency;\n }\n\n public String getBrewer() {\n return brewer;\n }\n\n public void setBrewer(String brewer) {\n this.brewer = brewer;\n }\n\n public double getDisplayBoilSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n if (this.calculateBoilVolume) {\n return Units.litersToGallons(calculateBoilVolume());\n }\n else {\n return Units.litersToGallons(this.boilSize);\n }\n }\n else {\n if (this.calculateBoilVolume) {\n return calculateBoilVolume();\n }\n else {\n return this.boilSize;\n }\n }\n }\n\n public void setDisplayBoilSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.boilSize = Units.gallonsToLiters(size);\n }\n else {\n this.boilSize = size;\n }\n }\n\n private double calculateBoilVolume() {\n // TODO: Get parameters from equipment profile.\n double TRUB_LOSS = Units.gallonsToLiters(.3); // Liters lost\n double SHRINKAGE = .04; // Percent lost\n double EVAP_LOSS = Units.gallonsToLiters(1.5); // Evaporation loss (L/hr)\n\n if (this.type.equals(Recipe.ALL_GRAIN)) {\n return batchSize * (1 + SHRINKAGE) + TRUB_LOSS + (EVAP_LOSS * Units.minutesToHours(boilTime));\n }\n else {\n return (batchSize / 3) * (1 + SHRINKAGE) + TRUB_LOSS + (EVAP_LOSS * Units.minutesToHours\n (boilTime));\n }\n }\n\n public double getBeerXmlStandardBoilSize() {\n return boilSize;\n }\n\n public void setBeerXmlStandardBoilSize(double boilSize) {\n this.boilSize = boilSize;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public double getFG() {\n this.FG = (double) Math.round(FG * 1000) / 1000;\n return this.FG;\n }\n\n public void setFG(double fG) {\n fG = (double) Math.round(fG * 1000) / 1000;\n this.FG = fG;\n }\n\n public int getFermentationStages() {\n return fermentationStages;\n }\n\n public void setFermentationStages(int fermentationStages) {\n this.fermentationStages = fermentationStages;\n }\n\n public int getTotalFermentationDays() {\n return this.primaryAge + this.secondaryAge + this.tertiaryAge;\n }\n\n public int getVersion() {\n return version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public ArrayList<Misc> getMiscList() {\n return miscs;\n }\n\n public ArrayList<Fermentable> getFermentablesList() {\n return fermentables;\n }\n\n public ArrayList<Hop> getHopsList() {\n return hops;\n }\n\n public ArrayList<Yeast> getYeastsList() {\n return yeasts;\n }\n\n public ArrayList<Water> getWatersList() {\n return waters;\n }\n\n /**\n * Generates a list of hops in this recipe with the given use.\n *\n * @param use\n * One of Ingredient.USE_*\n * @return An ArrayList of Ingredients.\n */\n public ArrayList<Ingredient> getHops(String use) {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n for (Hop h : this.getHopsList()) {\n if (h.getUse().equals(use)) {\n list.add(h);\n }\n }\n return list;\n }\n\n public double getMeasuredOG() {\n return this.measuredOG;\n }\n\n public void setMeasuredOG(double d) {\n this.measuredOG = d;\n }\n\n public double getMeasuredFG() {\n return this.measuredFG;\n }\n\n public void setMeasuredFG(double d) {\n this.measuredFG = d;\n }\n\n public int getDisplayCoolToFermentationTemp() {\n // Metric - imperial conversion is performed in Yeast\n for (Yeast y : this.getYeastsList()) {\n return y.getDisplayFermentationTemp();\n }\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return 65;\n }\n else {\n return (int) Units.fahrenheitToCelsius(65);\n }\n }\n\n public double getDisplaySteepTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(steepTemp);\n }\n else {\n return steepTemp;\n }\n }\n\n public void setDisplaySteepTemp(double t) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.steepTemp = Units.fahrenheitToCelsius(t);\n }\n else {\n this.steepTemp = t;\n }\n }\n\n public void setNumberFermentationStages(int stages) {\n this.fermentationStages = stages;\n }\n\n public void setFermentationAge(int stage, int age) {\n switch (stage) {\n case STAGE_PRIMARY:\n this.primaryAge = age;\n case STAGE_SECONDARY:\n this.secondaryAge = age;\n case STAGE_TERTIARY:\n this.tertiaryAge = age;\n }\n }\n\n public int getFermentationAge(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n return this.primaryAge;\n case STAGE_SECONDARY:\n return this.secondaryAge;\n case STAGE_TERTIARY:\n return this.tertiaryAge;\n default:\n return 7;\n }\n }\n\n public void setBeerXmlStandardFermentationTemp(int stage, double temp) {\n switch (stage) {\n case STAGE_PRIMARY:\n this.primaryTemp = temp;\n case STAGE_SECONDARY:\n this.secondaryTemp = temp;\n case STAGE_TERTIARY:\n this.tertiaryTemp = temp;\n }\n }\n\n public double getBeerXmlStandardFermentationTemp(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n return this.primaryTemp;\n case STAGE_SECONDARY:\n return this.secondaryTemp;\n case STAGE_TERTIARY:\n return this.tertiaryTemp;\n default:\n return 21;\n }\n }\n\n public void setDisplayFermentationTemp(int stage, double temp) {\n switch (stage) {\n case STAGE_PRIMARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.primaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.primaryTemp = temp;\n }\n break;\n\n case STAGE_SECONDARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.secondaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.secondaryTemp = temp;\n }\n break;\n\n case STAGE_TERTIARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.tertiaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.secondaryTemp = temp;\n }\n break;\n }\n }\n\n public double getDisplayFermentationTemp(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.primaryTemp);\n }\n else {\n return this.primaryTemp;\n }\n\n case STAGE_SECONDARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.secondaryTemp);\n }\n else {\n return this.secondaryTemp;\n }\n\n case STAGE_TERTIARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.tertiaryTemp);\n }\n else {\n return this.tertiaryTemp;\n }\n\n default:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(21);\n }\n else {\n return 21;\n }\n }\n }\n\n public String getTasteNotes() {\n if (this.tasteNotes == null) {\n this.tasteNotes = \"\";\n }\n return this.tasteNotes;\n }\n\n public void setTasteNotes(String s) {\n this.tasteNotes = s;\n }\n\n public int getTasteRating() {\n return this.tasteRating;\n }\n\n public void setTasteRating(int i) {\n this.tasteRating = i;\n }\n\n public int getBottleAge() {\n return this.bottleAge;\n }\n\n public void setBottleAge(int i) {\n this.bottleAge = i;\n }\n\n public double getBeerXmlStandardBottleTemp() {\n return this.bottleTemp;\n }\n\n public void setBeerXmlStandardBottleTemp(double d) {\n this.bottleTemp = d;\n }\n\n public double getDisplayBottleTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.bottleTemp);\n }\n else {\n return this.bottleTemp;\n }\n }\n\n public void setDisplayBottleTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.bottleTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.bottleTemp = d;\n }\n }\n\n public boolean isForceCarbonated() {\n return this.isForceCarbonated;\n }\n\n public void setIsForceCarbonated(boolean b) {\n this.isForceCarbonated = b;\n }\n\n public double getCarbonation() {\n return this.carbonation;\n }\n\n public void setCarbonation(double d) {\n this.carbonation = d;\n }\n\n public void setLastModified(String s) {\n this.lastModified = s;\n }\n\n public Date getLastModified() {\n try {\n Date d = new SimpleDateFormat(Constants.LAST_MODIFIED_DATE_FMT).parse(this.lastModified);\n Log.d(\"Recipe\", this.toString() + \" was last modified \" + d.toString());\n return d;\n } catch (ParseException e) {\n Log.w(\"Recipe\", \"Failed to parse lastModified: \" + this.lastModified);\n return new Date();\n } catch (NullPointerException e) {\n // No modified date was ever set - likely a recipe from before this\n // feature existed.\n Log.w(\"Recipe\", \"No last modified for recipe: \" + this.toString());\n return new Date();\n }\n }\n\n public String getBrewDate() {\n if (this.brewDate == null) {\n this.brewDate = \"\";\n }\n return this.brewDate;\n }\n\n public void setBrewDate(String s) {\n this.brewDate = s;\n }\n\n /* There is no standardized date format in beerXML. Thus, we need\n * to try and parse as many formats as possible. This method takes the given raw\n * date string and returns the best effort Date object. If not we're unable to parse\n * the date, then this method returns today's date.\n */\n public Date getBrewDateDate() {\n // First, try the common date formats to speed things up. We'll resort to a full search\n // of known formats if these fail.\n String d = this.getBrewDate();\n\n // This format is common for BeerSmith recipes.\n try {\n return new SimpleDateFormat(\"MM/dd/yyyy\").parse(d);\n } catch (ParseException e) {\n // Do nothing.\n }\n\n // This format is used by Biermacht.\n try {\n return new SimpleDateFormat(\"dd MMM yyyy\").parse(d);\n } catch (ParseException e) {\n // Do nothing.\n }\n\n // This takes a long time, so only do it as a last resort.\n // Look through a bunch of known formats to figure out what it is.\n String fmt = DateUtil.determineDateFormat(d);\n if (fmt == null) {\n Log.w(\"Recipe\", \"Failed to parse date: \" + d);\n return new Date();\n }\n try {\n return new SimpleDateFormat(fmt).parse(d);\n } catch (ParseException e) {\n Log.e(\"Recipe\", \"Failed to parse date: \" + d);\n e.printStackTrace();\n return new Date();\n }\n }\n\n public String getPrimingSugarName() {\n return this.primingSugarName;\n }\n\n public void setPrimingSugarName(String s) {\n this.primingSugarName = s;\n }\n\n public double getPrimingSugarEquiv() {\n // TODO\n return 0.0;\n }\n\n public void setPrimingSugarEquiv(double d) {\n this.primingSugarEquiv = d;\n }\n\n public double getBeerXmlStandardCarbonationTemp() {\n return this.carbonationTemp;\n }\n\n public void setBeerXmlStandardCarbonationTemp(double d) {\n this.carbonationTemp = d;\n }\n\n public double getDisplayCarbonationTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.carbonationTemp);\n }\n else {\n return this.carbonationTemp;\n }\n }\n\n public void setDisplayCarbonationTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.carbonationTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.carbonationTemp = d;\n }\n }\n\n public double getKegPrimingFactor() {\n return this.kegPrimingFactor;\n }\n\n public void setKegPrimingFactor(double d) {\n this.kegPrimingFactor = d;\n }\n\n public int getCalories() {\n return this.calories;\n }\n\n public void setCalories(int i) {\n this.calories = i;\n }\n\n public boolean getCalculateBoilVolume() {\n return this.calculateBoilVolume;\n }\n\n public void setCalculateBoilVolume(boolean b) {\n this.calculateBoilVolume = b;\n }\n\n public boolean getCalculateStrikeVolume() {\n return this.calculateStrikeVolume;\n }\n\n public void setCalculateStrikeVolume(boolean b) {\n this.calculateStrikeVolume = b;\n }\n\n public boolean getCalculateStrikeTemp() {\n return this.calculateStrikeTemp;\n }\n\n public void setCalculateStrikeTemp(boolean b) {\n this.calculateStrikeTemp = b;\n }\n\n public double getMeasuredABV() {\n if (this.getMeasuredFG() > 0 && this.getMeasuredOG() > this.getMeasuredFG()) {\n return (this.getMeasuredOG() - this.getMeasuredFG()) * 131;\n }\n else {\n return 0;\n }\n }\n\n public double getMeasuredEfficiency() {\n double potGravP, measGravP;\n double eff = 100;\n double measBatchSize = this.getBeerXmlMeasuredBatchSize();\n\n // If the user hasn't input a measured batch size, assume the recipe went as planned\n // and that the target final batch size was hit.\n if (measBatchSize == 0) {\n Log.d(\"Recipe\", \"No measured batch size, try using recipe batch size\");\n measBatchSize = this.getBeerXmlStandardBatchSize();\n }\n\n if (! this.getType().equals(Recipe.EXTRACT)) {\n eff = getEfficiency();\n }\n\n // Computation only valid if measured gravity is greater than 1, and batch size is non-zero.\n // Theoretically, measured gravity could be less than 1, but we don't support that yet.\n if ((this.getMeasuredOG() > 1) && (batchSize > 0)) {\n // Calculate potential milli-gravity points. Adjust the value returned by the\n // brew calculator, because it takes the expected efficiency into account (which\n // we don't want here).\n potGravP = (BrewCalculator.OriginalGravity(this) - 1) / (eff / 100);\n\n // Adjust potential gravity points to account for measured batch size.\n potGravP = potGravP * (getBeerXmlStandardBatchSize() / measBatchSize);\n\n // Calculate the measured milli-gravity points.\n measGravP = this.getMeasuredOG() - 1;\n\n // Return the efficiency.\n return 100 * measGravP / potGravP;\n }\n else {\n return 0;\n }\n }\n\n public void save(Context c) {\n Log.d(getRecipeName() + \"::save\", \"Saving with id: \" + this.getId());\n new DatabaseAPI(c).updateRecipe(this);\n }\n}", "public class Constants {\n\n // New Objects\n public static final BeerStyle BEERSTYLE_OTHER = new BeerStyle(\"Other\");\n\n // Master recipe's ID. This is the ID of the dummy recipe we create on first use.\n // This recipe is used as a placeholder when a user-created recipe is not available.\n // For example, when a custom ingredient is added to the database, but is not in a recipe.\n public static final long MASTER_RECIPE_ID = 1;\n\n // Keys for passing objects\n public static final String KEY_RECIPE_ID = \"biermacht.brews.recipe.id\";\n public static final String KEY_RECIPE = \"biermacht.brews.recipe\";\n public static final String KEY_PROFILE_ID = \"biermacht.brews.mash.profile.id\";\n public static final String KEY_PROFILE = \"biermacht.brews.mash.profile\";\n public static final String KEY_INGREDIENT_ID = \"biermacht.brews.ingredient.id\";\n public static final String KEY_INGREDIENT = \"biermacht.brews.ingredient\";\n public static final String KEY_MASH_STEP = \"biermacht.brews.mash.step\";\n public static final String KEY_MASH_STEP_ID = \"biermacht.brews.mash.step.id\";\n public static final String KEY_MASH_STEP_LIST = \"biermacht.brews.mash.profile.steps\";\n public static final String KEY_MASH_PROFILE = \"biermacht.brews.mash.profile\";\n public static final String KEY_INSTRUCTION = \"biermacht.brews.instruction\";\n public static final String KEY_DATABASE_ID = \"biermacht.brews.database.id\";\n public static final String KEY_SECONDS = \"biermacht.brews.remaining.seconds\";\n public static final String KEY_TITLE = \"biermacht.brews.title\";\n public static final String KEY_COMMAND = \"biermacht.brews.command\";\n public static final String KEY_STEP_NUMBER = \"biermacht.brews.stepnumber\";\n public static final String KEY_TIMER_STATE = \"biermacht.brews.timer.state\";\n public static final String KEY_STYLE = \"biermacht.brews.style\";\n\n public static final int INVALID_ID = - 1;\n\n public static final String BREW_DATE_FMT = \"dd MMM yyyy\";\n public static final String LAST_MODIFIED_DATE_FMT = \"dd MMM yyyy HH:mm:ss\";\n\n // Indicates if a recipe should be displayed after it is created.\n public static final String DISPLAY_ON_CREATE = \"biermacht.brews.recipe.display.on.create\";\n\n // Valid commands\n public static final String COMMAND_START = \"biermacht.brews.commands.start\";\n public static final String COMMAND_STOP = \"biermacht.brews.commands.stop\";\n public static final String COMMAND_PAUSE = \"biermacht.brews.commands.pause\";\n public static final String COMMAND_QUERY = \"biermacht.brews.commands.query\";\n public static final String COMMAND_STOP_ALARM = \"biermacht.brews.commands.stop.alarm\";\n\n // Database identifiers used to slice SQLite database into\n // multiple zones, each with a different purpose.\n\n // System DB - imported from assets. Contains the selection of \"default\" ingredients /\n // profiles / styles / etc that come with the application.\n public static final long DATABASE_SYSTEM_RESOURCES = 2;\n\n // User DB - custom resources added by the user. Constains the selection of ingredients / profiles\n // styles / etc that a user has specifically added to the application.\n public static final long DATABASE_USER_RESOURCES = 1;\n\n // User DB - stores recipes and specific instances of the \"rubber-stamp\"\n // ingredients / profiles / styles / etc from one of SYSTEM_ADDED or USER_ADDED\n // that are related to those recipes.\n public static final long DATABASE_USER_RECIPES = 0;\n\n // No owner ID for use in database\n public static final long OWNER_NONE = - 1;\n\n // Broadcast types\n public static final String BROADCAST_TIMER = \"com.biermacht.brews.broadcast.timer\";\n public static final String BROADCAST_REMAINING_TIME = \"com.biermacht.brews.broadcast.timer.remaining\";\n public static final String BROADCAST_TIMER_CONTROLS = \"com.biermacht.brews.broadcast.timer.controls\";\n public static final String BROADCAST_QUERY_RESP = \"com.biermacht.brews.broadcast.query.resp\";\n\n // Shared preferences Constants\n public static final String PREFERENCES = \"com.biermacht.brews.preferences\";\n public static final String PREF_USED_BEFORE = \"com.biermacht.brews.usedBefore\";\n public static final String PREF_LAST_OPENED = \"com.biermacht.brews.lastOpened\";\n public static final String PREF_BREWER_NAME = \"com.biermacht.brews.brewerName\";\n public static final String PREF_MEAS_SYSTEM = \"com.biermacht.brews.measurementSystem\";\n public static final String PREF_FIXED_RATIOS = \"com.biermacht.brews.waterToGrainRatiosFixed\";\n public static final String PREF_HYDROMETER_CALIBRATION_TEMP = \"com.biermacht.brews.hydrometerCalibrationTemp\";\n public static final String PREF_SORT_STRATEGY = \"com.biermacht.brews.recipe_sort_strategy\";\n\n // Value of this preference indicates the last time db contents were updated.\n public static final String PREF_NEW_CONTENTS_VERSION = \"com.biermacht.brews.newIngredientsVersion\";\n\n // Incremented when new database contents are added.\n public static int NEW_DB_CONTENTS_VERSION = 5;\n\n // Valid recipe sort strategies.\n public static final String SORT_STRATEGY_ALPHABETICAL = \"Name (A to Z)\";\n public static final String SORT_STRATEGY_REV_ALPHABETICAL = \"Name (Z to A)\";\n public static final String SORT_STRATEGY_BREW_DATE = \"Created (Newest first)\";\n public static final String SORT_STRATEGY_REV_BREW_DATE = \"Created (Oldest first)\";\n public static final String SORT_STRATEGY_MODIFIED = \"Modified (Latest first)\";\n\n // Activity for result return codes\n public static final int RESULT_DELETED = 1;\n public static final int RESULT_OK = 2;\n public static final int RESULT_CANCELED = 3;\n\n // Request codes for activities\n public static final int REQUEST_NEW_MASH_STEP = 1;\n public static final int REQUEST_EDIT_MASH_STEP = 2;\n public static final int REQUEST_EDIT_RECIPE = 3;\n public static final int REQUEST_IMPORT_FILE = 4;\n public static final int REQUEST_CONNECT_TO_DRIVE = 5;\n public static final int REQUEST_DRIVE_FILE_OPEN = 6;\n public static final int REQUEST_DRIVE_FILE_CREATE = 7;\n\n // Possible timer states\n public static int PAUSED = 0;\n public static int RUNNING = 1;\n public static int STOPPED = 2;\n\n // Constant messages\n public static String MESSAGE_AUTO_CALC_W2GR = \"Water-to-grain ratio is calculated automatically for this step.\";\n\n // Other Constants\n private static final String[] hop_uses = {Hop.USE_BOIL, Hop.USE_AROMA, Hop.USE_DRY_HOP, Hop.USE_FIRST_WORT};\n private static final String[] hop_forms = {Hop.FORM_PELLET, Hop.FORM_WHOLE, Hop.FORM_PLUG};\n private static final String[] ferm_types = {Fermentable.TYPE_GRAIN, Fermentable.TYPE_EXTRACT, Fermentable.TYPE_SUGAR, Fermentable.TYPE_ADJUNCT};\n private static final String[] step_types = {MashStep.INFUSION, MashStep.DECOCTION, MashStep.TEMPERATURE};\n private static final String[] unit_systems = {Units.IMPERIAL, Units.METRIC};\n private static final String[] mash_types = {MashProfile.MASH_TYPE_DECOCTION, MashProfile.MASH_TYPE_INFUSION, MashProfile.MASH_TYPE_TEMPERATURE, MashProfile.MASH_TYPE_BIAB};\n private static final String[] sparge_types = {MashProfile.SPARGE_TYPE_BATCH, MashProfile.SPARGE_TYPE_FLY, MashProfile.SPARGE_TYPE_BIAB};\n private static final String[] sort_strats = {SORT_STRATEGY_ALPHABETICAL, SORT_STRATEGY_REV_ALPHABETICAL, SORT_STRATEGY_BREW_DATE, SORT_STRATEGY_REV_BREW_DATE, SORT_STRATEGY_MODIFIED};\n\n public static final ArrayList<String> HOP_USES = new ArrayList<String>(Arrays.asList(hop_uses));\n public static final ArrayList<String> HOP_FORMS = new ArrayList<String>(Arrays.asList(hop_forms));\n public static final ArrayList<String> FERMENTABLE_TYPES = new ArrayList<String>(Arrays.asList(ferm_types));\n public static final ArrayList<String> MASH_STEP_TYPES = new ArrayList<String>(Arrays.asList(step_types));\n public static final ArrayList<String> UNIT_SYSTEMS = new ArrayList<String>(Arrays.asList(unit_systems));\n public static final ArrayList<String> MASH_TYPES = new ArrayList<String>(Arrays.asList(mash_types));\n public static final ArrayList<String> SPARGE_TYPES = new ArrayList<String>(Arrays.asList(sparge_types));\n public static final ArrayList<String> RECIPE_SORT_STRATEGIES = new ArrayList(Arrays.asList(sort_strats));\n\n}" ]
import android.content.Context; import android.util.Log; import com.biermacht.brews.exceptions.ItemNotFoundException; import com.biermacht.brews.ingredient.Ingredient; import com.biermacht.brews.recipe.BeerStyle; import com.biermacht.brews.recipe.MashProfile; import com.biermacht.brews.recipe.MashStep; import com.biermacht.brews.recipe.Recipe; import com.biermacht.brews.utils.Constants; import java.util.ArrayList;
package com.biermacht.brews.database; public class DatabaseAPI { private Context context; private DatabaseInterface databaseInterface; public DatabaseAPI(Context c) { this.context = c; this.databaseInterface = new DatabaseInterface(this.context); this.databaseInterface.open(); } // Get all recipes in database. public ArrayList<Recipe> getRecipeList() { ArrayList<Recipe> list = this.databaseInterface.getRecipeList(); for (Recipe r : list) { r.update(); } return list; } // Create recipe with the given name public Recipe createRecipeWithName(String name) { Recipe r = new Recipe(name); long id = this.databaseInterface.addRecipeToDatabase(r); r = this.databaseInterface.getRecipeWithId(id); return r; } // Creates recipe from an existing one. public Recipe createRecipeFromExisting(Recipe r) { long id = this.databaseInterface.addRecipeToDatabase(r); r = this.databaseInterface.getRecipeWithId(id); return r; } // Updates existing recipe public boolean updateRecipe(Recipe r) { r.update(); return this.databaseInterface.updateExistingRecipe(r); } // Updates existing ingredient
public boolean updateIngredient(Ingredient i, long dbid) {
1
OlliV/angr
workspace/Angr/src/fi/hbp/angr/models/actors/Grenade.java
[ "public class AssetContainer {\n /**\n * Texture for the body.\n */\n public Texture texture;\n\n /**\n * BodyDef for the body.\n */\n public BodyDef bd;\n\n /**\n * FixtureDef for the body.\n */\n public FixtureDef fd;\n}", "public class G {\n /**\n * Debug mode\n *\n * If this is set to true game will output some additional data and\n * enables debug camera functionality. Debug camera is enabled by\n * pressing d while in the game stage.\n */\n public static final boolean DEBUG = false;\n\n /**\n * Global static assets manager\n *\n * @note As there is no universal support for threaded access to the\n * OpenGL context from multiple threads and as its exclusively prohibited\n * in gdx a global asset manager is needed. This asset manager makes it\n * easier to load new assets asynchronously without blocking rendering.\n */\n private static AssetManager assetManager = new AssetManager();\n\n /**\n * Conversion from Box2D to the sprite relative/pixel coordinates\n */\n public static final float BOX_TO_WORLD = 100.0f;\n\n /**\n * Conversion from sprite relative/pixel coordinates to Box2D coordinates\n */\n public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD;\n\n /**\n * Get global static assets manager\n * @return Global asset manager.\n */\n public static AssetManager getAssetManager() {\n return assetManager;\n }\n\n /**\n * Game scoreboard\n */\n public static Scoreboard scoreboard = null;\n\n /**\n * Game pause button\n */\n public static int pauseButton = Keys.P;\n public static int pauseButton1 = Keys.BACK;\n}", "public interface ItemDestruction {\n\n /**\n * Adds specified actor to the destruction list.\n * @param actor Actor that should be destroyed.\n */\n void add(Actor actor);\n\n /**\n * Returns true if and only if the destruction list contains at least one\n * element e such that (o==null ? e==null : o.equals(e)).\n * @param actor element whose presence in this list is to be tested.\n * @return true if this list contains the specified element.\n */\n boolean contains(Actor actor);\n}", "public abstract class DamageModel {\n protected float health;\n\n /**\n * Reset health to a default value.\n */\n public void resetHealth() {\n health = 1f;\n }\n\n /**\n * Set object health.\n * @param health Health in scale 0..1\n */\n public void setHealth(float health) {\n this.health = health;\n }\n\n /**\n * Get object health status.\n * @return Object health in scale 0..1\n */\n public float getHealth() {\n return health;\n }\n\n /**\n * Enemy status.\n * @return true if this body is enemy.\n */\n public abstract boolean isEnemy();\n\n /**\n * Collision force\n * @param force value of force in Box2D scale.\n */\n public abstract void hit(float force);\n\n /**\n * Get points earned from destroying this model.\n * @return points.\n */\n public abstract int getPoints();\n\n @Override\n public String toString() {\n return String.format(\"%.2f\", health);\n }\n}", "public class CollisionFilterMasks {\n public static final short GROUND = 0x01;\n public static final short HANS_BODY = 0x02;\n public static final short HANS_HAND = 0x04;\n public static final short GRENADE = 0x08;\n /**\n * Other than listed here.\n */\n public static final short OTHER = 0x16;\n /**\n * All bodies.\n */\n public static final short ALL = 0xff;\n}", "public interface Destructible {\n /**\n * Get damage model of this object\n * @return Damage model\n */\n DamageModel getDatamageModel();\n\n /**\n * Set body as destroyed\n *\n * This information can be used for sprite rendering.\n */\n void setDestroyed();\n\n /**\n * Get destroyed status\n */\n boolean isDestroyed();\n\n /**\n * Get Box2D body\n *\n * This is used to remove body from the world\n * @return Body.\n */\n Body getBody();\n}", "public class Explosion {\n private final Body body;\n private final float maxDistance;\n private final float maxForce;\n private final Vector2 bodyPos = new Vector2();\n private final Vector2 hitBodyPos = new Vector2();\n\n /**\n * Class constructor.\n * @param body the body that sends the shock.\n */\n public Explosion(Body body) {\n this.maxDistance = 9.0f;\n this.maxForce = 80.0f;\n this.body = body;\n }\n\n /**\n * Class constructor with configurable maximum distance and force.\n * @param body the body that sends the shock.\n * @param maxDist the maximum distance of shock wave.\n * @param maxForce the maximum force applied.\n */\n public Explosion(Body body, float maxDist, float maxForce) {\n this.maxDistance = maxDist;\n this.maxForce = maxForce;\n this.body = body;\n }\n\n /**\n * Emits a shock impulse to the nearby bodies.\n */\n public void doExplosion() {\n /* Set exploding body as static so it won't fly away */\n BodyType origBdType = body.getType();\n body.setType(BodyType.StaticBody);\n\n bodyPos.set(body.getPosition());\n\n body.getWorld().QueryAABB(callback,\n bodyPos.x - maxDistance, bodyPos.y - maxDistance,\n bodyPos.x + maxDistance, bodyPos.y + maxDistance);\n\n /* Restore body type */\n body.setType(origBdType);\n }\n\n private QueryCallback callback = new QueryCallback() {\n @Override\n public boolean reportFixture (Fixture fixture) {\n float force;\n float angle;\n\n Body hitBody = fixture.getBody();\n hitBodyPos.set(hitBody.getPosition());\n\n float distance = body.getPosition().dst(hitBodyPos);\n if (distance <= maxDistance) {\n /* Closer objects should feel greater force */\n force = ((maxDistance - distance) / maxDistance) * maxForce;\n\n angle = MathUtils.atan2(hitBodyPos.y - bodyPos.y, hitBodyPos.x - bodyPos.x);\n /* Apply an impulse to the body, using the angle */\n hitBody.applyLinearImpulse(\n new Vector2(MathUtils.cos(angle) * force,\n MathUtils.sin(angle) * force),\n hitBodyPos);\n }\n return true; /* Keep going until all bodies in the area are checked. */\n }\n };\n}", "public abstract class SlingshotActor extends Actor implements InputProcessor {\n /**\n * Game stage\n */\n private final Stage stage;\n\n /**\n * Maximum mouse joint acceleration.\n */\n private final float a_max;\n /**\n * Applied impulse force.\n */\n private final float F_impulse;\n\n /**\n * Body of the item\n * @note Body is not initialized by this abstract class\n */\n protected Body body;\n\n public static final float touchDst = 10.0f;\n\n /**\n * Slingshot state.\n */\n private boolean slingshotEnabled = true;\n\n /* Input processing/Controls */\n protected MouseJoint mouseJoint = null;\n private final Vector3 testPoint = new Vector3();\n private final Vector2 startPoint = new Vector2();\n /**\n * Temporary target vector.\n */\n private final Vector2 target = new Vector2();\n private final Body groundBody;\n private Body hitBody = null;\n\n /**\n * Constructor for SlingShotActor.\n * @param stage game stage.\n * @param world game (physics) world.\n * @param a_max maximum mouse joint acceleration.\n * @param F_impulse maximum force.\n */\n public SlingshotActor(Stage stage, World world, float a_max, float F_impulse) {\n this.stage = stage;\n this.a_max = a_max;\n this.F_impulse = F_impulse;\n\n /* We also need an invisible zero size ground body\n * to which we can connect the mouse joint */\n BodyDef bodyDef = new BodyDef();\n groundBody = world.createBody(bodyDef);\n }\n\n QueryCallback callback = new QueryCallback() {\n @Override\n public boolean reportFixture (Fixture fixture) {\n /* If the hit point is inside the fixture of the body\n /* we report it\n */\n Vector2 v = fixture.getBody().getPosition();\n if (fixture.testPoint(testPoint.x, testPoint.y) ||\n v.dst(testPoint.x, testPoint.y) < touchDst) {\n hitBody = fixture.getBody();\n if (hitBody.equals(body)) {\n return false;\n }\n }\n return true; /* Keep going until all bodies in the area are checked. */\n }\n };\n\n @Override\n public boolean touchDown(int screenX, int screenY, int pointer, int button) {\n if (slingshotEnabled == false)\n return false;\n\n /* Translate the mouse coordinates to world coordinates */\n stage.getCamera().unproject(testPoint.set(screenX, screenY, 0));\n testPoint.x *= G.WORLD_TO_BOX;\n testPoint.y *= G.WORLD_TO_BOX;\n\n hitBody = null;\n body.getWorld().QueryAABB(callback,\n testPoint.x - 0.0001f,\n testPoint.y - 0.0001f,\n testPoint.x + 0.0001f,\n testPoint.y + 0.0001f);\n if (hitBody == groundBody) hitBody = null;\n\n if (hitBody == null)\n return false;\n\n /* Ignore kinematic bodies, they don't work with the mouse joint */\n if (hitBody.getType() == BodyType.KinematicBody)\n return false;\n\n if (hitBody.equals(this.body)) {\n MouseJointDef def = new MouseJointDef();\n def.bodyA = groundBody;\n def.bodyB = hitBody;\n def.collideConnected = true;\n def.target.set(testPoint.x, testPoint.y);\n def.maxForce = a_max * hitBody.getMass();\n\n startPoint.set(testPoint.x, testPoint.y);\n mouseJoint = (MouseJoint)((body.getWorld()).createJoint(def));\n hitBody.setAwake(true);\n }\n return false;\n }\n\n @Override\n public boolean touchDragged(int x, int y, int pointer) {\n /* If a mouse joint exists we simply update\n * the target of the joint based on the new\n * mouse coordinates\n * */\n if (mouseJoint != null) {\n stage.getCamera().unproject(testPoint.set(x, y, 0));\n testPoint.x = MathUtils.clamp(testPoint.x * G.WORLD_TO_BOX, startPoint.x - 3, startPoint.x + 3);\n testPoint.y = MathUtils.clamp(testPoint.y * G.WORLD_TO_BOX, startPoint.y - 3, startPoint.y + 3);\n mouseJoint.setTarget(target.set(testPoint.x, testPoint.y));\n }\n return false;\n }\n\n @Override public boolean touchUp(int x, int y, int pointer, int button) {\n /* If a mouse joint exists we simply destroy it */\n if (mouseJoint != null) {\n body.getWorld().destroyJoint(mouseJoint);\n mouseJoint = null;\n\n float fx = (startPoint.x - testPoint.x) * F_impulse;\n float fy = (startPoint.y - testPoint.y) * F_impulse;\n hitBody.applyLinearImpulse(new Vector2(fx, fy), hitBody.getPosition());\n\n slingshotRelease();\n }\n return false;\n }\n\n /**\n * Optional tasks to be done after releasing slingshot\n */\n protected abstract void slingshotRelease();\n\n @Override\n public boolean keyDown(int keycode) {\n return false;\n }\n\n @Override\n public boolean keyUp(int keycode) {\n return false;\n }\n\n @Override\n public boolean keyTyped(char character) {\n return false;\n }\n\n @Override\n public boolean mouseMoved(int screenX, int screenY) {\n return false;\n }\n\n @Override\n public boolean scrolled(int amount) {\n return false;\n }\n\n /**\n * Get slingshot state\n * @return true = slingshot enabled, false = slingshot disabled\n */\n public boolean getSlingshotState() {\n return slingshotEnabled;\n }\n\n /**\n * Set slingshot state\n * @param state true = slingshot enabled, false = slingshot disabled\n */\n public void setSlingshotState(boolean state) {\n slingshotEnabled = state;\n }\n\n public Body getBody() {\n return body;\n }\n}", "public class GameStage extends Stage {\n /** Box2D physics world*/\n private final World world;\n /** Item destruction list. */\n private final ItemDestructionList itemDestructor;\n /** Game state object. */\n private final GameState gameState = new GameState();\n /** Width of the current level for clamping. */\n private final float levelWidth;\n\n /* Debug */\n private Box2DDebugRenderer renderer;\n private OrthographicCamera debugCamera;\n\n /* Variables for key commands */\n private class KeyCommands {\n public boolean moveLeft;\n public boolean moveRight;\n public boolean moveUp;\n public boolean moveDown;\n public boolean enableDebugCamera;\n }\n KeyCommands keyCommands = new KeyCommands();\n\n /* Camera Follow */\n private CameraFilter camFilt = new CameraFilter(0.1f, 2.5f, 0.001f);\n private Body cameraFollowBody;\n private boolean destructibleCameraFollowBody = false;\n\n /* Game state related */\n /** Game state update interval */\n private final int gsUpdateInterval = 100;\n /** Game state update counter */\n private int gsCounter = gsUpdateInterval;\n /** Game has ended. true if end of game; otherwise false. */\n private boolean endOfGame = false;\n\n /**\n * This class is used to provide a short delay between physics modeling\n * and damage modeling to allow smooth initialization of physics world\n * as some bodies are spawned in air and this we don't want to cause any\n * initial damage to the bodies.\n */\n private class SetModelContactListener extends Timer.Task {\n @Override\n public void run() {\n ModelContactListener mcl = new ModelContactListener(gameState);\n\n /* \"The listener is owned by you and must remain in scope\", this is\n * bullshit on Java and can be safely ignored. */\n world.setContactListener(mcl);\n }\n }\n\n /**\n * Constructor for GameStage.\n * @param width width of the game stage viewport in pixels\n * @param height height of the game stage viewport in pixels\n * @param levelWidth game world/level width\n */\n public GameStage(float width, float height, float levelWidth) {\n super(width, height, false);\n world = new World(new Vector2(0.0f, -9.8f), true);\n /* TODO It seems that there is some strange static data inside the\n * world which doesn't get cleared even after this stage and world\n * declared here are disposed. This seems to cause strange\n * (gravitational?) forces when new world is created and disposed\n * few times.\n *\n * This could be also a result of varying fps during start up. */\n world.setWarmStarting(true);\n itemDestructor = new ItemDestructionList();\n this.levelWidth = levelWidth;\n\n /* Timer is used to implement a short delay between start of\n * physics modeling and damage modeling to allow bodies hit the ground\n * without any damage. */\n Timer.Task timTsk = new SetModelContactListener();\n Timer tim = new Timer();\n tim.scheduleTask(timTsk, 3.0f); /* sec */\n tim.start();\n\n if (G.DEBUG) {\n renderer = new Box2DDebugRenderer(true, true, true, true, true);\n debugCamera = new OrthographicCamera(\n this.getWidth() * G.WORLD_TO_BOX,\n this.getHeight() * G.WORLD_TO_BOX);\n renderer.setDrawAABBs(false);\n renderer.setDrawJoints(true);\n renderer.setDrawVelocities(true);\n renderer.setDrawBodies(true);\n\n Vector3 pos = this.getCamera().position;\n debugCamera.position.set(pos.x*G.WORLD_TO_BOX, pos.y*G.WORLD_TO_BOX, 0);\n debugCamera.update();\n }\n }\n\n /**\n * Remove destroyed actors/items.\n */\n public void destroyActors() {\n if (!itemDestructor.isEmpty()) {\n Iterator<Actor> it = itemDestructor.getIterator();\n while(it.hasNext()) {\n Actor a = it.next();\n ((Destructible)a).getBody().setUserData(null);\n world.destroyBody(((Destructible)a).getBody());\n a.remove();\n }\n itemDestructor.clear();\n }\n }\n\n @Override\n public void act(float delta) {\n destroyActors();\n world.step(delta, 6, 2);\n super.act(delta);\n }\n\n @Override\n public void draw() {\n super.draw();\n\n if (!keyCommands.enableDebugCamera) {\n updateCameraFollow();\n }\n else {\n updateDebugCamera();\n renderer.render(world, debugCamera.combined);\n }\n\n if (--gsCounter <= 0) {\n gsCounter = gsUpdateInterval;\n if(!gameState.update()) {\n this.endOfGame = true;\n }\n }\n }\n\n /**\n * Set camera follow body.\n * @param body body to follow.\n */\n public void setCameraFollow(Body body) {\n this.cameraFollowBody = body;\n this.destructibleCameraFollowBody = false;\n\n if (body == null)\n return;\n\n if (body.getUserData() != null) {\n if (Destructible.class.isInstance(cameraFollowBody)) {\n destructibleCameraFollowBody = true;\n }\n }\n }\n\n /**\n * Update camera position if camera follow body is set\n */\n private void updateCameraFollow() {\n if (cameraFollowBody == null) {\n return;\n }\n\n if (destructibleCameraFollowBody) {\n if (((Destructible)cameraFollowBody.getUserData()).isDestroyed()) {\n this.cameraFollowBody = null;\n return;\n }\n }\n\n float x = cameraFollowBody.getPosition().x * G.BOX_TO_WORLD;\n float y = cameraFollowBody.getPosition().y * G.BOX_TO_WORLD;\n float dt = Gdx.graphics.getDeltaTime();\n camFilt.updateX(x, dt);\n camFilt.updateY(y, dt);\n\n this.getCamera().position.x = clampX(camFilt.getX());\n this.getCamera().position.y = clampY(camFilt.getY());\n }\n\n /**\n * Updates position of the debug camera\n */\n private void updateDebugCamera() {\n float dx = 0;\n float dy = 0;\n\n if(keyCommands.moveLeft) {\n dx -= 50;\n }\n if(keyCommands.moveRight) {\n dx += 50;\n }\n if(keyCommands.moveDown) {\n dy -= 50;\n }\n if(keyCommands.moveUp) {\n dy += 50;\n }\n\n if(dx != 0 || dy != 0) {\n Vector3 pos = this.getCamera().position;\n float x = clampX(pos.x + dx);\n float y = clampY(pos.y + dy);\n this.getCamera().position.set(x, y, 0);\n debugCamera.position.set(x * G.WORLD_TO_BOX, y * G.WORLD_TO_BOX, 0);\n this.getCamera().update();\n debugCamera.update();\n }\n }\n\n /**\n * Calculate clamp for x axis.\n * @param x position on x axis.\n * @return Clamped value of x axis position.\n */\n private float clampX(float x) {\n return MathUtils.clamp(x, this.getWidth() / 2, levelWidth);\n }\n\n /**\n * Calculate clamp for y axis.\n * @param y position on y axis.\n * @return Clamped value of y axis position.\n */\n private float clampY(float y) {\n return MathUtils.clamp(y, this.getHeight() / 2, this.getHeight() * 1);\n }\n\n /**\n * Get the Box2D world.\n * @return World object.\n */\n public World getWorld() {\n return world;\n }\n\n /**\n * Get item destruction list.\n * @return ItemDestruction object.\n */\n public ItemDestruction getItemDestructionList() {\n return itemDestructor;\n }\n\n /**\n * Get game state object.\n * @return GameState object.\n */\n public GameState getGameState() {\n return gameState;\n }\n\n /**\n * Returns true if game has been ended.\n * @return true if game has been ended.\n */\n public boolean hasGameEnded() {\n return this.endOfGame;\n }\n\n @Override\n public boolean scrolled(int amount) {\n return false;\n }\n\n @Override\n public boolean keyDown(int keycode) {\n if(Gdx.app.getType().equals(ApplicationType.Android)) {\n return false;\n }\n if (G.DEBUG) {\n switch(keycode) {\n case Keys.LEFT:\n keyCommands.moveLeft = true;\n break;\n case Keys.RIGHT:\n keyCommands.moveRight = true;\n break;\n case Keys.UP:\n keyCommands.moveUp = true;\n break;\n case Keys.DOWN:\n keyCommands.moveDown = true;\n break;\n case Keys.D:\n keyCommands.enableDebugCamera = keyCommands.enableDebugCamera ? false : true;\n break;\n case Keys.E:\n endOfGame = true;\n break;\n }\n }\n return false;\n }\n\n @Override\n public boolean keyUp(int keycode) {\n if(Gdx.app.getType().equals(ApplicationType.Android)) {\n return false;\n }\n switch(keycode) {\n case Keys.LEFT:\n keyCommands.moveLeft = false;\n break;\n case Keys.RIGHT:\n keyCommands.moveRight = false;\n break;\n case Keys.UP:\n keyCommands.moveUp = false;\n break;\n case Keys.DOWN:\n keyCommands.moveDown = false;\n break;\n }\n return false;\n }\n\n @Override\n public void dispose () {\n renderer.dispose();\n renderer = null;\n world.dispose();\n }\n}" ]
import aurelienribon.bodyeditor.BodyEditorLoader; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.ParticleEffect; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import fi.hbp.angr.AssetContainer; import fi.hbp.angr.G; import fi.hbp.angr.ItemDestruction; import fi.hbp.angr.logic.DamageModel; import fi.hbp.angr.models.CollisionFilterMasks; import fi.hbp.angr.models.Destructible; import fi.hbp.angr.models.Explosion; import fi.hbp.angr.models.SlingshotActor; import fi.hbp.angr.stage.GameStage;
package fi.hbp.angr.models.actors; /** * A Throwable and explodable grenade model. */ public class Grenade extends SlingshotActor implements Destructible { /** * Name of this model. */ private final static String MODEL_NAME = "grenade"; /** * Texture file path. */ private final static String TEXTURE_PATH = "data/" + MODEL_NAME + ".png"; /** * Sound effect file path. */ private final static String SOUND_FX_PATH = "data/grenade.wav"; /** * Delay between release of grenade and explosion. */ private final static float EXPLOSION_DELAY = 3.0f; /** * Item destruction list. */
private final ItemDestruction itdes;
2
mokies/ratelimitj
ratelimitj-redis/src/test/java/es/moki/ratelimitj/redis/request/RedisSlidingWindowSyncRequestRequestRateLimiterPerformanceTest.java
[ "@ParametersAreNonnullByDefault\npublic class RequestLimitRule {\n\n private final int durationSeconds;\n private final long limit;\n private final int precision;\n private final String name;\n private final Set<String> keys;\n\n private RequestLimitRule(int durationSeconds, long limit, int precision) {\n this(durationSeconds, limit, precision, null);\n }\n\n private RequestLimitRule(int durationSeconds, long limit, int precision, String name) {\n this(durationSeconds, limit, precision, name, null);\n }\n\n private RequestLimitRule(int durationSeconds, long limit, int precision, String name, Set<String> keys) {\n this.durationSeconds = durationSeconds;\n this.limit = limit;\n this.precision = precision;\n this.name = name;\n this.keys = keys;\n }\n\n private static void checkDuration(Duration duration) {\n requireNonNull(duration, \"duration can not be null\");\n if (Duration.ofSeconds(1).compareTo(duration) > 0) {\n throw new IllegalArgumentException(\"duration must be great than 1 second\");\n }\n }\n\n /**\n * Initialise a request rate limit. Imagine the whole duration window as being one large bucket with a single count.\n *\n * @param duration The time the limit will be applied over. The duration must be greater than 1 second.\n * @param limit A number representing the maximum operations that can be performed in the given duration.\n * @return A limit rule.\n */\n public static RequestLimitRule of(Duration duration, long limit) {\n checkDuration(duration);\n if (limit < 0) {\n throw new IllegalArgumentException(\"limit must be greater than zero.\");\n }\n int durationSeconds = (int) duration.getSeconds();\n return new RequestLimitRule(durationSeconds, limit, durationSeconds);\n }\n\n /**\n * Controls (approximate) sliding window precision. A lower duration increases precision and minimises the Thundering herd problem - https://en.wikipedia.org/wiki/Thundering_herd_problem\n *\n * @param precision Defines the time precision that will be used to approximate the sliding window. The precision must be greater than 1 second.\n * @return a limit rule\n */\n public RequestLimitRule withPrecision(Duration precision) {\n checkDuration(precision);\n return new RequestLimitRule(this.durationSeconds, this.limit, (int) precision.getSeconds(), this.name, this.keys);\n }\n\n /**\n * Applies a name to the rate limit that is useful for metrics.\n *\n * @param name Defines a descriptive name for the rule limit.\n * @return a limit rule\n */\n public RequestLimitRule withName(String name) {\n return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, name, this.keys);\n }\n\n /**\n * Applies a key to the rate limit that defines to which keys, the rule applies, empty for any unmatched key.\n *\n * @param keys Defines a set of keys to which the rule applies.\n * @return a limit rule\n */\n public RequestLimitRule matchingKeys(String... keys) {\n Set<String> keySet = keys.length > 0 ? new HashSet<>(Arrays.asList(keys)) : null;\n return matchingKeys(keySet);\n }\n\n /**\n * Applies a key to the rate limit that defines to which keys, the rule applies, null for any unmatched key.\n *\n * @param keys Defines a set of keys to which the rule applies.\n * @return a limit rule\n */\n public RequestLimitRule matchingKeys(Set<String> keys) {\n return new RequestLimitRule(this.durationSeconds, this.limit, this.precision, this.name, keys);\n }\n\n /**\n * @return The limits duration in seconds.\n */\n public int getDurationSeconds() {\n return durationSeconds;\n }\n\n /**\n * @return The limits precision in seconds.\n */\n public int getPrecisionSeconds() {\n return precision;\n }\n\n /**\n * @return The name.\n */\n public String getName() {\n return name;\n }\n\n /**\n * @return The limit.\n */\n public long getLimit() {\n return limit;\n }\n\n /**\n * @return The keys.\n */\n @Nullable\n public Set<String> getKeys() {\n return keys;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || !(o instanceof RequestLimitRule)) {\n return false;\n }\n RequestLimitRule that = (RequestLimitRule) o;\n return durationSeconds == that.durationSeconds\n && limit == that.limit\n && Objects.equals(precision, that.precision)\n && Objects.equals(name, that.name)\n && Objects.equals(keys, that.keys);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(durationSeconds, limit, precision, name, keys);\n }\n}", "public interface RequestRateLimiter {\n\n /**\n * Determine if the given key, after incrementing by one, has exceeded the configured rate limit.\n * @param key key.\n * @return {@code true} if the key is over the limit, otherwise {@code false}\n */\n boolean overLimitWhenIncremented(String key);\n\n /**\n * Determine if the given key, after incrementing by the given weight, has exceeded the configured rate limit.\n * @param key key.\n * @param weight A variable weight.\n * @return {@code true} if the key has exceeded the limit, otherwise {@code false} .\n */\n boolean overLimitWhenIncremented(String key, int weight);\n\n /**\n * Determine if the given key, after incrementing by one, is &gt;= the configured rate limit.\n * @param key key.\n * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} .\n */\n boolean geLimitWhenIncremented(String key);\n\n /**\n * Determine if the given key, after incrementing by the given weight, is &gt;= the configured rate limit.\n * @param key key.\n * @param weight A variable weight.\n * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} .\n */\n boolean geLimitWhenIncremented(String key, int weight);\n\n// /**\n// * Determine if the given key has exceeded the configured rate limit.\n// * @param key key.\n// * @return {@code true} if the key is over the limit, otherwise {@code false}\n// */\n// boolean isOverLimit(String key);\n//\n// /**\n// * Determine if the given key is &gt;= the configured rate limit.\n// * @param key key.\n// * @return {@code true} if the key is &gt;== the limit, otherwise {@code false} .\n// */\n// boolean isGeLimit(String key);\n\n /**\n * Resets the accumulated rate for the given key.\n * @param key key.\n * @return {@code true} if the key existed, otherwise {@code false} .\n */\n boolean resetLimit(String key);\n}", "public interface TimeSupplier {\n\n @Deprecated\n CompletionStage<Long> getAsync();\n\n Mono<Long> getReactive();\n\n /**\n * Get unix time in seconds\n * @return unix time seconds\n */\n long get();\n}", "public class RedisStandaloneConnectionSetupExtension implements\n BeforeAllCallback, AfterAllCallback, AfterEachCallback {\n\n private static RedisClient client;\n private static StatefulRedisConnection<String, String> connect;\n private static RedisReactiveCommands<String, String> reactiveCommands;\n\n @Override\n @SuppressWarnings(\"FutureReturnValueIgnored\")\n public void afterAll(ExtensionContext context) {\n client.shutdownAsync();\n }\n\n @Override\n public void afterEach(ExtensionContext context) {\n connect.sync().flushdb();\n }\n\n @Override\n public void beforeAll(ExtensionContext context) {\n client = RedisClient.create(\"redis://localhost:7006\");\n connect = client.connect();\n reactiveCommands = connect.reactive();\n }\n\n public RedisClient getClient() {\n return client;\n }\n\n public RedisScriptingReactiveCommands<String, String> getScriptingReactiveCommands() {\n return reactiveCommands;\n }\n\n public RedisKeyReactiveCommands<String, String> getKeyReactiveCommands() {\n return reactiveCommands;\n }\n\n}", "public abstract class AbstractSyncRequestRateLimiterPerformanceTest {\n\n private final Logger log = LoggerFactory.getLogger(this.getClass());\n\n private final TimeBanditSupplier timeBandit = new TimeBanditSupplier();\n\n protected abstract RequestRateLimiter getRateLimiter(Set<RequestLimitRule> rules, TimeSupplier timeSupplier);\n\n @Test\n void shouldLimitDualWindowSyncTimed() {\n\n Stopwatch watch = Stopwatch.createStarted();\n\n ImmutableSet<RequestLimitRule> rules =\n ImmutableSet.of(RequestLimitRule.of(Duration.ofSeconds(2), 100), RequestLimitRule.of(Duration.ofSeconds(10), 100));\n RequestRateLimiter requestRateLimiter = getRateLimiter(rules, timeBandit);\n Random rand = new Random();\n\n int total = 10_000;\n IntStream.rangeClosed(1, total).map(i -> rand.nextInt(128)).forEach(value -> {\n timeBandit.addUnixTimeMilliSeconds(200L);\n requestRateLimiter.overLimitWhenIncremented(\"ip:127.0.0.\" + value);\n });\n\n double transactionsPerSecond = Math.ceil((double) total / watch.elapsed(TimeUnit.MILLISECONDS) * 1000);\n\n log.info(\"total time {} checks {}/sec\", watch.stop(), NumberFormat.getNumberInstance(Locale.US).format(transactionsPerSecond));\n }\n\n}" ]
import es.moki.ratelimitj.core.limiter.request.RequestLimitRule; import es.moki.ratelimitj.core.limiter.request.RequestRateLimiter; import es.moki.ratelimitj.core.time.TimeSupplier; import es.moki.ratelimitj.redis.extensions.RedisStandaloneConnectionSetupExtension; import es.moki.ratelimitj.test.limiter.request.AbstractSyncRequestRateLimiterPerformanceTest; import io.lettuce.core.RedisClient; import io.lettuce.core.api.StatefulRedisConnection; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.RegisterExtension; import java.util.Set;
package es.moki.ratelimitj.redis.request; public class RedisSlidingWindowSyncRequestRequestRateLimiterPerformanceTest extends AbstractSyncRequestRateLimiterPerformanceTest { @RegisterExtension
static RedisStandaloneConnectionSetupExtension extension = new RedisStandaloneConnectionSetupExtension();
3
GoogleCloudPlatform/healthcare-api-dicom-fuse
src/test/java/com/google/dicomwebfuse/AppMountProcessTest.java
[ "public interface FuseDao {\n\n List<DicomStore> getAllDicomStores(QueryBuilder queryBuilder) throws DicomFuseException;\n DicomStore getSingleDicomStore(QueryBuilder queryBuilder) throws DicomFuseException;\n List<Study> getStudies(QueryBuilder queryBuilder) throws DicomFuseException;\n Study getSingleStudy(QueryBuilder queryBuilder) throws DicomFuseException;\n List<Series> getSeries(QueryBuilder queryBuilder) throws DicomFuseException;\n Series getSingleSeries(QueryBuilder queryBuilder) throws DicomFuseException;\n List<Instance> getInstances(QueryBuilder queryBuilder) throws DicomFuseException;\n Instance getSingleInstance(QueryBuilder queryBuilder) throws DicomFuseException;\n\n void downloadInstance(QueryBuilder queryBuilder) throws DicomFuseException;\n void uploadInstance(QueryBuilder queryBuilder) throws DicomFuseException;\n void deleteInstance(QueryBuilder queryBuilder) throws DicomFuseException;\n void createDicomStore(QueryBuilder queryBuilder) throws DicomFuseException;\n void deleteDicomStore(QueryBuilder queryBuilder) throws DicomFuseException;\n}", "public class DicomFuseException extends Exception {\n\n private int statusCode;\n\n public DicomFuseException(String message) {\n super(message);\n }\n\n public DicomFuseException(String message, Exception e) {\n super(message, e);\n }\n\n public DicomFuseException(Exception e) {\n super(e);\n }\n\n public DicomFuseException(String message, int statusCode) {\n super(message);\n this.statusCode = statusCode;\n }\n\n public int getStatusCode() {\n return statusCode;\n }\n}", "public class DicomFuse extends FuseStubFS {\n\n private static final Logger LOGGER = LogManager.getLogger();\n private final DicomFuseHelper dicomFuseHelper;\n private final Parameters parameters;\n private final DicomPathParser dicomPathParser;\n private final OS os;\n\n public DicomFuse(Parameters parameters) {\n this.parameters = parameters;\n DicomPathCacher dicomPathCacher = new DicomPathCacher();\n Cache cache = new Cache();\n dicomFuseHelper = new DicomFuseHelper(parameters, dicomPathCacher, cache);\n dicomPathParser = new DicomPathParser(dicomPathCacher);\n os = parameters.getOs();\n }\n\n @Override\n public int getattr(String path, FileStat fileStat) {\n LOGGER.debug(\"getattr \" + path);\n DicomPath dicomPath;\n try {\n dicomFuseHelper.checkPath(path);\n dicomPath = dicomPathParser.parsePath(path);\n } catch (DicomFuseException e) {\n return -ErrorCodes.ENOENT();\n }\n try {\n dicomFuseHelper.checkExistingObject(dicomPath);\n dicomFuseHelper.setAttr(dicomPath, this, fileStat);\n } catch (DicomFuseException e) {\n LOGGER.debug(\"getattr error\", e);\n return -ErrorCodes.ENOENT();\n }\n return 0;\n }\n\n @Override\n public int readdir(String path, Pointer buf, FuseFillDir filler, @off_t long offset,\n FuseFileInfo fi) {\n LOGGER.debug(\"readdir \" + path);\n filler.apply(buf, \".\", null, 0); // add default folder\n filler.apply(buf, \"..\", null, 0); // add default folder\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n dicomFuseHelper.fillFolder(dicomPath, buf, filler);\n } catch (DicomFuseException e) {\n LOGGER.error(\"readdir error\", e);\n return -ErrorCodes.ENOENT();\n }\n return 0;\n }\n\n @Override\n public int opendir(String path, FuseFileInfo fi) {\n LOGGER.debug(\"opendir \" + path);\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n dicomFuseHelper.updateDir(dicomPath);\n } catch (DicomFuseException e) {\n LOGGER.error(\"opendir error\", e);\n return -ErrorCodes.ENOENT();\n }\n return 0;\n }\n\n @Override\n public int read(String path, Pointer buf, @size_t long size, @off_t long offset,\n FuseFileInfo fi) {\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n return dicomFuseHelper.readInstance(dicomPath, buf, (int) size, offset);\n } catch (DicomFuseException e) {\n LOGGER.error(\"read error\", e);\n return -ErrorCodes.EIO();\n }\n }\n\n @Override\n public int write(String path, Pointer buf, long size, long offset, FuseFileInfo fi) {\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n return dicomFuseHelper.writeInstance(dicomPath, buf, (int) size, offset);\n } catch (DicomFuseException e) {\n LOGGER.error(\"write error\", e);\n return -ErrorCodes.EIO();\n }\n }\n\n @Override\n public int open(String path, FuseFileInfo fi) {\n LOGGER.debug(\"open \" + path);\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n dicomFuseHelper.cacheInstanceData(dicomPath);\n } catch (DicomFuseException e) {\n LOGGER.error(\"open error\", e);\n return -ErrorCodes.EIO();\n }\n return 0;\n }\n\n @Override\n public int flush(String path, FuseFileInfo fi) {\n LOGGER.debug(\"flush \" + path);\n try {\n dicomFuseHelper.checkPath(path);\n } catch (DicomFuseException e) {\n LOGGER.debug(e);\n return -ErrorCodes.ENOENT();\n }\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n dicomFuseHelper.flushInstance(dicomPath);\n } catch (DicomFuseException e) {\n LOGGER.error(\"flush error\", e);\n if (os == LINUX) {\n // \"Remote I/O error\" in Linux but in macOS \"Unknown error: 121\"\n return -ErrorCodes.EREMOTEIO();\n } else {\n // \"Input/output error\" in macOS\n return -ErrorCodes.EIO();\n }\n }\n return 0;\n }\n\n @Override\n public int create(String path, long mode, FuseFileInfo fi) {\n LOGGER.debug(\"create \" + path);\n try {\n dicomFuseHelper.checkPath(path);\n } catch (DicomFuseException e) {\n LOGGER.debug(e);\n return -ErrorCodes.ENOENT();\n }\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path, Command.CREATE);\n dicomFuseHelper.createTemporaryInstance(dicomPath);\n } catch (DicomFuseException e) {\n LOGGER.error(\"create error\", e);\n return -ErrorCodes.EIO();\n }\n return 0;\n }\n\n @Override\n public int unlink(String path) {\n LOGGER.debug(\"unlink \" + path);\n if (parameters.isEnableDeletion()) {\n try {\n dicomFuseHelper.checkPath(path);\n } catch (DicomFuseException e) {\n LOGGER.debug(e);\n return -ErrorCodes.ENOENT();\n }\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n // Before creating a file in macOS, unlink method will be called for checking the existence\n // of the file\n if (dicomPath.getDicomPathLevel() != DicomPathLevel.INSTANCE) {\n return -ErrorCodes.ENOENT();\n }\n dicomFuseHelper.unlinkInstance(dicomPath);\n } catch (DicomFuseException e) {\n LOGGER.error(\"unlink error\", e);\n return -ErrorCodes.EIO();\n }\n }\n return 0;\n }\n\n @Override\n public int mkdir(String path, long mode) {\n LOGGER.debug(\"mkdir \" + path);\n try {\n dicomFuseHelper.checkPath(path);\n } catch (DicomFuseException e) {\n LOGGER.debug(e);\n return -ErrorCodes.EPERM();\n }\n try {\n DicomPath dicomPath = dicomPathParser.parsePath(path);\n dicomFuseHelper.createDicomStoreInDataset(dicomPath);\n } catch (DicomFuseException e) {\n LOGGER.error(\"mkdir error\", e);\n return -ErrorCodes.EPERM();\n }\n return 0;\n }\n\n @Override\n public int rename(String oldPath, String newPath) {\n // See: http://man7.org/linux/man-pages/man2/rename.2.html\n LOGGER.debug(\"rename \" + oldPath + \" to \" + newPath);\n try {\n DicomPath oldDicomPath = dicomPathParser.parsePath(oldPath);\n DicomPath newDicomPath = dicomPathParser.parsePath(newPath);\n dicomFuseHelper.renameDicomStoreInDataset(oldDicomPath, newDicomPath);\n } catch (DicomFuseException e) {\n LOGGER.error(\"rename error\", e);\n return -ErrorCodes.ENOENT();\n }\n return 0;\n }\n\n @Override\n public int statfs(String path, Statvfs stbuf) {\n if (os == WINDOWS || os == DARWIN) {\n if (\"/\".equals(path)) {\n stbuf.f_bsize.set(4096); // file system block size\n stbuf.f_frsize.set(1024 * 1024); // fragment size\n stbuf.f_blocks.set(1024 * 1024); // total data blocks in file system\n stbuf.f_bfree.set(1024 * 1024); // free blocks in fs\n stbuf.f_bavail.set(1024 * 1024); // free blocks for non-root\n }\n }\n return super.statfs(path, stbuf);\n }\n\n // When auto_xattr option used may cause the error in the terminal - \"Could not copy extended\n // attributes. Operation not permitted\". Instead auto_xattr option, these methods were implemented\n // but do nothing.\n // See: https://github.com/osxfuse/osxfuse/issues/363\n @Override\n public int setxattr(String path, String name, Pointer value, long size, int flags) {\n return super.setxattr(path, name, value, size, flags);\n }\n\n @Override\n public int getxattr(String path, String name, Pointer value, long size) {\n return super.getxattr(path, name, value, size);\n }\n\n @Override\n public int listxattr(String path, Pointer list, long size) {\n return super.listxattr(path, list, size);\n }\n\n @Override\n public int removexattr(String path, String name) {\n return super.removexattr(path, name);\n }\n\n // methods do nothing, but needs to be implemented for correct work some programs\n @Override\n public int truncate(String path, long size) {\n return super.truncate(path, size);\n }\n\n @Override\n public int chown(String path, long uid, long gid) {\n return super.chown(path, uid, gid);\n }\n\n @Override\n public int chmod(String path, long mode) {\n return super.chmod(path, mode);\n }\n}", "public class Parameters {\n\n private final FuseDao fuseDAO;\n private final CloudConf cloudConf;\n private final CacheTime cacheTime;\n private final long cacheSize;\n private final boolean enableDeletion;\n private final OS os;\n\n public Parameters(FuseDao fuseDAO, Arguments arguments, OS os) {\n this.fuseDAO = fuseDAO;\n this.cloudConf = arguments.cloudConf;\n this.cacheTime = arguments.cacheTime;\n this.cacheSize = arguments.cacheSize;\n this.enableDeletion = arguments.enableDeletion;\n this.os = os;\n }\n\n public FuseDao getFuseDAO() {\n return fuseDAO;\n }\n\n public CloudConf getCloudConf() {\n return cloudConf;\n }\n\n public CacheTime getCacheTime() {\n return cacheTime;\n }\n\n public long getCacheSize() {\n return cacheSize;\n }\n\n boolean isEnableDeletion() {\n return enableDeletion;\n }\n\n OS getOs() {\n return os;\n }\n}", "public class Arguments {\n\n @Parameter(\n names = {\"--datasetAddr\", \"-a\"},\n descriptionKey = \"option.datasetAddr\",\n required = true,\n order = 0,\n converter = CloudConfigurationConverter.class\n )\n public CloudConf cloudConf;\n\n @Parameter(\n names = {\"--mountPath\", \"-p\"},\n descriptionKey = \"option.mountPath\",\n required = true,\n order = 1,\n converter = PathConverter.class\n )\n public Path mountPath;\n\n @Parameter(\n names = {\"--cacheTime\", \"-t\"},\n descriptionKey = \"option.cacheTime\",\n converter = CacheTimeConverter.class,\n order = 2,\n validateWith = CacheTimePositiveValidator.class\n )\n public CacheTime cacheTime = new CacheTime(60, 300);\n\n @Parameter(\n names = {\"--cacheSize\", \"-s\"},\n descriptionKey = \"option.cacheSize\",\n converter = LongConverter.class,\n order = 3,\n validateWith = CacheSizePositiveValidator.class\n )\n public long cacheSize = 10000;\n\n @Parameter(\n names = {\"--enableDeletion\", \"-d\"},\n descriptionKey = \"option.enableDeletion\",\n order = 4,\n converter = BooleanConverter.class\n )\n public boolean enableDeletion = true;\n\n @Parameter(\n names = {\"--keyFile\", \"-k\"},\n descriptionKey = \"option.keyFile\",\n order = 5,\n converter = PathConverter.class\n )\n public Path keyPath;\n\n @Parameter(\n names = {\"--extraMountOptions\"},\n descriptionKey = \"option.extraMountOptions\",\n order = 6\n )\n public List<String> extraMountOptions = new ArrayList<>();\n\n @Parameter(\n names = {\"--help\", \"-h\"},\n help = true,\n descriptionKey = \"option.help\",\n order = 7\n )\n public boolean help = false;\n}" ]
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.ArgumentMatchers.any; import com.google.dicomwebfuse.dao.FuseDao; import com.google.dicomwebfuse.exception.DicomFuseException; import com.google.dicomwebfuse.fuse.DicomFuse; import com.google.dicomwebfuse.fuse.Parameters; import com.google.dicomwebfuse.parser.Arguments; import java.io.IOException; import java.util.Arrays; import java.util.List; import jnr.ffi.Platform; import jnr.ffi.Platform.OS; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito;
// Copyright 2019 Google LLC // // 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 com.google.dicomwebfuse; class AppMountProcessTest { private static OS systemOs; @BeforeAll static void setup() { systemOs = Platform.getNativePlatform().getOS(); } @Test void testShouldReturnExceptionIfUserDoesNotHaveAccessToAnDataset() throws DicomFuseException { // Given Arguments arguments = new Arguments(); // Setting OS OS os = OS.LINUX;
FuseDao fuseDao = Mockito.mock(FuseDao.class);
0
gentoku/pinnacle-api-client
src/pinnacle/api/dataobjects/Fixtures.java
[ "public class Json {\n\n\tprivate JsonObject jsonObject;\n\n\t/**\n\t * Private constructor by JsonObject.\n\t * \n\t * @param json\n\t */\n\tprivate Json(JsonObject jsonObject) {\n\t\tthis.jsonObject = jsonObject;\n\t}\n\n\t/**\n\t * Factory\n\t * \n\t * @param text\n\t * @return\n\t * @throws PinnacleException\n\t */\n\tpublic static Json of(String text) throws PinnacleException {\n\t\ttry {\n\t\t\tJsonObject jsonObject = new Gson().fromJson(text, JsonObject.class);\n\t\t\tJson json = new Json(jsonObject);\n\t\t\tif (json.isErrorJson())\n\t\t\t\tthrow PinnacleException.errorReturned(200, text);\n\t\t\treturn json;\n\t\t} catch (JsonSyntaxException e) {\n\t\t\tthrow PinnacleException.jsonUnparsable(\"JSON syntax error: \" + text);\n\t\t}\n\t}\n\n\tprivate boolean isErrorJson() {\n\t\treturn this.getAsString(\"code\").isPresent() && this.getAsString(\"message\").isPresent();\n\t}\n\n\tprivate Optional<JsonElement> getElement(String key) {\n\t\treturn Optional.ofNullable(this.jsonObject.get(key));\n\t}\n\n\tpublic Optional<BigDecimal> getAsBigDecimal(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsBigDecimal);\n\t}\n\n\tOptional<BigInteger> getAsBigInteger(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsBigInteger);\n\t}\n\n\tpublic Optional<Boolean> getAsBoolean(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsBoolean);\n\t}\n\n\t/*\n\t * Optional<Byte> getAsByte (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsByte); }\n\t * \n\t * Optional<Character> getAsCharacter (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsCharacter); }\n\t * \n\t * Optional<Double> getAsDouble (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsDouble); }\n\t * \n\t * Optional<Float> getAsFloat (String key) { return\n\t * this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement\n\t * ::getAsFloat); }\n\t */\n\n\tpublic Optional<Integer> getAsInteger(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsInt);\n\t}\n\n\tpublic Optional<Long> getAsLong(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsLong);\n\t}\n\n\t/*\n\t * Optional<Number> getAsNumber (String key) { return\n\t * this.getElement(key).map(JsonElement::getAsNumber); }\n\t * \n\t * Optional<Short> getAsShort (String key) { return\n\t * this.getElement(key).map(JsonElement::getAsShort); }\n\t */\n\n\tpublic Optional<String> getAsString(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString);\n\t}\n\n\tpublic Optional<Json> getAsJson(String key) {\n\t\treturn this.getElement(key).filter(JsonElement::isJsonObject).map(JsonElement::getAsJsonObject).map(Json::new);\n\t}\n\n\tpublic Stream<String> getAsStringStream(String keyOfArray) {\n\t\treturn this.getAsStream(keyOfArray).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString);\n\t}\n\n\tpublic Stream<Json> getAsJsonStream(String keyOfArray) {\n\t\treturn this.getAsStream(keyOfArray).filter(JsonElement::isJsonObject).map(JsonElement::getAsJsonObject)\n\t\t\t\t.map(Json::new);\n\t}\n\n\tprivate Stream<JsonElement> getAsStream(String keyOfArray) {\n\t\treturn this.getElement(keyOfArray).filter(JsonElement::isJsonArray).map(this::toStream).orElse(Stream.empty());\n\t}\n\n\t/**\n\t * Converts an array of JsonElements to stream of JsonElements.\n\t * \n\t * @param element\n\t * - must be JsonArray\n\t * @return\n\t */\n\tprivate Stream<JsonElement> toStream(JsonElement element) {\n\t\tJsonArray array = element.getAsJsonArray();\n\t\tSpliterator<JsonElement> spliterator = Spliterators.spliterator(array.iterator(), array.size(), 64);\n\t\treturn StreamSupport.stream(spliterator, true); // true for parallel\n\t}\n}", "@SuppressWarnings(\"serial\")\npublic class PinnacleException extends IOException {\n\n\tenum TYPE {\n\t\tCONNECTION_FAILED, ERROR_RETURNED, PARAMETER_INVALID, JSON_UNPARSABLE;\n\t}\n\n\tprivate TYPE errorType;\n\n\tpublic TYPE errorType() {\n\t\treturn this.errorType;\n\t}\n\n\tprivate String errorJson;\n\n\tpublic String errorJson() {\n\t\treturn this.errorJson;\n\t}\n\n\t/*\n\t * public GenericException parsedErrorJson () throws PinnacleException {\n\t * return GenericException.parse(this.errorJson); }\n\t */\n\tprivate int statusCode;\n\n\tpublic int statusCode() {\n\t\treturn this.statusCode;\n\t}\n\n\tprivate String unparsableJson;\n\n\tpublic String unparsableJson() {\n\t\treturn this.unparsableJson;\n\t}\n\n\tprivate PinnacleException(String message, TYPE errorType) {\n\t\tsuper(message);\n\t\tthis.errorType = errorType;\n\t}\n\n\tstatic PinnacleException connectionFailed(String message) {\n\t\treturn new PinnacleException(message, TYPE.CONNECTION_FAILED);\n\t}\n\n\tstatic PinnacleException errorReturned(int statusCode, String errorJson) {\n\t\tPinnacleException ex = new PinnacleException(\"API returned an error response:[\" + statusCode + \"] \" + errorJson,\n\t\t\t\tTYPE.ERROR_RETURNED);\n\t\tex.statusCode = statusCode;\n\t\tex.errorJson = errorJson;\n\t\treturn ex;\n\t}\n\n\tstatic PinnacleException parameterInvalid(String message) {\n\t\treturn new PinnacleException(message, TYPE.PARAMETER_INVALID);\n\t}\n\n\tstatic PinnacleException jsonUnparsable(String unparsableJson) {\n\t\tPinnacleException ex = new PinnacleException(\"Couldn't parse JSON: \" + unparsableJson, TYPE.JSON_UNPARSABLE);\n\t\tex.unparsableJson = unparsableJson;\n\t\treturn ex;\n\t}\n}", "public enum EVENT_STATUS {\n\n\tLINES_UNAVAILABLE_TEMPORARILY(\"H\"),\n\tLINES_WITH_RED_CIRCLE(\"I\"),\n\tLINES_OPEN_FOR_BETTING(\"O\"),\n\tUNDEFINED(\"undefined\");\n\n\tprivate final String value;\n\t\n\tprivate EVENT_STATUS (final String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic String toAPI () {\n\t\treturn this.value;\n\t}\n\t\n\tpublic static EVENT_STATUS fromAPI (String value) {\n\t\treturn Arrays.stream(EVENT_STATUS.values())\n\t\t .filter(e -> e.value.equals(value))\n\t\t .findAny()\n\t\t .orElse(EVENT_STATUS.UNDEFINED);\n\t}\n}", "public enum LIVE_STATUS {\n\n\tNO_LIVE_BETTING(\"0\"),\n\tLIVE_BETTING(\"1\"),\n\tWILL_BE_OFFERED(\"2\"),\n\tUNDEFINED(\"undefined\");\n\n\tprivate final String value;\n\t\n\tprivate LIVE_STATUS (final String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic String toAPI () {\n\t\treturn this.value;\n\t}\n\t\n\tpublic static LIVE_STATUS fromAPI (String value) {\n\t\treturn Arrays.stream(LIVE_STATUS.values())\n\t\t .filter(e -> e.value.equals(value))\n\t\t .findAny()\n\t\t .orElse(LIVE_STATUS.UNDEFINED);\n\t}\n}", "public enum PARLAY_RESTRICTION {\n\n\tALLOWED_WITHOUT_RESTRICTIONS(\"0\"),\n\tNOT_ALLOWED(\"1\"),\n\tALLOWED_WITH_RESTRICTIONS(\"2\"),\n\tUNDEFINED(\"undefined\");\n\n\tprivate final String value;\n\t\n\tprivate PARLAY_RESTRICTION (final String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic String toAPI () {\n\t\treturn this.value;\n\t}\n\t\n\tpublic static PARLAY_RESTRICTION fromAPI (String value) {\n\t\treturn Arrays.stream(PARLAY_RESTRICTION.values())\n\t\t .filter(e -> e.value.equals(value))\n\t\t .findAny()\n\t\t .orElse(PARLAY_RESTRICTION.UNDEFINED);\n\t}\n}" ]
import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import pinnacle.api.Json; import pinnacle.api.PinnacleException; import pinnacle.api.enums.EVENT_STATUS; import pinnacle.api.enums.LIVE_STATUS; import pinnacle.api.enums.PARLAY_RESTRICTION;
package pinnacle.api.dataobjects; public class Fixtures extends AbstractDataObject { private Integer sportId; public Integer sportId() { return this.sportId; } private Long last; public Long last() { return this.last; } private List<League> league = new ArrayList<>(); public List<League> league() { return this.league; } public Stream<League> leagueAsStream() { return this.league.stream(); } private Fixtures(Json json) { this.sportId = json.getAsInteger("sportId").orElse(null); this.last = json.getAsLong("last").orElse(null); this.league = json.getAsJsonStream("league").map(League::new).collect(Collectors.toList()); this.checkRequiredKeys(); } private Fixtures() { this.isEmpty = true; } public static Fixtures parse(String jsonText) throws PinnacleException { return jsonText.equals("{}") ? new Fixtures() : new Fixtures(Json.of(jsonText)); } @Override boolean hasRequiredKeyWithNull() { return this.sportId == null || this.last == null; } @Override public String toString() { return "Fixtures [sportId=" + sportId + ", last=" + last + ", league=" + league + "]"; } public static class League extends AbstractDataObject { private Long id; public Long id() { return this.id; } private List<Event> events = new ArrayList<>(); public List<Event> events() { return this.events; } public Stream<Event> eventsAsStream() { return this.events.stream(); } private League(Json json) { this.id = json.getAsLong("id").orElse(null); this.events = json.getAsJsonStream("events").map(Event::new).collect(Collectors.toList()); this.checkRequiredKeys(); } @Override boolean hasRequiredKeyWithNull() { return this.id == null; } @Override public String toString() { return "League [id=" + id + ", events=" + events + "]"; } } public static class Event extends AbstractDataObject { private Long id; public Long id() { return this.id; } private Instant starts; public Instant starts() { return this.starts; } private String home; public String home() { return this.home; } private String away; public String away() { return this.away; } private String rotNum; public String rotNum() { return this.rotNum; } private Optional<LIVE_STATUS> liveStatus; public Optional<LIVE_STATUS> liveStatus() { return this.liveStatus; }
private EVENT_STATUS status;
2
vy/log4j2-logstash-layout
layout/src/main/java/com/vlkan/log4j2/logstash/layout/LogstashLayout.java
[ "public class EventResolverContext implements TemplateResolverContext<LogEvent, EventResolverContext> {\n\n private final ObjectMapper objectMapper;\n\n private final StrSubstitutor substitutor;\n\n private final int writerCapacity;\n\n private final TimeZone timeZone;\n\n private final Locale locale;\n\n private final FastDateFormat timestampFormat;\n\n private final boolean locationInfoEnabled;\n\n private final boolean stackTraceEnabled;\n\n private final TemplateResolver<Throwable> stackTraceObjectResolver;\n\n private final boolean emptyPropertyExclusionEnabled;\n\n private final Pattern mdcKeyPattern;\n\n private final Pattern ndcPattern;\n\n private final KeyValuePair[] additionalFields;\n\n private final boolean mapMessageFormatterIgnored;\n\n private EventResolverContext(Builder builder) {\n this.objectMapper = builder.objectMapper;\n this.substitutor = builder.substitutor;\n this.writerCapacity = builder.writerCapacity;\n this.timeZone = builder.timeZone;\n this.locale = builder.locale;\n this.timestampFormat = builder.timestampFormat;\n this.locationInfoEnabled = builder.locationInfoEnabled;\n this.stackTraceEnabled = builder.stackTraceEnabled;\n this.stackTraceObjectResolver = stackTraceEnabled\n ? new StackTraceObjectResolver(builder.stackTraceElementObjectResolver)\n : null;\n this.emptyPropertyExclusionEnabled = builder.emptyPropertyExclusionEnabled;\n this.mdcKeyPattern = builder.mdcKeyPattern == null ? null : Pattern.compile(builder.mdcKeyPattern);\n this.ndcPattern = builder.ndcPattern == null ? null : Pattern.compile(builder.ndcPattern);\n this.additionalFields = builder.additionalFields;\n this.mapMessageFormatterIgnored = builder.mapMessageFormatterIgnored;\n }\n\n @Override\n public Class<EventResolverContext> getContextClass() {\n return EventResolverContext.class;\n }\n\n @Override\n public Map<String, TemplateResolverFactory<LogEvent, EventResolverContext, ? extends TemplateResolver<LogEvent>>> getResolverFactoryByName() {\n return EventResolverFactories.getResolverFactoryByName();\n }\n\n @Override\n public ObjectMapper getObjectMapper() {\n return objectMapper;\n }\n\n @Override\n public StrSubstitutor getSubstitutor() {\n return substitutor;\n }\n\n int getWriterCapacity() {\n return writerCapacity;\n }\n\n TimeZone getTimeZone() {\n return timeZone;\n }\n\n Locale getLocale() {\n return locale;\n }\n\n FastDateFormat getTimestampFormat() {\n return timestampFormat;\n }\n\n boolean isLocationInfoEnabled() {\n return locationInfoEnabled;\n }\n\n boolean isStackTraceEnabled() {\n return stackTraceEnabled;\n }\n\n TemplateResolver<Throwable> getStackTraceObjectResolver() {\n return stackTraceObjectResolver;\n }\n\n @Override\n public boolean isEmptyPropertyExclusionEnabled() {\n return emptyPropertyExclusionEnabled;\n }\n\n Pattern getMdcKeyPattern() {\n return mdcKeyPattern;\n }\n\n Pattern getNdcPattern() {\n return ndcPattern;\n }\n\n KeyValuePair[] getAdditionalFields() {\n return additionalFields;\n }\n\n boolean isMapMessageFormatterIgnored() {\n return mapMessageFormatterIgnored;\n }\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public static class Builder {\n\n private ObjectMapper objectMapper;\n\n private StrSubstitutor substitutor;\n\n private int writerCapacity;\n\n private TimeZone timeZone;\n\n private Locale locale;\n\n private FastDateFormat timestampFormat;\n\n private boolean locationInfoEnabled;\n\n private boolean stackTraceEnabled;\n\n private TemplateResolver<StackTraceElement> stackTraceElementObjectResolver;\n\n private boolean emptyPropertyExclusionEnabled;\n\n private String mdcKeyPattern;\n\n private String ndcPattern;\n\n private KeyValuePair[] additionalFields;\n\n private boolean mapMessageFormatterIgnored;\n\n private Builder() {\n // Do nothing.\n }\n\n public Builder setObjectMapper(ObjectMapper objectMapper) {\n this.objectMapper = objectMapper;\n return this;\n }\n\n public Builder setSubstitutor(StrSubstitutor substitutor) {\n this.substitutor = substitutor;\n return this;\n }\n\n public Builder setWriterCapacity(int writerCapacity) {\n this.writerCapacity = writerCapacity;\n return this;\n }\n\n public Builder setTimeZone(TimeZone timeZone) {\n this.timeZone = timeZone;\n return this;\n }\n\n public Builder setLocale(Locale locale) {\n this.locale = locale;\n return this;\n }\n\n public Builder setTimestampFormat(FastDateFormat timestampFormat) {\n this.timestampFormat = timestampFormat;\n return this;\n }\n\n public Builder setLocationInfoEnabled(boolean locationInfoEnabled) {\n this.locationInfoEnabled = locationInfoEnabled;\n return this;\n }\n\n public Builder setStackTraceEnabled(boolean stackTraceEnabled) {\n this.stackTraceEnabled = stackTraceEnabled;\n return this;\n }\n\n public Builder setStackTraceElementObjectResolver(TemplateResolver<StackTraceElement> stackTraceElementObjectResolver) {\n this.stackTraceElementObjectResolver = stackTraceElementObjectResolver;\n return this;\n }\n\n public Builder setEmptyPropertyExclusionEnabled(boolean emptyPropertyExclusionEnabled) {\n this.emptyPropertyExclusionEnabled = emptyPropertyExclusionEnabled;\n return this;\n }\n\n public Builder setMdcKeyPattern(String mdcKeyPattern) {\n this.mdcKeyPattern = mdcKeyPattern;\n return this;\n }\n\n public Builder setNdcPattern(String ndcPattern) {\n this.ndcPattern = ndcPattern;\n return this;\n }\n\n public Builder setAdditionalFields(KeyValuePair[] additionalFields) {\n this.additionalFields = additionalFields;\n return this;\n }\n\n public Builder setMapMessageFormatterIgnored(boolean mapMessageFormatterIgnored) {\n this.mapMessageFormatterIgnored = mapMessageFormatterIgnored;\n return this;\n }\n\n public EventResolverContext build() {\n validate();\n return new EventResolverContext(this);\n }\n\n private void validate() {\n Validate.notNull(objectMapper, \"objectMapper\");\n Validate.notNull(substitutor, \"substitutor\");\n Validate.isTrue(writerCapacity > 0, \"writerCapacity requires a non-zero positive integer\");\n Validate.notNull(timeZone, \"timeZone\");\n Validate.notNull(locale, \"locale\");\n Validate.notNull(timestampFormat, \"timestampFormat\");\n if (stackTraceEnabled) {\n Validate.notNull(stackTraceElementObjectResolver, \"stackTraceElementObjectResolver\");\n }\n }\n\n }\n\n}", "public class StackTraceElementObjectResolverContext implements TemplateResolverContext<StackTraceElement, StackTraceElementObjectResolverContext> {\n\n private final ObjectMapper objectMapper;\n\n private final StrSubstitutor substitutor;\n\n private final boolean emptyPropertyExclusionEnabled;\n\n private StackTraceElementObjectResolverContext(Builder builder) {\n this.objectMapper = builder.objectMapper;\n this.substitutor = builder.substitutor;\n this.emptyPropertyExclusionEnabled = builder.emptyPropertyExclusionEnabled;\n }\n\n @Override\n public Class<StackTraceElementObjectResolverContext> getContextClass() {\n return StackTraceElementObjectResolverContext.class;\n }\n\n @Override\n public Map<String, TemplateResolverFactory<StackTraceElement, StackTraceElementObjectResolverContext, ? extends TemplateResolver<StackTraceElement>>> getResolverFactoryByName() {\n return StackTraceElementObjectResolverFactories.getResolverFactoryByName();\n }\n\n @Override\n public ObjectMapper getObjectMapper() {\n return objectMapper;\n }\n\n @Override\n public StrSubstitutor getSubstitutor() {\n return substitutor;\n }\n\n @Override\n public boolean isEmptyPropertyExclusionEnabled() {\n return emptyPropertyExclusionEnabled;\n }\n\n public static Builder newBuilder() {\n return new Builder();\n }\n\n public static class Builder {\n\n private ObjectMapper objectMapper;\n\n private StrSubstitutor substitutor;\n\n private boolean emptyPropertyExclusionEnabled;\n\n private Builder() {\n // Do nothing.\n }\n\n public Builder setObjectMapper(ObjectMapper objectMapper) {\n this.objectMapper = objectMapper;\n return this;\n }\n\n public Builder setSubstitutor(StrSubstitutor substitutor) {\n this.substitutor = substitutor;\n return this;\n }\n\n public Builder setEmptyPropertyExclusionEnabled(boolean emptyPropertyExclusionEnabled) {\n this.emptyPropertyExclusionEnabled = emptyPropertyExclusionEnabled;\n return this;\n }\n\n public StackTraceElementObjectResolverContext build() {\n validate();\n return new StackTraceElementObjectResolverContext(this);\n }\n\n private void validate() {\n Validate.notNull(objectMapper, \"objectMapper\");\n Validate.notNull(substitutor, \"substitutor\");\n }\n\n }\n\n}", "public interface TemplateResolver<V> {\n\n void resolve(V value, JsonGenerator jsonGenerator) throws IOException;\n\n}", "public enum TemplateResolvers {;\n\n private static final TemplateResolver<?> EMPTY_ARRAY_RESOLVER = (TemplateResolver<Object>) (ignored, jsonGenerator) -> {\n jsonGenerator.writeStartArray();\n jsonGenerator.writeEndArray();\n };\n\n private static final TemplateResolver<?> EMPTY_OBJECT_RESOLVER = (TemplateResolver<Object>) (ignored, jsonGenerator) -> {\n jsonGenerator.writeStartObject();\n jsonGenerator.writeEndObject();\n };\n\n private static final TemplateResolver<?> NULL_NODE_RESOLVER = (TemplateResolver<Object>) (ignored, jsonGenerator) -> jsonGenerator.writeNull();\n\n public static <V, C extends TemplateResolverContext<V, C>> TemplateResolver<V> ofTemplate(C context, String template) {\n\n // Read the template.\n ObjectNode node;\n try {\n node = context.getObjectMapper().readValue(template, ObjectNode.class);\n } catch (IOException error) {\n String message = String.format(\"failed parsing template (template=%s)\", template);\n throw new RuntimeException(message, error);\n }\n\n // Append the additional fields.\n if (context instanceof EventResolverContext) {\n EventResolverContext eventResolverContext = (EventResolverContext) context;\n KeyValuePair[] additionalFields = eventResolverContext.getAdditionalFields();\n if (additionalFields != null) {\n for (KeyValuePair additionalField : additionalFields) {\n node.put(additionalField.getKey(), additionalField.getValue());\n }\n }\n }\n\n // Resolve the template.\n return ofNode(context, node);\n\n }\n\n private static <V, C extends TemplateResolverContext<V, C>> TemplateResolver<V> ofNode(C context, JsonNode node) {\n\n // Check for known types.\n JsonNodeType nodeType = node.getNodeType();\n switch (nodeType) {\n case ARRAY: return ofArrayNode(context, node);\n case OBJECT: return ofObjectNode(context, node);\n case STRING: return ofStringNode(context, node);\n }\n\n // Create constant resolver for the JSON.\n return (ignored, jsonGenerator) -> jsonGenerator.writeTree(node);\n\n }\n\n private static <V, C extends TemplateResolverContext<V, C>> TemplateResolver<V> ofArrayNode(C context, JsonNode arrayNode) {\n\n // Create resolver for each children.\n List<TemplateResolver<V>> itemResolvers = new ArrayList<>();\n for (int itemIndex = 0; itemIndex < arrayNode.size(); itemIndex++) {\n JsonNode itemNode = arrayNode.get(itemIndex);\n TemplateResolver<V> itemResolver = ofNode(context, itemNode);\n itemResolvers.add(itemResolver);\n }\n\n // Short-circuit if the array is empty.\n if (itemResolvers.isEmpty()) {\n @SuppressWarnings(\"unchecked\") TemplateResolver<V> emptyArrayResolver = (TemplateResolver<V>) EMPTY_ARRAY_RESOLVER;\n return emptyArrayResolver;\n }\n\n // Create a parent resolver collecting each child resolver execution.\n return (value, jsonGenerator) -> {\n jsonGenerator.writeStartArray();\n // noinspection ForLoopReplaceableByForEach (avoid iterator instantiation)\n for (int itemResolverIndex = 0; itemResolverIndex < itemResolvers.size(); itemResolverIndex++) {\n TemplateResolver<V> itemResolver = itemResolvers.get(itemResolverIndex);\n itemResolver.resolve(value, jsonGenerator);\n }\n jsonGenerator.writeEndArray();\n };\n\n }\n\n private static <V, C extends TemplateResolverContext<V, C>> TemplateResolver<V> ofObjectNode(C context, JsonNode srcNode) {\n\n // Create resolver for each object field.\n List<String> fieldNames = new ArrayList<>();\n List<TemplateResolver<V>> fieldResolvers = new ArrayList<>();\n Iterator<Map.Entry<String, JsonNode>> srcNodeFieldIterator = srcNode.fields();\n while (srcNodeFieldIterator.hasNext()) {\n Map.Entry<String, JsonNode> srcNodeField = srcNodeFieldIterator.next();\n String fieldName = srcNodeField.getKey();\n JsonNode fieldValue = srcNodeField.getValue();\n TemplateResolver<V> fieldResolver = ofNode(context, fieldValue);\n fieldNames.add(fieldName);\n fieldResolvers.add(fieldResolver);\n }\n\n // Short-circuit if the object is empty.\n int fieldCount = fieldNames.size();\n if (fieldCount == 0) {\n @SuppressWarnings(\"unchecked\") TemplateResolver<V> emptyObjectResolver = (TemplateResolver<V>) EMPTY_OBJECT_RESOLVER;\n return emptyObjectResolver;\n }\n\n // Create a parent resolver collecting each object field resolver execution.\n return (value, jsonGenerator) -> {\n jsonGenerator.writeStartObject();\n for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++) {\n String fieldName = fieldNames.get(fieldIndex);\n TemplateResolver<V> fieldResolver = fieldResolvers.get(fieldIndex);\n jsonGenerator.writeFieldName(fieldName);\n fieldResolver.resolve(value, jsonGenerator);\n }\n jsonGenerator.writeEndObject();\n };\n\n }\n\n private static <V, C extends TemplateResolverContext<V, C>> TemplateResolver<V> ofStringNode(C context, JsonNode textNode) {\n\n // Short-circuit if content is blank and not allowed.\n String fieldValue = textNode.asText();\n if (context.isEmptyPropertyExclusionEnabled() && StringUtils.isEmpty(fieldValue)) {\n @SuppressWarnings(\"unchecked\") TemplateResolver<V> nullNodeResolver = (TemplateResolver<V>) NULL_NODE_RESOLVER;\n return nullNodeResolver;\n }\n\n // Try to resolve the directive as a ${json:xxx} parameter.\n TemplateResolverRequest resolverRequest = readResolverRequest(fieldValue);\n if (resolverRequest != null) {\n TemplateResolverFactory<V, C, ? extends TemplateResolver<V>> resolverFactory =\n context.getResolverFactoryByName().get(resolverRequest.resolverName);\n if (resolverFactory != null) {\n return resolverFactory.create(context, resolverRequest.resolverKey);\n }\n }\n\n // The rest is the fallback template resolver that delegates every other substitution to Log4j. This will be the\n // case for every template value that does not use directives of pattern ${json:xxx}. This additionally serves\n // as a mechanism to resolve values at runtime when this library misses certain resolvers.\n\n // Check if substitution needed at all. (Copied logic from AbstractJacksonLayout.valueNeedsLookup() method.)\n boolean substitutionNeeded = fieldValue.contains(\"${\");\n if (substitutionNeeded) {\n if (EventResolverContext.class.isAssignableFrom(context.getContextClass())) {\n // Use Log4j substitutor with LogEvent.\n return (value, jsonGenerator) -> {\n LogEvent logEvent = (LogEvent) value;\n String replacedText = context.getSubstitutor().replace(logEvent, fieldValue);\n boolean replacedTextExcluded = context.isEmptyPropertyExclusionEnabled() && StringUtils.isEmpty(replacedText);\n if (replacedTextExcluded) {\n jsonGenerator.writeNull();\n } else {\n jsonGenerator.writeString(replacedText);\n }\n };\n } else {\n // Use standalone Log4j substitutor.\n return (value, jsonGenerator) -> {\n String replacedText = context.getSubstitutor().replace(null, fieldValue);\n boolean replacedTextExcluded = context.isEmptyPropertyExclusionEnabled() && StringUtils.isEmpty(replacedText);\n if (replacedTextExcluded) {\n jsonGenerator.writeNull();\n } else {\n jsonGenerator.writeString(replacedText);\n }\n };\n }\n } else {\n // Write the field value as is. (Blank value check has already been done at the top.)\n return (value, jsonGenerator) -> jsonGenerator.writeString(fieldValue);\n }\n\n }\n\n private static TemplateResolverRequest readResolverRequest(String fieldValue) {\n\n // Bail-out if cannot spot the template signature.\n if (!fieldValue.startsWith(\"${json:\") || !fieldValue.endsWith(\"}\")) {\n return null;\n }\n\n // Try to read both resolver name and key.\n int resolverNameStartIndex = 7;\n int fieldNameSeparatorIndex = fieldValue.indexOf(':', resolverNameStartIndex);\n if (fieldNameSeparatorIndex < 0) {\n int resolverNameEndIndex = fieldValue.length() - 1;\n String resolverName = fieldValue.substring(resolverNameStartIndex, resolverNameEndIndex);\n return new TemplateResolverRequest(resolverName, null);\n } else {\n @SuppressWarnings(\"UnnecessaryLocalVariable\")\n int resolverNameEndIndex = fieldNameSeparatorIndex;\n int resolverKeyStartIndex = fieldNameSeparatorIndex + 1;\n int resolverKeyEndIndex = fieldValue.length() - 1;\n String resolverName = fieldValue.substring(resolverNameStartIndex, resolverNameEndIndex);\n String resolverKey = fieldValue.substring(resolverKeyStartIndex, resolverKeyEndIndex);\n return new TemplateResolverRequest(resolverName, resolverKey);\n }\n\n }\n\n private static class TemplateResolverRequest {\n\n private final String resolverName;\n\n private final String resolverKey;\n\n private TemplateResolverRequest(String resolverName, String resolverKey) {\n this.resolverName = resolverName;\n this.resolverKey = resolverKey;\n }\n\n }\n\n}", "public enum AutoCloseables {;\n\n public static void closeUnchecked(AutoCloseable closeable) {\n try {\n closeable.close();\n } catch (Exception error) {\n throw new RuntimeException(error);\n }\n }\n\n}", "public enum ByteBufferDestinations {;\n\n /**\n * Back ported from {@link org.apache.logging.log4j.core.layout.ByteBufferDestinationHelper} introduced in 2.9.\n */\n public static void writeToUnsynchronized(ByteBuffer source, ByteBufferDestination destination) {\n ByteBuffer destBuff = destination.getByteBuffer();\n while (source.remaining() > destBuff.remaining()) {\n int originalLimit = source.limit();\n source.limit(Math.min(source.limit(), source.position() + destBuff.remaining()));\n destBuff.put(source);\n source.limit(originalLimit);\n destBuff = destination.drain(destBuff);\n }\n destBuff.put(source);\n // No drain in the end.\n }\n\n}", "public class ByteBufferOutputStream extends OutputStream {\n\n private final ByteBuffer byteBuffer;\n\n public ByteBufferOutputStream(int byteCount) {\n this.byteBuffer = ByteBuffer.allocate(byteCount);\n }\n\n public ByteBuffer getByteBuffer() {\n return byteBuffer;\n }\n\n @Override\n public void write(int codeInt) {\n byte codeByte = (byte) codeInt;\n byteBuffer.put(codeByte);\n }\n\n @Override\n public void write(byte[] buf) {\n byteBuffer.put(buf);\n }\n\n @Override\n public void write(byte[] buf, int off, int len) {\n byteBuffer.put(buf, off, len);\n }\n\n public byte[] toByteArray() {\n @SuppressWarnings(\"RedundantCast\") // for Java 8 compatibility\n int size = ((Buffer) byteBuffer).position();\n byte[] buffer = new byte[size];\n System.arraycopy(byteBuffer.array(), 0, buffer, 0, size);\n return buffer;\n }\n\n public String toString(Charset charset) {\n // noinspection RedundantCast (for Java 8 compatibility)\n return new String(byteBuffer.array(), 0, ((Buffer) byteBuffer).position(), charset);\n }\n\n}", "public enum Uris {;\n\n public static String readUri(String spec) {\n try {\n return unsafeReadUri(spec);\n } catch (Exception error) {\n String message = String.format(\"failed reading URI (spec=%s)\", spec);\n throw new RuntimeException(message, error);\n }\n }\n\n private static String unsafeReadUri(String spec) throws Exception {\n URI uri = new URI(spec);\n String uriScheme = uri.getScheme().toLowerCase();\n switch (uriScheme) {\n case \"classpath\":\n return readClassPathUri(uri);\n case \"file\":\n return readFileUri(uri);\n default: {\n String message = String.format(\"unknown URI scheme (spec='%s')\", spec);\n throw new IllegalArgumentException(message);\n }\n }\n\n }\n\n private static String readFileUri(URI uri) throws IOException {\n File file = new File(uri);\n try (FileReader fileReader = new FileReader(file)) {\n return consumeReader(fileReader);\n }\n }\n\n private static String readClassPathUri(URI uri) throws IOException {\n String spec = uri.toString();\n String path = spec.substring(\"classpath:\".length());\n URL resource = Uris.class.getClassLoader().getResource(path);\n Validate.notNull(resource, \"could not locate classpath resource (path=%s)\", path);\n try (InputStream inputStream = resource.openStream()) {\n try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {\n return consumeReader(reader);\n }\n }\n }\n\n private static String consumeReader(Reader reader) throws IOException {\n StringBuilder builder = new StringBuilder();\n try (BufferedReader bufferedReader = new BufferedReader(reader)) {\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n builder.append(line);\n }\n }\n return builder.toString();\n }\n\n}" ]
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.vlkan.log4j2.logstash.layout.resolver.EventResolverContext; import com.vlkan.log4j2.logstash.layout.resolver.StackTraceElementObjectResolverContext; import com.vlkan.log4j2.logstash.layout.resolver.TemplateResolver; import com.vlkan.log4j2.logstash.layout.resolver.TemplateResolvers; import com.vlkan.log4j2.logstash.layout.util.AutoCloseables; import com.vlkan.log4j2.logstash.layout.util.ByteBufferDestinations; import com.vlkan.log4j2.logstash.layout.util.ByteBufferOutputStream; import com.vlkan.log4j2.logstash.layout.util.Uris; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.Node; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; import org.apache.logging.log4j.core.config.plugins.PluginConfiguration; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.layout.ByteBufferDestination; import org.apache.logging.log4j.core.lookup.StrSubstitutor; import org.apache.logging.log4j.core.util.Constants; import org.apache.logging.log4j.core.util.KeyValuePair; import org.apache.logging.log4j.core.util.datetime.FastDateFormat; import java.io.IOException; import java.lang.reflect.Method; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.function.Supplier;
.setStackTraceEnabled(builder.stackTraceEnabled) .setStackTraceElementObjectResolver(stackTraceElementObjectResolver) .setEmptyPropertyExclusionEnabled(builder.emptyPropertyExclusionEnabled) .setMdcKeyPattern(builder.mdcKeyPattern) .setNdcPattern(builder.ndcPattern) .setAdditionalFields(builder.eventTemplateAdditionalFields.pairs) .setMapMessageFormatterIgnored(builder.mapMessageFormatterIgnored) .build(); return TemplateResolvers.ofTemplate(resolverContext, eventTemplate); } private static Supplier<LogstashLayoutSerializationContext> createSerializationContextSupplier(Builder builder, ObjectMapper objectMapper) { return LogstashLayoutSerializationContexts.createSupplier( objectMapper, builder.maxByteCount, builder.prettyPrintEnabled, builder.emptyPropertyExclusionEnabled, builder.maxStringLength); } private static String readEventTemplate(Builder builder) { return readTemplate(builder.eventTemplate, builder.eventTemplateUri); } private static String readStackTraceElementTemplate(Builder builder) { return readTemplate(builder.stackTraceElementTemplate, builder.stackTraceElementTemplateUri); } private static String readTemplate(String template, String templateUri) { return StringUtils.isBlank(template) ? Uris.readUri(templateUri) : template; } private static Locale readLocale(String locale) { if (locale == null) { return Locale.getDefault(); } String[] localeFields = locale.split("_", 3); switch (localeFields.length) { case 1: return new Locale(localeFields[0]); case 2: return new Locale(localeFields[0], localeFields[1]); case 3: return new Locale(localeFields[0], localeFields[1], localeFields[2]); } throw new IllegalArgumentException("invalid locale: " + locale); } @Override public String toSerializable(LogEvent event) { LogstashLayoutSerializationContext context = getResetSerializationContext(); try { encode(event, context); return context.getOutputStream().toString(CHARSET); } catch (Exception error) { reloadSerializationContext(context); throw new RuntimeException("failed serializing JSON", error); } } @Override public byte[] toByteArray(LogEvent event) { LogstashLayoutSerializationContext context = getResetSerializationContext(); try { encode(event, context); return context.getOutputStream().toByteArray(); } catch (Exception error) { reloadSerializationContext(context); throw new RuntimeException("failed serializing JSON", error); } } @Override public void encode(LogEvent event, ByteBufferDestination destination) { LogstashLayoutSerializationContext context = getResetSerializationContext(); try { encode(event, context); ByteBuffer byteBuffer = context.getOutputStream().getByteBuffer(); // noinspection RedundantCast (for Java 8 compatibility) ((Buffer) byteBuffer).flip(); // noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (destination) { ByteBufferDestinations.writeToUnsynchronized(byteBuffer, destination); } } catch (Exception error) { reloadSerializationContext(context); throw new RuntimeException("failed serializing JSON", error); } } // Visible for tests. LogstashLayoutSerializationContext getSerializationContext() { return Constants.ENABLE_THREADLOCALS ? serializationContextRef.get() : serializationContextSupplier.get(); } private LogstashLayoutSerializationContext getResetSerializationContext() { LogstashLayoutSerializationContext context; if (Constants.ENABLE_THREADLOCALS) { context = serializationContextRef.get(); context.reset(); } else { context = serializationContextSupplier.get(); } return context; } private void reloadSerializationContext(LogstashLayoutSerializationContext oldContext) { AutoCloseables.closeUnchecked(oldContext); if (Constants.ENABLE_THREADLOCALS) { LogstashLayoutSerializationContext newContext = serializationContextSupplier.get(); serializationContextRef.set(newContext); } } private void encode(LogEvent event, LogstashLayoutSerializationContext context) throws IOException { JsonGenerator jsonGenerator = context.getJsonGenerator(); eventResolver.resolve(event, jsonGenerator); jsonGenerator.flush();
ByteBufferOutputStream outputStream = context.getOutputStream();
6
xoxefdp/farmacia
src/Vista/VistaLaboratorioManejo.java
[ "public class Botonera extends JPanel{ \r\n JButton[] botones;\r\n JPanel cuadroBotonera;\r\n \r\n public Botonera(int botonesBotonera){\r\n cuadroBotonera = new JPanel();\r\n cuadroBotonera.setLayout(new FlowLayout());\r\n \r\n if (botonesBotonera == 2) {\r\n botones = new JButton[2];\r\n botones[0] = new JButton(\"Aceptar\");\r\n cuadroBotonera.add(botones[0]);\r\n botones[1] = new JButton(\"Cancelar\");\r\n cuadroBotonera.add(botones[1]);\r\n }\r\n if (botonesBotonera == 3) {\r\n botones = new JButton[3];\r\n botones[0] = new JButton(\"Incluir\"); \r\n cuadroBotonera.add(botones[0]); \r\n botones[1] = new JButton(\"Modificar\");\r\n cuadroBotonera.add(botones[1]); \r\n botones[2] = new JButton(\"Eliminar\");\r\n cuadroBotonera.add(botones[2]);\r\n }\r\n add(cuadroBotonera);\r\n }\r\n\r\n public void adherirEscucha(int posBoton, ActionListener escucha){\r\n if (posBoton >= 0 && posBoton <= 2){\r\n botones[posBoton].addActionListener(escucha); \r\n }\r\n if (posBoton >= 0 && posBoton <= 1){\r\n botones[posBoton].addActionListener(escucha);\r\n }\r\n }\r\n}\r", "public interface CerrarVentana {\r\n \r\n public abstract void cerrarVentana();\r\n}", "public interface IncluirActualizarEliminar {\r\n \r\n public abstract void incluir();\r\n \r\n public abstract void actualizar();\r\n \r\n public abstract void eliminar(); \r\n}", "public class OyenteActualizar implements ActionListener{\r\n IncluirActualizarEliminar eventoActualizar;\r\n \r\n public OyenteActualizar(IncluirActualizarEliminar accionActualizar){\r\n eventoActualizar = accionActualizar;\r\n }\r\n\r\n @Override\r\n public void actionPerformed(ActionEvent ae) {\r\n eventoActualizar.actualizar();\r\n }\r\n \r\n //El oyente debe manejar un elemento seleccionado por mouse\r\n}", "public class OyenteEliminar implements ActionListener{\r\n IncluirActualizarEliminar eventoEliminar;\r\n \r\n public OyenteEliminar(IncluirActualizarEliminar accionEliminar){\r\n eventoEliminar = accionEliminar;\r\n }\r\n\r\n @Override\r\n public void actionPerformed(ActionEvent ae) {\r\n eventoEliminar.eliminar();\r\n }\r\n \r\n //El oyente debe manejar un elemento seleccionado por mouse\r\n}", "public class OyenteIncluir implements ActionListener{\r\n IncluirActualizarEliminar eventoIncluir;\r\n\r\n public OyenteIncluir(IncluirActualizarEliminar accionIncluir){\r\n eventoIncluir = accionIncluir;\r\n }\r\n \r\n @Override\r\n public void actionPerformed(ActionEvent ae) {\r\n eventoIncluir.incluir();\r\n } \r\n}", "public class TablaDeLaboratorios extends JPanel{\r\n\r\n private Object[] nombreCamposLab, claseCamposLab;\r\n private ModeloDeTabla tablaLabDobleColumna;\r\n private JTable tablaLab;\r\n private TableColumn colDescripcion, colIdLaboratorio;\r\n private Object[] datosLab = new Object[2];\r\n private JTextField campoLab;\r\n private ResultSet resultado;\r\n\r\n public TablaDeLaboratorios(){\r\n\r\n setLayout(new FlowLayout());\r\n setBorder(BorderFactory.createTitledBorder(\"Laboratorios\"));\r\n setOpaque(false);\r\n crearTabla();\r\n }\r\n\r\n final void crearTabla(){\r\n\r\n Object[] nombreCamposLab = {\"Descripcion\", \"\"};\r\n Object[] claseCamposLab = {new String(), 0};\r\n tablaLabDobleColumna = new ModeloDeTabla(nombreCamposLab, claseCamposLab);\r\n campoLab = new JTextField();\r\n campoLab.setEditable(false);\r\n\r\n tablaLab = new JTable(tablaLabDobleColumna);\r\n tablaLab.setPreferredScrollableViewportSize(new Dimension(100,100));\r\n tablaLab.setFillsViewportHeight(false);\r\n colDescripcion = tablaLab.getColumnModel().getColumn(0);\r\n colIdLaboratorio = tablaLab.getColumnModel().getColumn(1);\r\n\r\n colDescripcion.setMinWidth(100);\r\n colDescripcion.setMaxWidth(100);\r\n colDescripcion.setCellEditor(new DefaultCellEditor(campoLab));\r\n colIdLaboratorio.setMinWidth(0);\r\n colIdLaboratorio.setMaxWidth(0);\r\n\r\n JScrollPane scrollPanel = new JScrollPane(tablaLab);\r\n add(scrollPanel);\r\n }\r\n\r\n public void cargarTabla(){\r\n int filas = tablaLab.getRowCount();\r\n\r\n for (int i = 0; i < filas; i++)\r\n tablaLabDobleColumna.removeRow(0);\r\n\r\n datosLab[0] = \"Carga inicial\";\r\n datosLab[1] = \"0\";\r\n tablaLabDobleColumna.addRow(datosLab);\r\n }\r\n\r\n public boolean agregarFila(String nombreLaboratorio){\r\n boolean salidaLimpia = false;\r\n datosLab[0] = nombreLaboratorio;\r\n datosLab[1] = \"0\";\r\n salidaLimpia = true;\r\n tablaLabDobleColumna.addRow(datosLab);\r\n return salidaLimpia;\r\n }\r\n\r\n public boolean modificarFila(String nombreLaboratorio){\r\n boolean salidaLimpia = false;\r\n int fila = tablaLab.getSelectedRow();\r\n\r\n if (fila >= 0){\r\n datosLab[0] = nombreLaboratorio;\r\n tablaLabDobleColumna.setValueAt(nombreLaboratorio, fila, 0);\r\n salidaLimpia = true;\r\n }\r\n return salidaLimpia;\r\n }\r\n\r\n public boolean eliminarFila(){\r\n int fila = tablaLab.getSelectedRow();\r\n boolean salidaLimpia = false;\r\n if (fila >= 0){\r\n int respuesta = JOptionPane.showConfirmDialog(this, \"¿Seguro quiere eliminar a: \" + tablaLabDobleColumna.getValueAt(fila, 0));\r\n if (respuesta == JOptionPane.OK_OPTION){\r\n tablaLabDobleColumna.removeRow(fila);\r\n salidaLimpia = true;\r\n }\r\n }\r\n return salidaLimpia;\r\n }\r\n\r\n public String obtenerDescripcion(){\r\n int fila = tablaLab.getSelectedRow();\r\n if (fila >= 0)\r\n return (String)tablaLab.getValueAt(fila, 0);\r\n else\r\n return null;\r\n }\r\n\r\n public String obtenerId(){\r\n int fila = tablaLab.getSelectedRow();\r\n if (fila >= 0)\r\n return (String)tablaLab.getValueAt(fila, 1);\r\n else\r\n return null;\r\n }\r\n}" ]
import Vista.Formatos.Botonera; import Control.CerrarVentana; import Control.IncluirActualizarEliminar; import Control.OyenteActualizar; import Control.OyenteEliminar; import Control.OyenteIncluir; import Vista.Tablas.TablaDeLaboratorios; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame;
package Vista; /** * * @author José Diaz */ public class VistaLaboratorioManejo extends JFrame implements ActionListener, CerrarVentana, IncluirActualizarEliminar{ private TablaDeLaboratorios tablaLab; private Botonera botoneraLab; public VistaLaboratorioManejo(){ crearVentana(); } final void crearVentana(){ setTitle("Manejo de Laboratorios"); setLayout(new BorderLayout()); tablaLab = new TablaDeLaboratorios(); botoneraLab = new Botonera(3); botoneraLab.adherirEscucha(0, new OyenteIncluir(this)); botoneraLab.adherirEscucha(1, new OyenteActualizar(this));
botoneraLab.adherirEscucha(2, new OyenteEliminar(this));
4
Rai220/Telephoto
app/src/main/java/com/rai220/securityalarmbot/commands/HDPhotoCommand.java
[ "public class BotService extends Service implements MotionDetectorController.MotionDetectorListener, IStartService {\n public static final String TELEPHOTO_SERVICE_STOPPED = \"TELEPHOTO_SERVICE_STOPPED\";\n\n private TelegramService telegramService;\n private BatteryReceiver batteryReceiver;\n private SmsReceiver smsReceiver;\n private CallReceiver callReceiver;\n private final HiddenCamera2 hiddenCamera2 = new HiddenCamera2(this);\n private Observer observer = new Observer();\n private MotionDetectorController detector = new MotionDetectorController();\n private LocationController locationController = new LocationController();\n private SensorListener sensorListener;\n private SensorManager mSensorManager;\n private Sensor mAccelerometer;\n private TimeStatsSaver timeStatsSaver = new TimeStatsSaver();\n private AudioRecordController audioRecordController = new AudioRecordController();\n //private Sensor mTemperature;\n //private Sensor mHumidity;\n //private Sensor mProximity;\n private boolean isSensorStarted = false;\n\n public Handler handler = null;\n public TextToSpeech tts = null;\n public volatile boolean ttsInitialized = false;\n\n private volatile PowerManager.WakeLock wakeLock = null;\n\n @Override\n public void onCreate() {\n super.onCreate();\n L.i(\"Build version: \" + BuildConfig.VERSION_NAME);\n\n subscribeToFirebase();\n\n PrefsController.instance.init(this);\n telegramService = new TelegramService(this);\n telegramService.init(this);\n\n Prefs prefs = PrefsController.instance.getPrefs();\n hiddenCamera2.init(this);\n\n preventSleepMode();\n\n FabricUtils.initFabric(this);\n handler = new Handler(Looper.getMainLooper());\n\n try {\n tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {\n @Override\n public void onInit(int i) {\n ttsInitialized = true;\n }\n });\n } catch (Throwable ex) {\n L.e(\"Error initializing TTS \" + ex.toString());\n }\n\n\n // Runs service in IDDQD mode :)\n Intent notificationIntent = new Intent(this, SettingsActivity.class);\n final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);\n Notification notification = new NotificationCompat.Builder(this)\n .setSmallIcon(R.drawable.icon)\n .setContentTitle(getString(R.string.app_name))\n .setContentText(getString(R.string.bot_running))\n .setContentIntent(pendingIntent).build();\n startForeground(1337, notification);\n\n batteryReceiver = new BatteryReceiver(this);\n registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));\n registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));\n registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_POWER_CONNECTED));\n registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_LOW));\n registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_OKAY));\n\n smsReceiver = new SmsReceiver(this);\n registerReceiver(smsReceiver, new IntentFilter(\"android.provider.Telephony.SMS_RECEIVED\"));\n\n callReceiver = new CallReceiver(getTelegramService());\n registerReceiver(callReceiver, new IntentFilter(\"android.intent.action.PHONE_STATE\"));\n\n FabricUtils.initFabric(this);\n// hiddenCamera.init(this);\n detector.init(hiddenCamera2, this);\n locationController.init(this);\n\n observer.init(hiddenCamera2, telegramService);\n observer.start(prefs.minutesPeriod);\n\n sensorListener = new SensorListener();\n\n mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // Получаем менеджер сенсоров\n mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // Получаем датчик положения\n\n List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);\n L.i(\"---------------------------------------------------\");\n L.i(\"Sensors count: \" + sensors.size());\n for (Sensor s : sensors) {\n L.i(s.getName());\n }\n L.i(\"---------------------------------------------------\");\n\n //todo do not work :(\n// int sensorType;\n\n// mTemperature = mSensorManager.getDefaultSensor(sensorType);\n// if (mTemperature != null) {\n// mSensorManager.registerListener(sensorListener, mTemperature, SensorManager.SENSOR_DELAY_NORMAL);\n// } else {\n// L.i(\"Temperature sensor not support!\");\n// }\n //------------------------------------------------------------------------------------------\n\n// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {\n// mHumidity = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); // Датчик влажности\n// if (mHumidity != null) {\n// mSensorManager.registerListener(sensorListener, mHumidity, SensorManager.SENSOR_DELAY_NORMAL);\n// } else {\n// L.i(\"Humidity sensor not support!\");\n// }\n// }\n\n// mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); // Датчик приближения\n// if (mProximity != null) {\n// mSensorManager.registerListener(sensorListener, mProximity, SensorManager.SENSOR_DELAY_NORMAL);\n// }\n\n prefs.removeOldTimeStats();\n PrefsController.instance.setPrefs(prefs);\n\n timeStatsSaver.start();\n locationController.start();\n\n L.i(\"Service created\");\n Answers.getInstance().logCustom(new CustomEvent(\"Service started!\"));\n }\n\n private void subscribeToFirebase() {\n try {\n //FirebaseMessaging.getInstance().subscribeToTopic(\"bye\");\n } catch (Throwable ex) {\n L.e(ex);\n }\n }\n\n @Override\n public void onStartSuccess() {\n }\n\n @Override\n public void onStartFailed() {\n final BotService botService = this;\n handler.post(new Runnable() {\n @Override\n public void run() {\n Toast.makeText(botService, R.string.error_bot_token, Toast.LENGTH_SHORT).show();\n stopSelf();\n }\n });\n }\n\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n @Override\n public int onStartCommand(final Intent intent, int flags, int startId) {\n if (!PrefsController.instance.hasToken()) {\n Toast.makeText(this, R.string.error_no_bot_token, Toast.LENGTH_LONG).show();\n stopSelf();\n }\n return START_STICKY;\n }\n\n @Override\n public void onDestroy() {\n L.i(\"----- DESTROY service -----\");\n\n try {\n hiddenCamera2.destroy();\n// hiddenCamera.destroy();\n tts.stop();\n tts.shutdown();\n if (telegramService != null) {\n telegramService.stop();\n telegramService.getBot().removeGetUpdatesListener();\n }\n } catch (Throwable ex) {\n L.e(ex);\n }\n\n try {\n if (wakeLock != null) {\n wakeLock.release();\n }\n } catch (Throwable ex) {\n L.e(ex);\n }\n\n// detector.stop();\n timeStatsSaver.stop();\n observer.stop();\n locationController.stop();\n unregisterReceiver(batteryReceiver);\n unregisterReceiver(smsReceiver);\n unregisterReceiver(callReceiver);\n stopSensor();\n L.i(\"Service stopped\");\n\n Intent intent = new Intent(TELEPHOTO_SERVICE_STOPPED);\n LocalBroadcastManager.getInstance(this).sendBroadcast(intent);\n }\n\n public static byte[] buildGif(List<ImageShot> oldShots, Bitmap newBmp) {\n //ArrayList<Bitmap> bitmaps = adapter.getBitmapArray();\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n AnimatedGifEncoder encoder = new AnimatedGifEncoder();\n encoder.start(bos);\n //encoder.setDelay(250);\n for (ImageShot is : oldShots) {\n byte[] imgByte = is.toYuvByteArray();\n Bitmap bmp = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);\n encoder.addFrame(bmp);\n }\n if (newBmp != null) {\n encoder.addFrame(newBmp);\n }\n\n encoder.finish();\n return bos.toByteArray();\n }\n\n @Override\n public void motionDetected(byte[] debug, byte[] real, byte[] oldReal, boolean rareMotion, List<ImageShot> oldShots) {\n Set<Prefs.UserPrefs> listenerUsers = PrefsController.instance.getPrefs().getEventListeners();\n\n Bitmap newBmp = BitmapFactory.decodeByteArray(real, 0, real.length);\n byte[] gif = buildGif(oldShots, newBmp);\n\n\n for (Prefs.UserPrefs user : listenerUsers) {\n //telegramService.sendPhoto(user.lastChatId, gif);\n telegramService.sendDocument(user.lastChatId, gif, \"gif.gif\");\n }\n\n AlarmType currentAlarmType = PrefsController.instance.getPrefs().alarmType;\n if (currentAlarmType.equals(AlarmType.GIF_AND_PHOTO)) {\n PhotoCommand.getPhoto(this, null, null);\n } else if (currentAlarmType.equals(AlarmType.GIF_AND_3_PHOTOS)) {\n PhotoCommand.getPhoto(this, null, null);\n PhotoCommand.getPhoto(this, null, null);\n PhotoCommand.getPhoto(this, null, null);\n }\n }\n\n public void startSensor() {\n SensitivityType sensitivityType = PrefsController.instance.getPrefs().shakeSensitivity;\n sensorListener.init(telegramService, this, sensitivityType);\n int sensorDelay = SENSOR_DELAY_GAME;\n if (sensitivityType.equals(SensitivityType.HIGH)) {\n sensorDelay = SENSOR_DELAY_FASTEST;\n }\n mSensorManager.registerListener(sensorListener, mAccelerometer, sensorDelay);\n isSensorStarted = true;\n }\n\n public void stopSensor() {\n mSensorManager.unregisterListener(sensorListener);\n isSensorStarted = false;\n }\n\n public boolean isSensorStarted() {\n return isSensorStarted;\n }\n\n public HiddenCamera2 getCamera() {\n return hiddenCamera2;\n }\n\n public Observer getObserver() {\n return observer;\n }\n\n public BatteryReceiver getBatteryReceiver() {\n return batteryReceiver;\n }\n\n public TelegramService getTelegramService() {\n return telegramService;\n }\n\n public MotionDetectorController getDetector() {\n return detector;\n }\n\n// public Sensor getTemperature() {\n// return mTemperature;\n// }\n\n public LocationController getLocationController() {\n return locationController;\n }\n\n public AudioRecordController getAudioRecordController() {\n return audioRecordController;\n }\n\n private void preventSleepMode() {\n try {\n PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);\n wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,\n \"MyWakelockTag\");\n wakeLock.acquire();\n } catch (Throwable ex) {\n L.e(ex);\n }\n }\n\n}", "public abstract class CameraTask {\n private final int cameraId;\n private final int w;\n private final int h;\n private final boolean isMd;\n\n public CameraTask(int cameraId) {\n this(cameraId, -1, -1, false);\n }\n\n public CameraTask(int cameraId, int w, int h) {\n this(cameraId, w, h, false);\n }\n\n public CameraTask(int cameraId, int w, int h, boolean isMd) {\n this.cameraId = cameraId;\n this.isMd = isMd;\n\n if (w <= 0 || h <= 0) {\n Prefs prefs = PrefsController.instance.getPrefs();\n Prefs.CameraPrefs cameraPrefs = prefs.getCameraPrefs(cameraId);\n if (cameraPrefs != null && cameraPrefs.width != 0 && cameraPrefs.height != 0) {\n this.w = cameraPrefs.width;\n this.h = cameraPrefs.height;\n } else {\n this.w = 640;\n this.h = 480;\n }\n } else {\n this.w = w;\n this.h = h;\n }\n }\n\n public int getCameraId() {\n return cameraId;\n }\n\n public int getW() {\n return w;\n }\n\n public int getH() {\n return h;\n }\n\n public boolean isMd() {\n return isMd;\n }\n\n abstract public void processResult(ImageShot shot);\n}", "public class ImageShot {\n private int cameraId;\n private byte[] image;\n private Camera.Parameters parameters;\n\n public ImageShot(byte[] image, Camera.Parameters parameters, int cameraId) {\n this.image = image;\n this.parameters = parameters;\n this.cameraId = cameraId;\n }\n\n public int getCameraId() {\n return cameraId;\n }\n\n public byte[] getImage() {\n return image;\n }\n\n public void setImage(byte[] image) {\n this.image = image;\n }\n\n public Camera.Parameters getParameters() {\n return parameters;\n }\n\n public void setParameters(Camera.Parameters parameters) {\n this.parameters = parameters;\n }\n\n public byte[] toGoodQuality() {\n return imgToByte(true);\n }\n\n public byte[] toYuvByteArray() {\n return imgToByte(false);\n }\n\n private byte[] imgToByte(boolean quality) {\n Camera.Parameters parameters = getParameters();\n int width = parameters.getPreviewSize().width;\n int height = parameters.getPreviewSize().height;\n\n YuvImage yuv = new YuvImage(getImage(), parameters.getPreviewFormat(), width, height, null);\n ByteArrayOutputStream out =\n new ByteArrayOutputStream();\n yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);\n\n byte[] compressed = out.toByteArray();\n\n Bitmap newBmp = BitmapFactory.decodeByteArray(compressed, 0, compressed.length);\n Matrix mat = new Matrix();\n mat.postRotate(PrefsController.instance.getPrefs().getCameraPrefs(cameraId).angle);\n newBmp = Bitmap.createBitmap(newBmp, 0, 0, newBmp.getWidth(), newBmp.getHeight(), mat, true);\n ByteArrayOutputStream out2 = new ByteArrayOutputStream();\n if (quality) {\n newBmp.compress(Bitmap.CompressFormat.PNG, 100, out2);\n } else {\n newBmp.compress(Bitmap.CompressFormat.JPEG, 80, out2);\n }\n\n return out2.toByteArray();\n }\n}", "public class Prefs {\n public static final Gson prefsGson = registerDateTime(new GsonBuilder()).create();\n\n /** Пары user-id, user-data */\n private Map<Integer, UserPrefs> usersDataById = new HashMap<>();\n private Map<Integer, CameraPrefs> camerasPrefs = new HashMap<>();\n private List<TimeStats> timeStatsList = new LinkedList<>();\n public int minutesPeriod = 0;\n public CameraMode cameraMode = CameraMode.ALL;\n public CameraMode mdMode = CameraMode.FRONT;\n public MdSwitchType mdSwitchType = MdSwitchType.OFF;\n public SensitivityType sensitivity = SensitivityType.MEDIUM;\n public SensitivityType shakeSensitivity = SensitivityType.LOW;\n public AlarmType alarmType = AlarmType.GIF;\n public String password = \"\";\n\n public boolean hasEventListeners() {\n for (UserPrefs userPref : usersDataById.values()) {\n if (userPref.isEventListener) {\n return true;\n }\n }\n return false;\n }\n\n public Set<UserPrefs> getEventListeners() {\n Set<UserPrefs> result = new HashSet<>();\n for (UserPrefs userPref : usersDataById.values()) {\n if (userPref.isEventListener) {\n result.add(userPref);\n }\n }\n return result;\n }\n\n public CameraPrefs getCameraPrefs(int cameraId) {\n CameraPrefs prefs = camerasPrefs.get(cameraId);\n if (prefs == null) {\n prefs = new CameraPrefs();\n camerasPrefs.put(cameraId, prefs);\n }\n return prefs;\n }\n\n public void setCamerasPrefs(int cameraId, CameraPrefs prefs) {\n this.camerasPrefs.put(cameraId, prefs);\n }\n\n public void addUser(UserPrefs user) {\n usersDataById.put(user.id, user);\n }\n\n public UserPrefs addUser(User user, long chatId) {\n Prefs.UserPrefs newUser = Converters.USER_TO_USERPREFS.apply(user);\n if (newUser != null) {\n newUser.lastChatId = chatId;\n }\n addUser(newUser);\n return newUser;\n }\n\n public UserPrefs getUser(Integer id) {\n return usersDataById.get(id);\n }\n\n public UserPrefs getUser(User user) {\n return usersDataById.get(user.id());\n }\n\n public boolean updateUser(User user) {\n UserPrefs savedUser = getUser(user.id());\n if (savedUser != null) {\n if ((savedUser.userName != null && !savedUser.userName.equals(user.username())) ||\n (savedUser.userName == null && user.username() != null)) {\n long lastChat = savedUser.lastChatId;\n savedUser = Converters.USER_TO_USERPREFS.apply(user);\n if (savedUser != null) {\n savedUser.lastChatId = lastChat;\n }\n addUser(savedUser);\n return true;\n }\n }\n return false;\n }\n\n public Set<UserPrefs> getUsers() {\n Set<UserPrefs> result = new HashSet<>();\n for (UserPrefs user : usersDataById.values()) {\n result.add(user);\n }\n return result;\n }\n\n public void removeRegisterUsers() {\n usersDataById.clear();\n }\n\n public void addTimeStats(TimeStats timeStats) {\n timeStatsList.add(timeStats);\n }\n\n public void removeOldTimeStats() {\n DateTime removeToDate = DateTime.now().withTimeAtStartOfDay().minusWeeks(1);\n Iterator<TimeStats> iter = timeStatsList.iterator();\n while (iter.hasNext()) {\n DateTime dateTime = iter.next().getDateTime();\n if (dateTime.isBefore(removeToDate)) {\n iter.remove();\n } else {\n break;\n }\n }\n }\n\n public List<TimeStats> getTimeStatsList() {\n sortTimeStatsList(timeStatsList);\n return timeStatsList;\n }\n\n public List<TimeStats> getTimeStatsList(DateTime from, DateTime to) {\n List<TimeStats> result = new LinkedList<>();\n if (!from.isAfter(to)) {\n int fromIndex = -1;\n int toIndex = -1;\n sortTimeStatsList(timeStatsList);\n for (TimeStats stat : timeStatsList) {\n if (fromIndex == -1 && !from.isAfter(stat.getDateTime())) {\n fromIndex = timeStatsList.indexOf(stat);\n } else if (stat.getDateTime().isAfter(to)) {\n toIndex = timeStatsList.indexOf(stat);\n break;\n }\n }\n if (fromIndex != -1) {\n if (toIndex == -1 || toIndex > timeStatsList.size()) {\n toIndex = timeStatsList.size();\n }\n result = timeStatsList.subList(fromIndex, toIndex);\n }\n }\n return result;\n }\n\n private void sortTimeStatsList(List<TimeStats> timeStatsList) {\n Collections.sort(timeStatsList, new Comparator<TimeStats>() {\n @Override\n public int compare(TimeStats ts1, TimeStats ts2) {\n return ts1.getDateTime().compareTo(ts2.getDateTime());\n }\n });\n }\n\n public static final class UserPrefs {\n public int id = 0;\n public String userName = null;\n public boolean isNick = false;\n public long lastChatId = 0;\n public boolean isEventListener = true;\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n UserPrefs userPrefs = (UserPrefs) o;\n\n return id == userPrefs.id;\n }\n\n @Override\n public int hashCode() {\n return id;\n }\n }\n\n public static final class CameraPrefs {\n public int height = 0;\n public int width = 0;\n public float angle = 0;\n public String flashMode;\n public String wb;\n }\n}", "public class PrefsController {\n public static final PrefsController instance = new PrefsController();\n\n private static final String PREFS_CODE = \"PREFS_CODE\";\n private static final String TELEGRAM_BOT_TOKEN = \"TELEGRAM_BOT_TOKEN\";\n private static final String AUTORUN = \"AUTORUN\";\n private static final String IS_HELP_SHOWN = \"IS_HELP_SHOWN\";\n private static final String LAST_MD_DETECTED = \"LAST_MD_DETECTED\";\n private static final String IS_PRO = \"IS_PRO\";\n\n private volatile SharedPreferences preferences;\n private volatile Prefs prefs = null;\n\n public synchronized void init(Context context) {\n if (preferences == null) {\n preferences = PreferenceManager.getDefaultSharedPreferences(context);\n }\n }\n\n private PrefsController() {\n }\n\n public boolean hasToken() {\n return !Strings.isNullOrEmpty(getToken());\n }\n\n public String getToken() {\n return preferences.getString(TELEGRAM_BOT_TOKEN, \"\");\n }\n\n public void setToken(String newToken) {\n newToken = newToken.replaceAll(\"\\\\s+\", \"\");\n preferences.edit().putString(TELEGRAM_BOT_TOKEN, newToken).apply();\n }\n\n public boolean isHelpShown() {\n return preferences.getBoolean(IS_HELP_SHOWN, false);\n }\n\n public void setHelpShown(boolean isShown) {\n preferences.edit().putBoolean(IS_HELP_SHOWN, isShown).apply();\n }\n\n public synchronized void setPrefs(Prefs prefs) {\n String toSave = prefsGson.toJson(prefs);\n L.i(\"Writing settings: \" + toSave);\n preferences.edit().putString(PREFS_CODE, toSave).apply();\n this.prefs = prefs;\n }\n\n public synchronized Prefs getPrefs() {\n if (this.prefs == null) {\n String prefsJson = preferences.getString(PREFS_CODE, null);\n L.i(\"Reading settings: \" + prefsJson);\n if (prefsJson == null) {\n prefs = new Prefs();\n } else {\n prefs = prefsGson.fromJson(prefsJson, Prefs.class);\n }\n }\n return prefs;\n }\n\n public void setAutorun(boolean isAutorunEnabled) {\n preferences.edit().putBoolean(AUTORUN, isAutorunEnabled).apply();\n }\n\n public boolean isAutorunEnabled() {\n return preferences.getBoolean(AUTORUN, false);\n }\n\n public void setPassword(String password) {\n Prefs prefs = getPrefs();\n String newPass = null;\n if (!Strings.isNullOrEmpty(password)) {\n password = password.replaceAll(\"\\\\s+\", \"\");\n newPass = password.equals(prefs.password) ? password : FabricUtils.crypt(password);\n }\n if (newPass != null && (prefs.password == null || !newPass.equals(prefs.password))) {\n prefs.removeRegisterUsers();\n }\n prefs.password = newPass;\n setPrefs(prefs);\n }\n\n public String getPassword() {\n return getPrefs().password;\n }\n\n public void updateLastMdDetected() {\n preferences.edit().putLong(LAST_MD_DETECTED, System.currentTimeMillis()).apply();\n }\n\n public long getLastMdDetected() {\n return preferences.getLong(LAST_MD_DETECTED, 0L);\n }\n\n public void makePro() {\n preferences.edit().putBoolean(IS_PRO, true).apply();\n }\n\n public boolean isPro() {\n return preferences.getBoolean(IS_PRO, false);\n }\n\n public void unmakePro() {\n preferences.edit().putBoolean(IS_PRO, false).apply();\n }\n}", "public class FabricUtils {\n private static MessageDigest messageDigest;\n\n static {\n try {\n messageDigest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException ex) {\n L.e(ex);\n }\n }\n\n public static void initFabric(Context context) {\n CrashlyticsCore core = new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build();\n Fabric.with(context, new Crashlytics.Builder().core(core).build());\n Fabric.with(context, new Answers());\n }\n\n public static int[] getAvailableCameras() {\n int[] res = new int[Camera.getNumberOfCameras()];\n for (int i = 0; i < Camera.getNumberOfCameras(); i++) {\n res[i] = i;\n }\n return res;\n }\n\n public static int[] getSelectedCameras() {\n CameraMode cameraMode = PrefsController.instance.getPrefs().cameraMode;\n int[] res;\n if (cameraMode == null || cameraMode == CameraMode.ALL) {\n res = getAvailableCameras();\n } else {\n res = new int[1];\n res[0] = cameraMode.getNumber();\n }\n return res;\n }\n\n public static int[] getSelectedCamerasForMd() {\n CameraMode cameraMode = PrefsController.instance.getPrefs().mdMode;\n int[] res;\n if (cameraMode == null || cameraMode == CameraMode.ALL) {\n res = getAvailableCameras();\n } else {\n res = new int[1];\n res[0] = cameraMode.getNumber();\n }\n return res;\n }\n\n\n public static boolean isAvailable(CameraMode mode) {\n if (mode.equals(CameraMode.ALL)) {\n return true;\n }\n int[] supportedCameras = getAvailableCameras();\n for (int cameraId : supportedCameras) {\n if (cameraId == mode.getNumber()) {\n return true;\n }\n }\n return false;\n }\n\n public static void interruptThread(Thread thread) {\n try {\n if (thread != null && thread.isAlive()) {\n thread.interrupt();\n thread.join(1000);\n L.i(String.format(\"Thread[%s] stopped\", thread.getName()));\n }\n } catch (InterruptedException ignore) {\n } catch (Throwable ex) {\n L.e(ex);\n }\n }\n\n public static String defaultIfBlank(String str, String def) {\n return (str == null || str.trim().length() == 0) ? def : str;\n }\n\n public static String crypt(String pass) {\n byte[] digested = getDigest(pass);\n if (digested != null) {\n StringBuilder sb = new StringBuilder();\n for (byte dig : digested) {\n sb.append(Integer.toHexString(0xff & dig));\n }\n return sb.toString();\n }\n return null;\n }\n\n public static boolean isPassCorrect(String check, String expect) {\n String crypt = crypt(check);\n return Strings.isNullOrEmpty(expect) || (crypt != null && crypt.equals(expect));\n }\n\n private static byte[] getDigest(String pass) {\n byte[] result = null;\n if (messageDigest != null) {\n byte[] passBytes = pass.getBytes();\n messageDigest.reset();\n result = messageDigest.digest(passBytes);\n }\n return result;\n }\n\n public static String getNameByPhone(Context context, String phoneNumber) {\n try {\n String[] projection = new String[]\n {ContactsContract.Data.CONTACT_ID,\n ContactsContract.Contacts.LOOKUP_KEY,\n ContactsContract.Contacts.DISPLAY_NAME,\n ContactsContract.Contacts.STARRED,\n ContactsContract.Contacts.CONTACT_STATUS,\n ContactsContract.Contacts.CONTACT_PRESENCE};\n\n String selection = \"PHONE_NUMBERS_EQUAL(\" +\n ContactsContract.CommonDataKinds.Phone.NUMBER + \",?) AND \" +\n ContactsContract.Data.MIMETYPE + \"='\" +\n ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + \"'\";\n\n String selectionArgs[] = {PhoneNumberUtils.stripSeparators(phoneNumber)};\n\n String name = \"unknown\";\n if (context != null && context.getContentResolver() != null) {\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null);\n } catch (Exception ex) {\n L.e(selection, ex);\n }\n\n if (cursor != null) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n name = cursor.getString(2);\n }\n cursor.close();\n }\n }\n return name;\n } catch (Throwable ex) {\n L.e(ex);\n return \"\";\n }\n }\n\n}", "public class L {\n private static final String TAG = \"SecurityAlarmBot\";\n\n private static final int MAX_LOG_SIZE = 10 * 1000;\n private static final LinkedList<String> logs = new LinkedList<>();\n\n private L() {\n }\n\n public static void e(String error) {\n Log.e(TAG, error);\n saveToLog(\"e\", error);\n }\n\n public static void e(Throwable th) {\n e(null, th);\n }\n\n public static void e(String message, Throwable th) {\n Log.e(TAG, \"\", th);\n StackTraceElement[] stack = th.getStackTrace();\n StackTraceElement lastElement = stack[stack.length - 1];\n String where = lastElement.getClassName() + \":\" + lastElement.getLineNumber();\n Answers.getInstance().logCustom(new CustomEvent(\"Error\").putCustomAttribute(\"error_text\", where));\n if (message != null) {\n Crashlytics.log(message);\n }\n Crashlytics.logException(th);\n\n saveToLog(\"e\", where);\n }\n\n public static void i(Object obj) {\n saveToLog(\"I\", \"\" + obj);\n Log.i(TAG, \"\" + obj);\n }\n\n public static void d(Object obj) {\n Log.d(TAG, \"\" + obj);\n }\n\n public static String logsToString() {\n synchronized (logs) {\n return Joiner.on(\"\\n\").join(logs);\n }\n }\n\n private static void saveToLog(String level, String text) {\n synchronized (logs) {\n logs.addLast(\"\" + System.currentTimeMillis() + \" (\" + level + \") \" + text);\n if (logs.size() > MAX_LOG_SIZE) {\n logs.removeFirst();\n }\n }\n }\n}" ]
import com.pengrad.telegrambot.model.Message; import com.rai220.securityalarmbot.BotService; import com.rai220.securityalarmbot.R; import com.rai220.securityalarmbot.photo.CameraTask; import com.rai220.securityalarmbot.photo.ImageShot; import com.rai220.securityalarmbot.prefs.Prefs; import com.rai220.securityalarmbot.prefs.PrefsController; import com.rai220.securityalarmbot.utils.FabricUtils; import com.rai220.securityalarmbot.utils.L; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package com.rai220.securityalarmbot.commands; /** * */ public class HDPhotoCommand extends AbstractCommand { private final ExecutorService es = Executors.newCachedThreadPool(); public HDPhotoCommand(BotService service) { super(service); } @Override public String getCommand() { return "/hd_photo"; } @Override public String getName() { return "HD Photo"; } @Override public String getDescription() { return "Take a HD photo"; } @Override public boolean isHide() { return true; } @Override public boolean execute(final Message message, Prefs prefs) { es.submit(new Runnable() { @Override public void run() { final Long chatId = message.chat().id(); if (PrefsController.instance.isPro()) { final int[] cameraIds = FabricUtils.getSelectedCameras(); for (int cameraId : cameraIds) {
boolean addTaskResult = botService.getCamera().addTask(new CameraTask(cameraId, 10000, 10000) {
1
comtel2000/jfxvnc
jfxvnc-app/src/main/java/org/jfxvnc/app/presentation/connect/ConnectViewPresenter.java
[ "public class HistoryEntry implements Comparable<HistoryEntry>, Serializable {\n\n private static final long serialVersionUID = 2877392353047511185L;\n\n private final String host;\n private final int port;\n private int securityType;\n private String password;\n private String serverName;\n\n public HistoryEntry(String host, int port) {\n this.host = host;\n this.port = port;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((host == null) ? 0 : host.hashCode());\n result = prime * result + port;\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n HistoryEntry other = (HistoryEntry) obj;\n if (host == null) {\n if (other.host != null) {\n return false;\n }\n } else if (!host.equals(other.host)) {\n return false;\n }\n if (port != other.port) {\n return false;\n }\n return true;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getServerName() {\n return serverName;\n }\n\n public void setServerName(String serverName) {\n this.serverName = serverName;\n }\n\n public String getHost() {\n return host;\n }\n\n public int getPort() {\n return port;\n }\n\n public int getSecurityType() {\n return securityType;\n }\n\n public void setSecurityType(int type) {\n securityType = type;\n }\n\n @Override\n public String toString() {\n return host + \":\" + port + (serverName != null ? \" (\" + serverName + \")\" : \"\");\n }\n\n @Override\n public int compareTo(HistoryEntry o) {\n if (o == null) {\n return 1;\n }\n if (o.equals(this)) {\n return 0;\n }\n if (host != null && o.getHost() != null) {\n int h = host.compareTo(o.getHost());\n if (h == 0 && port != o.getPort()) {\n h = port > o.getPort() ? 1 : -1;\n }\n return h;\n }\n return host != null ? 1 : -1;\n }\n\n}", "public class SessionContext {\n\n private final static org.slf4j.Logger logger = LoggerFactory.getLogger(SessionContext.class);\n\n private String name;\n private Path propPath;\n\n private ObservableList<HistoryEntry> history;\n private ObservableMap<String, Property<?>> bindings;\n\n private final Properties props = new Properties();\n\n private Path streamPath;\n\n public SessionContext() {\n setSession(SessionContext.class.getName());\n }\n\n public void setSession(String name) {\n this.name = name;\n propPath = FileSystems.getDefault().getPath(System.getProperty(\"user.home\"), \".\" + name + \".properties\");\n streamPath = FileSystems.getDefault().getPath(System.getProperty(\"user.home\"), \".\" + name + \".history\");\n }\n\n public Properties getProperties() {\n return props;\n }\n\n public void loadSession() {\n\n if (Files.exists(propPath, LinkOption.NOFOLLOW_LINKS)) {\n try (InputStream is = Files.newInputStream(propPath, StandardOpenOption.READ)) {\n props.load(is);\n } catch (IOException ex) {\n logger.error(ex.getMessage(), ex);\n }\n }\n }\n\n @PreDestroy\n public void saveSession() {\n logger.debug(\"save session\");\n try (OutputStream outStream = Files.newOutputStream(propPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {\n props.store(outStream, name + \" session properties\");\n } catch (IOException ex) {\n logger.error(ex.getMessage(), ex);\n }\n\n try {\n saveHistory();\n } catch (IOException e) {\n logger.error(e.getMessage(), e);\n }\n\n }\n\n public void bind(final BooleanProperty property, final String propertyName) {\n String value = props.getProperty(propertyName);\n if (value != null) {\n property.set(Boolean.valueOf(value));\n }\n property.addListener(o -> {\n props.setProperty(propertyName, property.getValue().toString());\n });\n }\n\n @SuppressWarnings(\"unchecked\")\n public void bind(final ObjectProperty<?> property, final String propertyName, Class<?> type) {\n String value = props.getProperty(propertyName);\n if (value != null) {\n if (type.getName().equals(Color.class.getName())) {\n ((ObjectProperty<Color>) property).set(Color.valueOf(value));\n } else if (type.getName().equals(String.class.getName())) {\n ((ObjectProperty<String>) property).set(value);\n } else {\n ((ObjectProperty<Object>) property).set(value);\n }\n }\n property.addListener(o -> {\n props.setProperty(propertyName, property.getValue().toString());\n });\n }\n\n public void bind(final DoubleProperty property, final String propertyName) {\n String value = props.getProperty(propertyName);\n if (value != null) {\n property.set(Double.valueOf(value));\n }\n property.addListener(o -> {\n props.setProperty(propertyName, property.getValue().toString());\n });\n }\n\n public void bind(final ToggleGroup toggleGroup, final String propertyName) {\n try {\n String value = props.getProperty(propertyName);\n if (value != null) {\n int selectedToggleIndex = Integer.parseInt(value);\n toggleGroup.selectToggle(toggleGroup.getToggles().get(selectedToggleIndex));\n }\n } catch (Exception ignored) {\n }\n toggleGroup.selectedToggleProperty().addListener(o -> {\n if (toggleGroup.getSelectedToggle() == null) {\n props.remove(propertyName);\n } else {\n props.setProperty(propertyName, Integer.toString(toggleGroup.getToggles().indexOf(toggleGroup.getSelectedToggle())));\n }\n });\n }\n\n public void bind(final Accordion accordion, final String propertyName) {\n Object selectedPane = props.getProperty(propertyName);\n for (TitledPane tp : accordion.getPanes()) {\n if (tp.getText() != null && tp.getText().equals(selectedPane)) {\n accordion.setExpandedPane(tp);\n break;\n }\n }\n accordion.expandedPaneProperty().addListener((ov, t, expandedPane) -> {\n if (expandedPane != null) {\n props.setProperty(propertyName, expandedPane.getText());\n }\n });\n }\n\n public void bind(final ComboBox<?> combo, final String propertyName) {\n try {\n String value = props.getProperty(propertyName);\n if (value != null) {\n int index = Integer.parseInt(value);\n combo.getSelectionModel().select(index);\n }\n } catch (Exception ignored) {\n }\n combo.getSelectionModel().selectedIndexProperty().addListener(o -> {\n props.setProperty(propertyName, Integer.toString(combo.getSelectionModel().getSelectedIndex()));\n });\n }\n\n public void bind(final StringProperty property, final String propertyName) {\n String value = props.getProperty(propertyName);\n if (value != null) {\n property.set(value);\n }\n\n property.addListener(o -> {\n props.setProperty(propertyName, property.getValue());\n });\n }\n\n /**\n * session scope bindings\n * \n * @return\n */\n public ObservableMap<String, Property<?>> getBindings() {\n if (bindings == null) {\n bindings = FXCollections.observableHashMap();\n }\n return bindings;\n }\n\n /**\n * add session scope binding (Property.getName() required)\n * \n * @param value\n */\n public void addBinding(Property<?> value) {\n if (value.getName() == null || value.getName().isEmpty()) {\n throw new IllegalArgumentException(\"property name must not be empty\");\n }\n getBindings().put(value.getName(), value);\n }\n\n public Optional<Property<?>> getBinding(String key) {\n return Optional.ofNullable(getBindings().get(key));\n }\n\n public Optional<ObjectProperty<?>> getObjectBinding(String key) {\n Optional<Property<?>> b = getBinding(key);\n if (!b.isPresent() || !ObjectProperty.class.isInstance(b.get())) {\n return Optional.empty();\n }\n return Optional.of((ObjectProperty<?>) b.get());\n }\n\n public Optional<BooleanProperty> getBooleanBinding(String key) {\n Optional<Property<?>> b = getBinding(key);\n if (!b.isPresent() || !BooleanProperty.class.isInstance(b.get())) {\n return Optional.empty();\n }\n return Optional.of((BooleanProperty) b.get());\n }\n\n public Optional<IntegerProperty> getIntegerBinding(String key) {\n Optional<Property<?>> b = getBinding(key);\n if (!b.isPresent() || !IntegerProperty.class.isInstance(b.get())) {\n return Optional.empty();\n }\n return Optional.of((IntegerProperty) b.get());\n }\n\n public Optional<StringProperty> getStringBinding(String key) {\n Optional<Property<?>> b = getBinding(key);\n if (!b.isPresent() || !StringProperty.class.isInstance(b.get())) {\n return Optional.empty();\n }\n return Optional.of((StringProperty) b.get());\n }\n\n public Optional<DoubleProperty> getDoubleBinding(String key) {\n Optional<Property<?>> b = getBinding(key);\n if (!b.isPresent() || !DoubleProperty.class.isInstance(b.get())) {\n return Optional.empty();\n }\n return Optional.of((DoubleProperty) b.get());\n }\n\n public Optional<FloatProperty> getFloatBinding(String key) {\n Optional<Property<?>> b = getBinding(key);\n if (!b.isPresent() || !FloatProperty.class.isInstance(b.get())) {\n return Optional.empty();\n }\n return Optional.of((FloatProperty) b.get());\n }\n\n public ObservableList<HistoryEntry> getHistory() {\n if (history == null) {\n history = FXCollections.observableArrayList();\n loadHistory();\n }\n return history;\n }\n\n private void loadHistory() {\n history.clear();\n\n if (!Files.exists(streamPath, LinkOption.NOFOLLOW_LINKS)) {\n logger.debug(\"no stream exist ({})\", streamPath);\n return;\n }\n logger.info(\"load history ({})\", streamPath);\n\n try (InputStream inStream = Files.newInputStream(streamPath, StandardOpenOption.READ)) {\n try (ObjectInputStream oStream = new ObjectInputStream(inStream)) {\n Object o = null;\n while (inStream.available() > 0 && (o = oStream.readObject()) != null) {\n HistoryEntry dev = (HistoryEntry) o;\n logger.debug(\"read dev: {}\", dev);\n if (!history.contains(dev)) {\n history.add(dev);\n } else {\n logger.error(\"device already exist ({})\", dev);\n }\n }\n }\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n try {\n Files.deleteIfExists(streamPath);\n } catch (IOException e1) {\n }\n }\n }\n\n private void saveHistory() throws IOException {\n if (history.isEmpty()) {\n Files.deleteIfExists(streamPath);\n return;\n }\n\n try (\n OutputStream outStream = Files.newOutputStream(streamPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {\n try (ObjectOutputStream historyStream = new ObjectOutputStream(outStream)) {\n for (HistoryEntry h : history) {\n historyStream.writeObject(h);\n }\n }\n }\n\n }\n}", "public class ProtocolVersion implements Comparable<ProtocolVersion> {\n\n public final static ProtocolVersion RFB_3_3 = new ProtocolVersion(3, 3);\n public final static ProtocolVersion RFB_3_7 = new ProtocolVersion(3, 7);\n public final static ProtocolVersion RFB_3_8 = new ProtocolVersion(3, 8);\n\n private final Pattern VERSION_PAT = Pattern.compile(\"RFB ([0-9]{3}).([0-9]{3})\");\n\n private int majorVersion;\n\n private int minorVersion;\n\n /**\n * RFB protocol parser (RFB ([0-9]{3}).([0-9]{3}))\n * \n * @param version String\n */\n public ProtocolVersion(String version) {\n if (version == null) {\n throw new IllegalArgumentException(\"null can not parsed to version\");\n }\n Matcher versionMatcher = VERSION_PAT.matcher(version);\n if (versionMatcher.find()) {\n majorVersion = Integer.parseInt(versionMatcher.group(1));\n minorVersion = Integer.parseInt(versionMatcher.group(2));\n } else {\n throw new IllegalArgumentException(\"version: \" + version + \" not supported\");\n }\n }\n\n public ProtocolVersion(int major, int minor) {\n majorVersion = major;\n minorVersion = minor;\n }\n\n public int getMajorVersion() {\n return majorVersion;\n }\n\n public int getMinorVersion() {\n return minorVersion;\n }\n\n public boolean isGreaterThan(ProtocolVersion o) {\n return compareTo(o) > 0;\n }\n\n public boolean isGreaterThan(String v) {\n return compareTo(new ProtocolVersion(v)) > 0;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null || !(obj instanceof ProtocolVersion)) {\n return false;\n }\n return compareTo((ProtocolVersion) obj) == 0;\n }\n\n @Override\n public int compareTo(ProtocolVersion v) {\n if (majorVersion == v.getMajorVersion() && minorVersion == v.getMinorVersion()) {\n return 0;\n }\n if (majorVersion > v.getMajorVersion() || (majorVersion == v.getMajorVersion() && minorVersion > v.getMinorVersion())) {\n return 1;\n }\n return -1;\n }\n\n /**\n * encoded ASCII bytes include LF\n * \n * @return expected RFB version bytes\n */\n public byte[] getBytes() {\n return String.format(\"RFB %03d.%03d\\n\", majorVersion, minorVersion).getBytes(StandardCharsets.US_ASCII);\n }\n\n @Override\n public String toString() {\n return String.format(\"RFB %03d.%03d\", majorVersion, minorVersion);\n }\n}", "public enum SecurityType {\n\n UNKNOWN(-1), INVALID(0), NONE(1), VNC_Auth(2), RA2(5), RA2ne(6), Tight(16), Ultra(17), TLS(18), VeNCrypt(19), GTK_VNC_SAS(20), MD5(21), Colin_Dean_xvp(22);\n\n private final int type;\n\n private SecurityType(int type) {\n this.type = type;\n }\n\n public static SecurityType valueOf(int type) {\n for (SecurityType e : values()) {\n if (e.type == type) {\n return e;\n }\n }\n return UNKNOWN;\n }\n\n public int getType() {\n return type;\n }\n}", "public class ConnectInfoEvent implements ServerDecoderEvent {\n\n String remoteAddress;\n\n String serverName;\n\n ProtocolVersion rfbProtocol;\n\n int frameHeight;\n int frameWidth;\n\n Encoding[] supportedEncodings;\n\n PixelFormat serverPF;\n\n PixelFormat clientPF;\n\n SecurityType security;\n\n String connectionType;\n\n public String getServerName() {\n return serverName;\n }\n\n public void setServerName(String serverName) {\n this.serverName = serverName;\n }\n\n public ProtocolVersion getRfbProtocol() {\n return rfbProtocol;\n }\n\n public void setRfbProtocol(ProtocolVersion rfbProtocol) {\n this.rfbProtocol = rfbProtocol;\n }\n\n public int getFrameHeight() {\n return frameHeight;\n }\n\n public void setFrameHeight(int frameHeight) {\n this.frameHeight = frameHeight;\n }\n\n public int getFrameWidth() {\n return frameWidth;\n }\n\n public void setFrameWidth(int frameWidth) {\n this.frameWidth = frameWidth;\n }\n\n public Encoding[] getSupportedEncodings() {\n return supportedEncodings;\n }\n\n public void setSupportedEncodings(Encoding[] supportedEncodings) {\n this.supportedEncodings = supportedEncodings;\n }\n\n public PixelFormat getServerPF() {\n return serverPF;\n }\n\n public void setServerPF(PixelFormat serverPF) {\n this.serverPF = serverPF;\n }\n\n public PixelFormat getClientPF() {\n return clientPF;\n }\n\n public void setClientPF(PixelFormat clientPF) {\n this.clientPF = clientPF;\n }\n\n public SecurityType getSecurity() {\n return security;\n }\n\n public void setSecurity(SecurityType securityType) {\n this.security = securityType;\n }\n\n public String getRemoteAddress() {\n return remoteAddress;\n }\n\n public void setRemoteAddress(String adr) {\n this.remoteAddress = adr;\n }\n\n public String getConnectionType() {\n return connectionType;\n }\n\n public void setConnectionType(String connectionType) {\n this.connectionType = connectionType;\n }\n\n @Override\n public String toString() {\n return \"ConnectInfoEvent [\" + (remoteAddress != null ? \"remoteAddress=\" + remoteAddress + \", \" : \"\")\n + (serverName != null ? \"serverName=\" + serverName + \", \" : \"\") + (rfbProtocol != null ? \"rfbProtocol=\" + rfbProtocol + \", \" : \"\") + \"frameHeight=\"\n + frameHeight + \", frameWidth=\" + frameWidth + \", \"\n + (supportedEncodings != null ? \"supportedEncodings=\" + Arrays.toString(supportedEncodings) + \", \" : \"\")\n + (serverPF != null ? \"serverPF=\" + serverPF + \", \" : \"\") + (clientPF != null ? \"clientPF=\" + clientPF + \", \" : \"\") + \"security=\" + security + \", \"\n + (connectionType != null ? \"connectionType=\" + connectionType : \"\") + \"]\";\n }\n\n}", "public interface ProtocolConfiguration {\n\n final int DEFAULT_PORT = 5900;\n final int DEFAULT_LISTENING_PORT = 5500;\n\n /**\n * VNC server name or IP address\n * \n * @return host\n */\n StringProperty hostProperty();\n\n /**\n * VNC server port (default: 5900)\n * \n * @return port\n */\n IntegerProperty portProperty();\n\n /**\n * listening mode to accept incoming connection requests (default: 5500)\n * \n * @return listening port\n */\n IntegerProperty listeningPortProperty();\n\n /**\n * VNC authentication password\n * \n * @return password\n */\n StringProperty passwordProperty();\n\n /**\n * Enable SSL/TLS transfer\n * \n * @return SSL/TLS enabled\n */\n BooleanProperty sslProperty();\n\n /**\n * Security Type {@link SecurityType}\n * \n * @return current {@link SecurityType}\n * @see org.jfxvnc.net.rfb.codec.security.SecurityType\n */\n ObjectProperty<SecurityType> securityProperty();\n\n /**\n * VNC connection shared by other clients\n * \n * @return shared\n */\n BooleanProperty sharedProperty();\n\n /**\n * Used Protocol Version {@link ProtocolVersion}\n * \n * @return current {@link ProtocolVersion}\n */\n ObjectProperty<ProtocolVersion> versionProperty();\n\n /**\n * Used PixelFormat {@link PixelFormat}\n * \n * @return current {@link PixelFormat}\n * @see org.jfxvnc.net.rfb.codec.PixelFormat\n */\n ObjectProperty<PixelFormat> clientPixelFormatProperty();\n\n /**\n * Activate RAW encoding\n * \n * @return raw enabled\n * @see org.jfxvnc.net.rfb.codec.Encoding\n */\n BooleanProperty rawEncProperty();\n\n /**\n * Activate COPY RECT encoding\n * \n * @return raw enabled\n * @see org.jfxvnc.net.rfb.codec.Encoding\n */\n BooleanProperty copyRectEncProperty();\n\n /**\n * Activate Hextile encoding\n * \n * @return Hextile enabled\n * @see org.jfxvnc.net.rfb.codec.Encoding\n */\n BooleanProperty hextileEncProperty();\n\n /**\n * Activate Cursor pseudo encoding\n * \n * @return Cursor enabled\n * @see org.jfxvnc.net.rfb.codec.Encoding\n */\n BooleanProperty clientCursorProperty();\n\n /**\n * Activate Desktop Resize pseudo encoding\n * \n * @return Desktop Resize enabled\n * @see org.jfxvnc.net.rfb.codec.Encoding\n */\n BooleanProperty desktopSizeProperty();\n\n /**\n * Activate Zlib pseudo encoding\n * \n * @return Zlib enabled\n * @see org.jfxvnc.net.rfb.codec.Encoding\n */\n BooleanProperty zlibEncProperty();\n\n}", "public class VncRenderService implements RenderProtocol {\n\n private final static org.slf4j.Logger logger = LoggerFactory.getLogger(VncRenderService.class);\n\n private final VncConnection con;\n\n private BiConsumer<ServerDecoderEvent, ImageRect> eventConsumer;\n\n private final BooleanProperty listeningMode = new SimpleBooleanProperty(false);\n\n private final ReadOnlyBooleanWrapper online = new ReadOnlyBooleanWrapper(false);\n private final ReadOnlyBooleanWrapper bell = new ReadOnlyBooleanWrapper(false);\n private final ReadOnlyStringWrapper serverCutText = new ReadOnlyStringWrapper();\n\n private final ReadOnlyObjectWrapper<ConnectInfoEvent> connectInfo = new ReadOnlyObjectWrapper<>();\n private final ReadOnlyObjectWrapper<ProtocolState> protocolState = new ReadOnlyObjectWrapper<>(ProtocolState.CLOSED);\n private final ReadOnlyObjectWrapper<InputEventListener> inputEventListener = new ReadOnlyObjectWrapper<>();\n private final ReadOnlyObjectWrapper<ColourMapEvent> colourMapEvent = new ReadOnlyObjectWrapper<>();\n\n private final ReadOnlyObjectWrapper<Throwable> exceptionCaught = new ReadOnlyObjectWrapper<>();\n\n private ReadOnlyObjectWrapper<ImageRect> image;\n\n private final double minZoomLevel = 0.2;\n private final double maxZoomLevel = 5.0;\n\n private final DoubleProperty zoomLevel = new SimpleDoubleProperty(1);\n private final BooleanProperty fullSceen = new SimpleBooleanProperty(false);\n private final BooleanProperty restart = new SimpleBooleanProperty(false);\n\n public VncRenderService() {\n this(new VncConnection());\n }\n\n public VncRenderService(VncConnection con) {\n this.con = con;\n zoomLevel.addListener((l, a, b) -> {\n if (b.doubleValue() > maxZoomLevel) {\n zoomLevel.set(maxZoomLevel);\n } else if (b.doubleValue() < minZoomLevel) {\n zoomLevel.set(minZoomLevel);\n }\n });\n\n }\n\n public void setEventConsumer(BiConsumer<ServerDecoderEvent, ImageRect> c) {\n eventConsumer = c;\n }\n\n public ProtocolConfiguration getConfiguration() {\n return con.getConfiguration();\n }\n\n public void connect() {\n con.setRenderProtocol(this);\n con.addFaultListener(exceptionCaught::set);\n\n if (listeningMode.get()) {\n con.startListeningMode().whenComplete((c, th) -> {\n if (th != null) {\n exceptionCaught(th);\n disconnect();\n }\n });\n return;\n }\n con.connect().whenComplete((c, th) -> {\n if (th != null) {\n exceptionCaught(th);\n disconnect();\n }\n });\n }\n\n public void disconnect() {\n con.disconnect();\n online.set(false);\n }\n\n @Override\n public void render(ImageRect rect) {\n if (eventConsumer != null) {\n eventConsumer.accept(null, rect);\n }\n if (image != null) {\n image.set(rect);\n }\n \n }\n\n @Override\n public void renderComplete(RenderCallback callback) {\n Platform.runLater(() -> callback.renderComplete());\n }\n \n @Override\n public void eventReceived(ServerDecoderEvent event) {\n logger.debug(\"event received: {}\", event);\n \n if (eventConsumer != null) {\n eventConsumer.accept(event, null);\n }\n \n if (event instanceof ConnectInfoEvent) {\n connectInfo.set((ConnectInfoEvent) event);\n online.set(true);\n return;\n }\n if (event instanceof BellEvent) {\n bell.set(!bell.get());\n return;\n }\n if (event instanceof ServerCutTextEvent) {\n serverCutText.set(((ServerCutTextEvent) event).getText());\n return;\n }\n if (event instanceof ColourMapEvent) {\n colourMapEvent.set((ColourMapEvent) event);\n return;\n }\n\n logger.warn(\"not handled event: {}\", event);\n }\n\n @Override\n public void exceptionCaught(Throwable t) {\n exceptionCaught.set(t);\n }\n\n @Override\n public void stateChanged(ProtocolState state) {\n protocolState.set(state);\n if (state == ProtocolState.CLOSED) {\n disconnect();\n }\n }\n\n @Override\n public void registerInputEventListener(InputEventListener listener) {\n inputEventListener.set(listener);\n }\n\n public ReadOnlyObjectProperty<ConnectInfoEvent> connectInfoProperty() {\n return connectInfo.getReadOnlyProperty();\n }\n\n public ReadOnlyObjectProperty<ProtocolState> protocolStateProperty() {\n return protocolState;\n }\n\n public ReadOnlyObjectProperty<InputEventListener> inputEventListenerProperty() {\n return inputEventListener.getReadOnlyProperty();\n }\n\n public ReadOnlyObjectProperty<ImageRect> imageProperty() {\n if (image == null) {\n image = new ReadOnlyObjectWrapper<>();\n }\n return image.getReadOnlyProperty();\n }\n\n public ReadOnlyObjectProperty<ColourMapEvent> colourMapEventProperty() {\n return colourMapEvent.getReadOnlyProperty();\n }\n\n public ReadOnlyObjectProperty<Throwable> exceptionCaughtProperty() {\n return exceptionCaught.getReadOnlyProperty();\n }\n\n public ReadOnlyBooleanProperty connectingProperty() {\n return con.connectingProperty();\n }\n\n public ReadOnlyBooleanProperty connectedProperty() {\n return con.connectedProperty();\n }\n \n public ReadOnlyBooleanProperty onlineProperty() {\n return online.getReadOnlyProperty();\n }\n\n public ReadOnlyBooleanProperty bellProperty() {\n return bell.getReadOnlyProperty();\n }\n\n public ReadOnlyStringProperty serverCutTextProperty() {\n return serverCutText.getReadOnlyProperty();\n }\n\n public DoubleProperty zoomLevelProperty() {\n return zoomLevel;\n }\n\n public BooleanProperty fullSceenProperty() {\n return fullSceen;\n }\n\n public BooleanProperty restartProperty() {\n return restart;\n }\n\n public BooleanProperty listeningModeProperty() {\n return listeningMode;\n }\n\n public IntegerProperty listeningPortProperty() {\n return getConfiguration().listeningPortProperty();\n }\n}" ]
import java.net.URL; import java.util.Optional; import java.util.ResourceBundle; import javax.inject.Inject; import org.jfxvnc.app.persist.HistoryEntry; import org.jfxvnc.app.persist.SessionContext; import org.jfxvnc.net.rfb.codec.ProtocolVersion; import org.jfxvnc.net.rfb.codec.security.SecurityType; import org.jfxvnc.net.rfb.render.ConnectInfoEvent; import org.jfxvnc.net.rfb.render.ProtocolConfiguration; import org.jfxvnc.ui.service.VncRenderService; import javafx.application.Platform; import javafx.beans.binding.Bindings; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ListView; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.util.StringConverter; import javafx.util.converter.NumberStringConverter;
/******************************************************************************* * Copyright (c) 2016 comtel inc. * * 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 org.jfxvnc.app.presentation.connect; public class ConnectViewPresenter implements Initializable { @Inject SessionContext ctx; @Inject
VncRenderService con;
6
Darkona/AdventureBackpack2
src/main/java/com/darkona/adventurebackpack/handlers/PlayerEventHandler.java
[ "public class ServerActions\n{\n public static final boolean HOSE_SWITCH = false;\n public static final boolean HOSE_TOGGLE = true;\n\n /**\n * Cycles tools. In a cycle. The tool in your hand with the tools in the special tool slots of the backpack, to be precise.\n *\n * @param player - Duh\n * @param direction - An integer indicating the direction of the switch. Nobody likes to swith always inthe same\n * direction all the timeInSeconds. That's stupid.\n * @param slot The slot that will be switched with the backpack.\n */\n public static void cycleTool(EntityPlayer player, int direction, int slot)\n {\n try\n {\n InventoryBackpack backpack = Wearing.getBackpackInv(player, true);\n ItemStack current = player.getCurrentEquippedItem();\n backpack.openInventory();\n if (direction < 0)\n {\n //LogHelper.info(\"Item of class \" + backpack.getStackInSlot(Constants.lowerTool).getItem().getClass().getName());\n player.inventory.mainInventory[slot] = backpack.getStackInSlot(Constants.upperTool);\n backpack.setInventorySlotContentsNoSave(Constants.upperTool, backpack.getStackInSlot(Constants.lowerTool));\n backpack.setInventorySlotContentsNoSave(Constants.lowerTool, current);\n\n } else\n {\n if (direction > 0)\n {\n player.inventory.mainInventory[slot] = backpack.getStackInSlot(Constants.lowerTool);\n backpack.setInventorySlotContentsNoSave(Constants.lowerTool, backpack.getStackInSlot(Constants.upperTool));\n backpack.setInventorySlotContentsNoSave(Constants.upperTool, current);\n }\n }\n backpack.markDirty();\n player.inventory.closeInventory();\n } catch (Exception oops)\n {\n LogHelper.debug(\"Exception trying to cycle tools.\");\n oops.printStackTrace();\n }\n }\n\n /**\n * @param world The world. Like, the WHOLE world. That's a lot of stuff. Do stuff with it, like detecting biomes\n * or whatever.\n * @param player Is a player. To whom the nice or evil effects you're going to apply will affect.\n * See? I know the proper use of the words \"effect\" & \"affect\".\n * @param tank The tank that holds the fluid, whose effect will affect the player that's in the world.\n * @return If the effect can be applied, and it is actually applied, returns true.\n */\n public static boolean setFluidEffect(World world, EntityPlayer player, FluidTank tank)\n {\n FluidStack drained = tank.drain(Constants.bucket, false);\n boolean done = false;\n if (drained != null && drained.amount >= Constants.bucket && FluidEffectRegistry.hasFluidEffect(drained.getFluid()))\n {\n done = FluidEffectRegistry.executeFluidEffectsForFluid(drained.getFluid(), player, world);\n }\n return done;\n }\n\n /**\n * @param player Duh!\n * @param direction The direction in which the hose modes will switch.\n * @param action The type of the action to be performed on the hose.\n * Can be HOSE_SWITCH for mode or HOSE_TOGGLE for tank\n * @param slot The slot in which the hose gleefully frolicks in the inventory.\n */\n public static void switchHose(EntityPlayer player, boolean action, int direction, int slot)\n {\n\n ItemStack hose = player.inventory.mainInventory[slot];\n if (hose != null && hose.getItem() instanceof ItemHose)\n {\n NBTTagCompound tag = hose.hasTagCompound() ? hose.stackTagCompound : new NBTTagCompound();\n if (!action)\n {\n int mode = ItemHose.getHoseMode(hose);\n if (direction > 0)\n {\n mode = (mode + 1) % 3;\n } else if (direction < 0)\n {\n mode = (mode - 1 < 0) ? 2 : mode - 1;\n }\n tag.setInteger(\"mode\", mode);\n }\n\n if (action)\n {\n int tank = ItemHose.getHoseTank(hose);\n tank = (tank + 1) % 2;\n tag.setInteger(\"tank\", tank);\n }\n hose.setTagCompound(tag);\n }\n }\n\n /**\n * Electrifying! Transforms a backpack into its electrified version. Shhh this is kinda secret, ok?\n *\n * @param player The player wearing the backpack.\n */\n public static void electrify(EntityPlayer player)\n {\n ItemStack backpack = Wearing.getWearingBackpack(player);\n if (BackpackNames.getBackpackColorName(backpack).equals(\"Pig\"))\n {\n BackpackNames.setBackpackColorName(backpack, \"Pigman\");\n }\n if (BackpackNames.getBackpackColorName(backpack).equals(\"Diamond\"))\n {\n BackpackNames.setBackpackColorName(backpack, \"Electric\");\n }\n }\n\n /**\n * @param player\n * @param bow\n * @param charge\n */\n public static void leakArrow(EntityPlayer player, ItemStack bow, int charge)\n {\n World world = player.worldObj;\n Random itemRand = new Random();\n InventoryBackpack backpack = new InventoryBackpack(Wearing.getWearingBackpack(player));\n\n //this is all vanilla code for the bow\n boolean flag = player.capabilities.isCreativeMode\n || EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, bow) > 0;\n\n if (flag || backpack.hasItem(Items.arrow))\n {\n float f = (float) charge / 20.0F;\n f = (f * f + f * 2.0F) / 3.0F;\n if ((double) f < 0.1D)\n {\n return;\n }\n if (f > 1.0F)\n {\n f = 1.0F;\n }\n EntityArrow entityarrow = new EntityArrow(world, player, f * 2.0F);\n if (f == 1.0F)\n {\n entityarrow.setIsCritical(true);\n }\n int power = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, bow);\n if (power > 0)\n {\n entityarrow.setDamage(entityarrow.getDamage() + (double) power * 0.5D + 0.5D);\n }\n int punch = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, bow);\n if (punch > 0)\n {\n entityarrow.setKnockbackStrength(punch);\n }\n if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, bow) > 0)\n {\n entityarrow.setFire(100);\n }\n\n bow.damageItem(1, player);\n world.playSoundAtEntity(player, \"random.bow\", 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + f * 0.5F);\n\n if (flag)\n {\n entityarrow.canBePickedUp = 2;\n } else\n {\n /*\n * From here, instead of leaking an arrow to the player inventory, which may be full and then it would be\n * pointless, leak an arrow straight from the backpack ^_^\n *\n * It could be possible to switch a whole stack with the player inventory, fire the arrow, and then\n * switch back, but that's stupid.\n *\n * That's how you make a quiver (for vanilla bows at least, or anything that uses the events and vanilla\n * arrows) Until we have an event that fires when a player consumes items in his/her inventory.\n *\n * I should make a pull request. Too lazy, though.\n * */\n backpack.consumeInventoryItem(Items.arrow);\n backpack.dirtyInventory();\n }\n\n if (!world.isRemote)\n {\n world.spawnEntityInWorld(entityarrow);\n }\n }\n }\n\n /**\n * @param player\n * @param coordX\n * @param coordY\n * @param coordZ\n */\n public static void toggleSleepingBag(EntityPlayer player, int coordX, int coordY, int coordZ)\n {\n World world = player.worldObj;\n if (world.getTileEntity(coordX, coordY, coordZ) instanceof TileAdventureBackpack)\n {\n TileAdventureBackpack te = (TileAdventureBackpack) world.getTileEntity(coordX, coordY, coordZ);\n if (!te.isSBDeployed())\n {\n int can[] = canDeploySleepingBag(world, coordX, coordY, coordZ);\n if (can[0] > -1)\n {\n if (te.deploySleepingBag(player, world, can[1], can[2], can[3], can[0]))\n {\n player.closeScreen();\n }\n } else if (world.isRemote)\n {\n player.addChatComponentMessage(new ChatComponentText(\"Can't deploy the sleeping bag! Check the surrounding area.\"));\n }\n } else\n {\n te.removeSleepingBag(world);\n }\n player.closeScreen();\n }\n\n }\n\n public static int[] canDeploySleepingBag(World world, int coordX, int coordY, int coordZ)\n {\n TileAdventureBackpack te = (TileAdventureBackpack) world.getTileEntity(coordX, coordY, coordZ);\n int newMeta = -1;\n\n if (!te.isSBDeployed())\n {\n int meta = world.getBlockMetadata(coordX, coordY, coordZ);\n switch (meta & 3)\n {\n case 0:\n --coordZ;\n if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid())\n {\n if (world.isAirBlock(coordX, coordY, coordZ - 1) && world.getBlock(coordX, coordY - 1, coordZ - 1).getMaterial().isSolid())\n {\n newMeta = 2;\n }\n }\n break;\n case 1:\n ++coordX;\n if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid())\n {\n if (world.isAirBlock(coordX + 1, coordY, coordZ) && world.getBlock(coordX + 1, coordY - 1, coordZ).getMaterial().isSolid())\n {\n newMeta = 3;\n }\n }\n break;\n case 2:\n ++coordZ;\n if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid())\n {\n if (world.isAirBlock(coordX, coordY, coordZ + 1) && world.getBlock(coordX, coordY - 1, coordZ + 1).getMaterial().isSolid())\n {\n newMeta = 0;\n }\n }\n break;\n case 3:\n --coordX;\n if (world.isAirBlock(coordX, coordY, coordZ) && world.getBlock(coordX, coordY - 1, coordZ).getMaterial().isSolid())\n {\n if (world.isAirBlock(coordX - 1, coordY, coordZ) && world.getBlock(coordX - 1, coordY - 1, coordZ).getMaterial().isSolid())\n {\n newMeta = 1;\n }\n }\n break;\n default:\n break;\n }\n }\n int result[] = {newMeta, coordX, coordY, coordZ};\n return result;\n }\n\n /**\n * Adds vertical inertia to the movement in the Y axis of the player, and makes Newton's Laws cry.\n * In other words, makes you jump higher.\n * Also it plays a nice sound effect that will probably get annoying after a while.\n *\n * @param player - The player performing the jump.\n */\n public static void pistonBootsJump(EntityPlayer player)\n {\n //TODO add configuration for the playing of the sound effect.\n //TODO Maybe configurable jump height too, because why not.\n player.playSound(\"tile.piston.out\", 0.5F, player.getRNG().nextFloat() * 0.25F + 0.6F);\n player.motionY += 0.30;\n player.jumpMovementFactor += 0.3;\n }\n\n public static void toggleCopterPack(EntityPlayer player, ItemStack copter, byte type)\n {\n String message = \"\";\n boolean actionPerformed = false;\n\n if (!copter.hasTagCompound())\n {\n copter.stackTagCompound = new NBTTagCompound();\n }\n if (!copter.stackTagCompound.hasKey(\"status\"))\n {\n copter.stackTagCompound.setByte(\"status\", ItemCopterPack.OFF_MODE);\n }\n\n byte mode = copter.stackTagCompound.getByte(\"status\");\n byte newMode = ItemCopterPack.OFF_MODE;\n\n if (type == WearableModePacket.COPTER_ON_OFF)\n {\n if (mode == ItemCopterPack.OFF_MODE)\n {\n newMode = ItemCopterPack.NORMAL_MODE;\n message = \"adventurebackpack:messages.copterpack.normal\";\n actionPerformed = true;\n if (!player.worldObj.isRemote)\n {\n ModNetwork.sendToNearby(new EntitySoundPacket.Message(EntitySoundPacket.COPTER_SOUND,player), player);\n\n }\n } else\n {\n newMode = ItemCopterPack.OFF_MODE;\n message = \"adventurebackpack:messages.copterpack.off\";\n actionPerformed = true;\n }\n }\n\n if (type == WearableModePacket.COPTER_TOGGLE && mode != ItemCopterPack.OFF_MODE)\n {\n if (mode == ItemCopterPack.NORMAL_MODE)\n {\n newMode = ItemCopterPack.HOVER_MODE;\n message = \"adventurebackpack:messages.copterpack.hover\";\n actionPerformed = true;\n }\n if (mode == ItemCopterPack.HOVER_MODE)\n {\n newMode = ItemCopterPack.NORMAL_MODE;\n message = \"adventurebackpack:messages.copterpack.normal\";\n actionPerformed = true;\n }\n }\n\n if (actionPerformed)\n {\n copter.stackTagCompound.setByte(\"status\", newMode);\n if (player.worldObj.isRemote)\n {\n player.addChatComponentMessage(new ChatComponentTranslation(message));\n }\n\n }\n }\n\n public static void toggleSteamJetpack(EntityPlayer player, ItemStack jetpack, byte on_off)\n {\n InventorySteamJetpack inv = new InventorySteamJetpack(jetpack);\n if(inv.getStatus())\n {\n inv.setStatus(false);\n inv.markDirty();\n if (player.worldObj.isRemote)\n {\n player.addChatComponentMessage(new ChatComponentTranslation(\"adventurebackpack:messages.jetpack.off\"));\n }\n }else{\n inv.setStatus(true);\n inv.markDirty();\n if (player.worldObj.isRemote)\n {\n player.addChatComponentMessage(new ChatComponentTranslation(\"adventurebackpack:messages.jetpack.on\"));\n }\n }\n }\n}", "public class ConfigHandler\n{\n\n\n public static Configuration config;\n\n public static boolean IS_BUILDCRAFT = false;\n public static boolean IS_BAUBLES = false;\n public static boolean IS_TINKERS = false;\n public static boolean IS_THAUM = false;\n public static boolean IS_TWILIGHT = false;\n public static boolean IS_ENVIROMINE = false;\n public static boolean IS_RAILCRAFT = false;\n\n public static int GUI_TANK_RENDER = 2;\n public static boolean BONUS_CHEST_ALLOWED = false;\n public static boolean PIGMAN_ALLOWED = false;\n\n public static boolean BACKPACK_DEATH_PLACE = true;\n public static boolean BACKPACK_ABILITIES = true;\n\n public static boolean ALLOW_COPTER_SOUND = true;\n public static boolean ALLOW_JETPACK_SOUNDS = true;\n\n\n public static boolean STATUS_OVERLAY = true;\n public static boolean TANKS_OVERLAY = true;\n public static boolean HOVERING_TEXT_TANKS = false;\n public static boolean SADDLE_RECIPE = true;\n public static boolean FIX_LEAD = true;\n\n\n public static void init(File configFile)\n {\n if (config == null)\n {\n config = new Configuration(configFile);\n loadConfiguration();\n }\n }\n\n\n private static void loadConfiguration()\n {\n GUI_TANK_RENDER = config.getInt(\"TankRenderType\", config.CATEGORY_GENERAL, 3, 1, 3, \"1,2 or 3 for different rendering of fluids in the Backpack GUI\");\n BONUS_CHEST_ALLOWED = config.getBoolean(\"BonusBackpack\", config.CATEGORY_GENERAL, false, \"Include a Standard Adventure Backpack in bonus chest?\");\n PIGMAN_ALLOWED = config.getBoolean(\"PigmanBackpacks\", config.CATEGORY_GENERAL, false, \"Allow generation of Pigman Backpacks in dungeon loot and villager trades\");\n ALLOW_COPTER_SOUND = config.getBoolean(\"CopterPackSound\", config.CATEGORY_GENERAL, true, \"Allow playing the CopterPack sound (Client Only, other players may hear it)\");\n BACKPACK_ABILITIES = config.getBoolean(\"BackpackAbilities\", config.CATEGORY_GENERAL, true, \"Allow the backpacks to execute their special abilities, or be only cosmetic (Doesn't affect lightning transformation) Must be \" +\n \"disabled in both Client and Server to work properly\");\n STATUS_OVERLAY = config.getBoolean(\"StatusOverlay\", config.CATEGORY_GENERAL,true, \"Show player status effects on screen?\");\n TANKS_OVERLAY = config.getBoolean(\"BackpackOverlay\", config.CATEGORY_GENERAL,true, \"Show the different wearable overlays on screen?\");\n HOVERING_TEXT_TANKS = config.getBoolean(\"HoveringText\", config.CATEGORY_GENERAL,false, \"Show hovering text on fluid tanks?\");\n FIX_LEAD = config.getBoolean(\"FixVanillaLead\", config.CATEGORY_GENERAL,true, \"Fix the vanilla Lead? (Checks mobs falling on a leash to not die of fall damage if they're not falling so fast)\");\n BACKPACK_DEATH_PLACE = config.getBoolean(\"BackpackDeathPlace\", config.CATEGORY_GENERAL,true,\"Place backpacks as a block when you die?\");\n //RECIPES\n SADDLE_RECIPE = config.getBoolean(\"SaddleRecipe\", config.CATEGORY_GENERAL,true, \"Add recipe for saddle?\");\n if (config.hasChanged())\n {\n config.save();\n }\n }\n\n @SubscribeEvent\n public void onConfigChangeEvent(ConfigChangedEvent.OnConfigChangedEvent event)\n {\n if (event.modID.equalsIgnoreCase(ModInfo.MOD_ID))\n {\n loadConfiguration();\n }\n }\n\n\n}", "public class BackpackProperty implements IExtendedEntityProperties\n{\n\n public static final String PROPERTY_NAME = \"abp.property\";\n protected EntityPlayer player = null;\n private ItemStack wearable = null;\n private ChunkCoordinates campFire = null;\n private NBTTagCompound wearableData = new NBTTagCompound();\n private boolean forceCampFire = false;\n private int dimension = 0;\n\n public NBTTagCompound getWearableData()\n {\n return wearableData;\n }\n\n\n public static void sync(EntityPlayer player)\n {\n if(player instanceof EntityPlayerMP)\n {\n syncToNear(player);\n }\n }\n\n public static void syncToNear(EntityPlayer player)\n {\n //Thanks diesieben07!!!\n if(player != null && player instanceof EntityPlayerMP)\n {\n try\n {\n ((EntityPlayerMP) player)\n .getServerForPlayer()\n .getEntityTracker()\n .func_151248_b(player, ModNetwork.net.getPacketFrom(new SyncPropertiesPacket.Message(player.getEntityId(), get(player).getData())));\n }catch(Exception ex){\n ex.printStackTrace();\n }\n }\n }\n\n public BackpackProperty(EntityPlayer player)\n {\n this.player = player;\n }\n\n public NBTTagCompound getData()\n {\n NBTTagCompound data = new NBTTagCompound();\n saveNBTData(data);\n\n return data;\n }\n\n public static void register(EntityPlayer player)\n {\n player.registerExtendedProperties(PROPERTY_NAME, new BackpackProperty(player));\n }\n\n public static BackpackProperty get(EntityPlayer player)\n {\n return (BackpackProperty) player.getExtendedProperties(PROPERTY_NAME);\n }\n\n /**\n * Called when the entity that this class is attached to is saved.\n * Any custom entity data that needs saving should be saved here.\n *\n * @param compound The compound to save to.\n */\n @Override\n public void saveNBTData(NBTTagCompound compound)\n {\n if(wearable != null) compound.setTag(\"wearable\", wearable.writeToNBT(new NBTTagCompound()));\n if (campFire != null)\n {\n compound.setInteger(\"campFireX\", campFire.posX);\n compound.setInteger(\"campFireY\", campFire.posY);\n compound.setInteger(\"campFireZ\", campFire.posZ);\n compound.setInteger(\"campFireDim\", dimension);\n\n }\n compound.setBoolean(\"forceCampFire\",forceCampFire);\n }\n\n /**\n * Called when the entity that this class is attached to is loaded.\n * In order to hook into this, you will need to subscribe to the EntityConstructing event.\n * Otherwise, you will need to initialize manually.\n *\n * @param compound The compound to load from.\n */\n @Override\n public void loadNBTData(NBTTagCompound compound)\n {\n if(compound!=null)\n {\n setWearable( compound.hasKey(\"wearable\") ? ItemStack.loadItemStackFromNBT(compound.getCompoundTag(\"wearable\")) : null);\n setCampFire( new ChunkCoordinates(compound.getInteger(\"campFireX\"), compound.getInteger(\"campFireY\"), compound.getInteger(\"campFireZ\")));\n dimension = compound.getInteger(\"compFireDim\");\n forceCampFire = compound.getBoolean(\"forceCampfire\");\n }\n }\n\n /**\n * Used to initialize the extended properties with the entity that this is attached to, as well\n * as the world object.\n * Called automatically if you register with the EntityConstructing event.\n * May be called multiple times if the extended properties is moved over to a new entity.\n * Such as when a player switches dimension {Minecraft re-creates the player entity}\n *\n * @param entity The entity that this extended properties is attached to\n * @param world The world in which the entity exists\n */\n @Override\n public void init(Entity entity, World world)\n {\n this.player = (EntityPlayer)entity;\n }\n\n public void setWearable(ItemStack bp)\n {\n wearable = bp;\n }\n\n\n public ItemStack getWearable()\n {\n return wearable != null ? wearable : null ;\n }\n\n public void setCampFire(ChunkCoordinates cf)\n {\n campFire = cf;\n }\n\n public boolean hasWearable()\n {\n return wearable != null;\n }\n\n public ChunkCoordinates getCampFire()\n {\n return campFire;\n }\n\n public EntityPlayer getPlayer()\n {\n return player;\n }\n\n public void setDimension(int dimension)\n {\n this.dimension = dimension;\n }\n\n public int getDimension()\n {\n return dimension;\n }\n\n public boolean isForcedCampFire()\n {\n return forceCampFire;\n }\n\n public void setForceCampFire(boolean forceCampFire)\n {\n this.forceCampFire = forceCampFire;\n }\n\n //Scary names for methods because why not\n public void executeWearableUpdateProtocol()\n {\n if(Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class))\n {\n ((IBackWearableItem)wearable.getItem()).onEquippedUpdate(player.getEntityWorld(), player, wearable);\n }\n }\n\n public void executeWearableDeathProtocol()\n {\n if (Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class))\n {\n ((IBackWearableItem) wearable.getItem()).onPlayerDeath(player.getEntityWorld(), player, wearable);\n }\n }\n\n public void executeWearableEquipProtocol()\n {\n if (Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class))\n {\n ((IBackWearableItem) wearable.getItem()).onEquipped(player.getEntityWorld(), player, wearable);\n }\n }\n\n public void executeWearableUnequipProtocol()\n {\n if (Utils.notNullAndInstanceOf(wearable.getItem() , IBackWearableItem.class))\n {\n ((IBackWearableItem) wearable.getItem()).onUnequipped(player.getEntityWorld(), player, wearable);\n }\n }\n}", "public class ServerProxy implements IProxy\n{\n private static final Map<UUID, NBTTagCompound> extendedEntityData = new HashMap<UUID, NBTTagCompound>();\n\n @Override\n public void init()\n {\n\n }\n\n @Override\n public void registerKeybindings()\n {\n\n }\n\n @Override\n public void initNetwork()\n {\n\n }\n\n @Override\n public void joinPlayer(EntityPlayer player)\n {\n NBTTagCompound playerData = extractPlayerProps(player.getUniqueID());\n\n if (playerData != null)\n {\n LogHelper.info(\"Stored properties retrieved\");\n BackpackProperty.get(player).loadNBTData(playerData);\n BackpackProperty.syncToNear(player);\n }else{\n LogHelper.info(\"Data is null! WTF!\");\n }\n }\n\n @Override\n public void synchronizePlayer(int id, NBTTagCompound compound)\n {\n\n }\n\n public static void storePlayerProps(EntityPlayer player)\n {\n try\n {\n NBTTagCompound data = BackpackProperty.get(player).getData();\n if(data.hasKey(\"wearable\"))\n {\n LogHelper.info(\"Storing wearable: \" + ItemStack.loadItemStackFromNBT(data.getCompoundTag(\"wearable\")).getDisplayName());\n }\n extendedEntityData.put(player.getUniqueID(), data);\n LogHelper.info(\"Stored player properties for dead player\");\n }\n catch(Exception ex)\n {\n LogHelper.error(\"Something went wrong while saving player properties: \" + ex.getMessage());\n ex.printStackTrace();\n }\n }\n\n\n public static NBTTagCompound extractPlayerProps(UUID playerID)\n {\n return extendedEntityData.remove(playerID);\n }\n}", "public class BackpackNames\n{\n\n public static String[] backpackNames = {\n \"Standard\",\n \"Cow\",\n \"Bat\",\n \"Black\",\n \"Blaze\",\n \"Carrot\",\n \"Coal\",\n \"Diamond\",\n \"Emerald\",\n \"Gold\",\n \"Iron\",\n \"IronGolem\",\n \"Lapis\",\n \"Redstone\",\n \"Blue\",\n \"Bookshelf\",\n \"Brown\",\n \"Cactus\",\n \"Cake\",\n \"Chest\",\n \"Cookie\",\n \"Cyan\",\n \"Dragon\",\n \"Egg\",\n \"Electric\",\n \"Deluxe\",\n \"Enderman\",\n \"End\",\n \"Chicken\",\n \"Ocelot\",\n \"Ghast\",\n \"Gray\",\n \"Green\",\n \"Haybale\",\n \"Horse\",\n \"Leather\",\n \"LightBlue\",\n \"Glowstone\",\n \"LightGray\",\n \"Lime\",\n \"Magenta\",\n \"MagmaCube\",\n \"Melon\",\n \"BrownMushroom\",\n \"RedMushroom\",\n \"Mooshroom\",\n \"Nether\",\n \"Wither\",\n \"Obsidian\",\n \"Orange\",\n \"Overworld\",\n \"Pigman\",\n \"Pink\",\n \"Pig\",\n \"Pumpkin\",\n \"Purple\",\n \"Quartz\",\n \"Rainbow\",\n \"Red\",\n \"Sandstone\",\n \"Sheep\",\n \"Silverfish\",\n \"Squid\",\n \"Sunflower\",\n \"Creeper\",\n \"Skeleton\",\n \"WitherSkeleton\",\n \"Slime\",\n \"Snow\",\n \"Spider\",\n \"Sponge\",\n \"Villager\",\n \"White\",\n \"Wolf\",\n \"Yellow\",\n \"Zombie\"\n };\n\n public static ItemStack setBackpackColorNameFromDamage(ItemStack backpack, int damage)\n {\n\n if (backpack == null) return null;\n if (!(backpack.getItem() instanceof ItemAdventureBackpack)) return null;\n NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ;\n backpack.setItemDamage(damage);\n assert backpackData != null;\n backpackData.setString(\"colorName\", backpackNames[damage]);\n BackpackUtils.setBackpackData(backpack,backpackData);\n return backpack;\n }\n\n public static int getBackpackDamageFromName(String name)\n {\n for (int i = 0; i < backpackNames.length; i++)\n {\n if (backpackNames[i].equals(name)) return i;\n }\n return 0;\n }\n\n public static String getBackpackColorName(TileAdventureBackpack te)\n {\n return te.getColorName();\n }\n\n public static String getBackpackColorName(ItemStack backpack)\n {\n if (backpack == null) return \"\";\n NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ;\n assert backpackData != null;\n if (backpackData.getString(\"colorName\").isEmpty())\n {\n backpackData.setString(\"colorName\", \"Standard\");\n }\n return backpackData.getString(\"colorName\");\n }\n\n public static void setBackpackColorName(ItemStack backpack, String newName)\n {\n if (backpack != null)\n {\n NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ;\n assert backpackData != null;\n backpackData.setString(\"colorName\", newName);\n BackpackUtils.setBackpackData(backpack, backpackData);\n }\n }\n}", "public class Utils\n{\n\n public static float degreesToRadians(float degrees)\n {\n return degrees / 57.2957795f;\n }\n\n public static float radiansToDegrees(float radians)\n {\n return radians * 57.2957795f;\n }\n\n public static int[] calculateEaster(int year)\n {\n\n\n int a = year % 19,\n b = year / 100,\n c = year % 100,\n d = b / 4,\n e = b % 4,\n g = (8 * b + 13) / 25,\n h = (19 * a + b - d - g + 15) % 30,\n j = c / 4,\n k = c % 4,\n m = (a + 11 * h) / 319,\n r = (2 * e + 2 * j - k - h + m + 32) % 7,\n n = (h - m + r + 90) / 25,\n p = (h - m + r + n + 19) % 32;\n\n return new int[]{n, p};\n }\n\n public static String getHoliday()\n {\n\n Calendar calendar = Calendar.getInstance();\n int year = calendar.get(Calendar.YEAR),\n month = calendar.get(Calendar.MONTH) + 1,\n day = calendar.get(Calendar.DAY_OF_MONTH);\n\n if (AdventureBackpack.instance.chineseNewYear) return \"ChinaNewYear\";\n if (AdventureBackpack.instance.hannukah) return \"Hannukah\";\n if (month == Utils.calculateEaster(year)[0] && day == Utils.calculateEaster(year)[1]) return \"Easter\";\n String dia = \"Standard\";\n if (month == 1)\n {\n if (day == 1) dia = \"NewYear\";\n if (day == 28) dia = \"Shuttle\";//Challenger\n }\n if (month == 2)\n {\n if (day == 1) dia = \"Shuttle\";//Columbia\n if (day == 14) dia = \"Valentines\";\n if (day == 23) dia = \"Fatherland\";\n }\n if (month == 3)\n {\n if (day == 17) dia = \"Patrick\";\n }\n if (month == 4)\n {\n if (day == 1) dia = \"Fools\";\n if (day == 25) dia = \"Italy\";\n }\n if (month == 5)\n {\n if (day == 8 || day == 9 || day == 10) dia = \"Liberation\";\n }\n if (month == 6)\n {\n }\n if (month == 7)\n {\n if (day == 4) dia = \"USA\";\n if (day == 24) dia = \"Bolivar\";\n if (day == 14) dia = \"Bastille\";\n }\n if (month == 8)\n {\n }\n if (month == 9)\n {\n if (day == 19) dia = \"Pirate\";\n }\n if (month == 10)\n {\n if (day == 3) dia = \"Germany\";\n if (day == 12) dia = \"Columbus\";\n if (day == 31) dia = \"Halloween\";\n }\n if (month == 11)\n {\n if (day == 2) dia = \"Muertos\";\n }\n if (month == 12)\n {\n if (day >= 22 && day <= 26) dia = \"Christmas\";\n if (day == 31) dia = \"NewYear\";\n }\n //LogHelper.info(\"Today is: \" + day + \"/\" + month + \"/\" + year + \". Which means today is: \" + dia);\n return dia;\n\n }\n\n public static int isBlockRegisteredAsFluid(Block block)\n {\n /*\n * for (Map.Entry<String,Fluid> fluid :\n\t\t * getRegisteredFluids().entrySet()) { int ID =\n\t\t * (fluid.getValue().getBlockID() == BlockID) ? fluid.getValue().getID()\n\t\t * : -1; if (ID > 0) return ID; }\n\t\t */\n int fluidID = -1;\n for (Fluid fluid : FluidRegistry.getRegisteredFluids().values())\n {\n fluidID = (fluid.getBlock() == block) ? fluid.getID() : -1;\n if (fluidID > 0)\n {\n return fluidID;\n }\n }\n return fluidID;\n }\n\n public static boolean shouldGiveEmpty(ItemStack cont)\n {\n boolean valid = true;\n // System.out.println(\"Item class name is: \"+cont.getItem().getClass().getName());\n\n try\n {\n // Industrialcraft cells\n // if (apis.ic2.api.item.Items.getItem(\"cell\").getClass().isInstance(cont.getItem()))\n // {\n // valid = false;\n // }\n // Forestry capsules\n if (java.lang.Class.forName(\"forestry.core.items.ItemLiquidContainer\").isInstance(cont.getItem()))\n {\n valid = false;\n }\n } catch (Exception oops)\n {\n\n }\n // Others\n\n return valid;\n }\n\n public static ChunkCoordinates findBlock2D(World world, int x, int y, int z, Block block, int range)\n {\n for (int i = x - range; i <= x + range; i++)\n {\n for (int j = z - range; j <= z + range; j++)\n {\n if (world.getBlock(i, y, j) == block)\n {\n return new ChunkCoordinates(i, y, j);\n }\n }\n }\n return null;\n }\n\n public static ChunkCoordinates findBlock3D(World world, int x, int y, int z, Block block, int hRange, int vRange)\n {\n for (int i = (y - vRange); i <= (y + vRange); i++)\n {\n for (int j = (x - hRange); j <= (x + hRange); j++)\n {\n for (int k = (z - hRange); k <= (z + hRange); k++)\n {\n if (world.getBlock(j, i, k) == block)\n {\n return new ChunkCoordinates(j, i, k);\n }\n }\n }\n }\n return null;\n }\n\n public static String capitalize(String s)\n {\n // Character.toUpperCase(itemName.charAt(0)) + itemName.substring(1);\n return s.substring(0, 1).toUpperCase().concat(s.substring(1));\n }\n\n public static int getOppositeCardinalFromMeta(int meta)\n {\n return (meta % 2 == 0) ? (meta == 0) ? 2 : 0 : ((meta + 1) % 4) + 1;\n }\n\n //This is some black magic that returns a block or entity as far as the argument reach goes.\n public static MovingObjectPosition getMovingObjectPositionFromPlayersHat(World world, EntityPlayer player, boolean flag, double reach)\n {\n float f = 1.0F;\n float playerPitch = player.prevRotationPitch\n + (player.rotationPitch - player.prevRotationPitch) * f;\n float playerYaw = player.prevRotationYaw\n + (player.rotationYaw - player.prevRotationYaw) * f;\n double playerPosX = player.prevPosX + (player.posX - player.prevPosX)\n * f;\n double playerPosY = (player.prevPosY + (player.posY - player.prevPosY)\n * f + 1.6200000000000001D)\n - player.yOffset;\n double playerPosZ = player.prevPosZ + (player.posZ - player.prevPosZ)\n * f;\n Vec3 vecPlayer = Vec3.createVectorHelper(playerPosX, playerPosY,\n playerPosZ);\n float cosYaw = (float) Math.cos(-playerYaw * 0.01745329F - 3.141593F);\n float sinYaw = (float) Math.sin(-playerYaw * 0.01745329F - 3.141593F);\n float cosPitch = (float) -Math.cos(-playerPitch * 0.01745329F);\n float sinPitch = (float) Math.sin(-playerPitch * 0.01745329F);\n float pointX = sinYaw * cosPitch;\n float pointY = sinPitch;\n float pointZ = cosYaw * cosPitch;\n Vec3 vecPoint = vecPlayer.addVector(pointX * reach, pointY * reach,\n pointZ * reach);\n return world.func_147447_a/*rayTraceBlocks_do_do*/(\n vecPlayer, vecPoint, flag, !flag, flag);\n }\n\n public static String printCoordinates(int x, int y, int z)\n {\n return \"X= \" + x + \", Y= \" + y + \", Z= \" + z;\n }\n\n\n public static int secondsToTicks(int seconds)\n {\n return seconds * 20;\n }\n\n public static int secondsToTicks(float seconds)\n {\n return (int) seconds * 20;\n }\n\n public static boolean inServer()\n {\n Side side = FMLCommonHandler.instance().getEffectiveSide();\n return side == Side.SERVER;\n }\n\n private static ChunkCoordinates checkCoordsForBackpack(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, boolean except)\n {\n //LogHelper.info(\"Checking coordinates in X=\"+X+\", Y=\"+Y+\", Z=\"+Z);\n if (except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z) && !areCoordinatesTheSame(origX, Y, origZ, X, Y, Z))\n {\n //LogHelper.info(\"Found spot with the exception of the death point\");\n return new ChunkCoordinates(X, Y, Z);\n }\n if (!except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z))\n {\n //LogHelper.info(\"Found spot without exceptions\");\n return new ChunkCoordinates(X, Y, Z);\n }\n return null;\n }\n\n private static ChunkCoordinates checkCoordsForPlayer(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, boolean except)\n {\n LogHelper.info(\"Checking coordinates in X=\"+X+\", Y=\"+Y+\", Z=\"+Z);\n if (except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z) && world.isAirBlock(X,Y+1,Z) && !areCoordinatesTheSame2D(origX, origZ, X, Z))\n {\n LogHelper.info(\"Found spot with the exception of the origin point\");\n return new ChunkCoordinates(X, Y, Z);\n }\n if (!except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z)&& world.isAirBlock(X,Y+1,Z))\n {\n LogHelper.info(\"Found spot without exceptions\");\n return new ChunkCoordinates(X, Y, Z);\n }\n return null;\n }\n\n /**\n * Gets you the nearest Empty Chunk Coordinates, free of charge! Looks in two dimensions and finds a block\n * that a: can have stuff placed on it and b: has space above it.\n * This is a spiral search, will begin at close range and move out.\n * @param world The world object.\n * @param origX Original X coordinate\n * @param origZ Original Z coordinate\n * @param X Moving X coordinate, should be the same as origX when called.\n * @param Y Y coordinate, does not move.\n * @param Z Moving Z coordinate, should be the same as origZ when called.\n * @param radius The radius of the search. If set to high numbers, will create a ton of lag\n * @param except Wether to include the origin of the search as a valid block.\n * @param steps Number of steps of the recursive recursiveness that recurses through the recursion. It is the first size of the spiral, should be one (1) always at the first call.\n * @param pass Pass switch for the witchcraft I can't quite explain. Set to 0 always at the beggining.\n * @param type True = for player, False = for backpack\n * @return The coordinates of the block in the chunk of the world of the game of the server of the owner of the computer, where you can place something above it.\n */\n public static ChunkCoordinates getNearestEmptyChunkCoordinatesSpiral(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, int radius, boolean except, int steps, byte pass, boolean type)\n {\n //Spiral search, because I'm awesome :)\n //This is so the backpack tries to get placed near the death point first\n //And then goes looking farther away at each step\n //Steps mod 2 == 0 => X++, Z--\n //Steps mod 2 == 1 => X--, Z++\n\n //\n if (steps >= radius) return null;\n int i = X, j = Z;\n if (steps % 2 == 0)\n {\n if (pass == 0)\n {\n for (; i <= X + steps; i++)\n {\n\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n if (pass == 1)\n {\n for (; j >= Z - steps; j--)\n {\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass--;\n steps++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n }\n\n if (steps % 2 == 1)\n {\n if (pass == 0)\n {\n for (; i >= X - steps; i--)\n {\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n if (pass == 1)\n {\n for (; j <= Z + steps; j++)\n {\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass--;\n steps++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n }\n\n /* Old code. Still works, though.\n for (int i = x - radius; i <= x + radius; i++)\n {\n for (int j = y - (radius / 2); j <= y + (radius / 2); j++)\n {\n for (int k = z + radius; k <= z + (radius); k++)\n {\n if (except && world.isSideSolid(i, j - 1, k, ForgeDirection.UP) && world.isAirBlock(i, j, k) && !areCoordinatesTheSame(x, y, z, i, j, k))\n {\n return new ChunkCoordinates(i, j, k);\n }\n if (!except && world.isSideSolid(i, j - 1, k, ForgeDirection.UP) && world.isAirBlock(i, j, k))\n {\n return new ChunkCoordinates(i, j, k);\n }\n }\n }\n }*/\n return null;\n }\n\n /**\n * Compares two coordinates. Heh.\n *\n * @param X1 First coordinate X.\n * @param Y1 First coordinate Y.\n * @param Z1 First coordinate Z.\n * @param X2 Second coordinate X.\n * @param Y2 Second coordinate Y.\n * @param Z2 Second coordinate Z. I really didn't need to type all that, its obvious.\n * @return If both coordinates are the same, returns true. This is the least helpful javadoc ever.\n */\n private static boolean areCoordinatesTheSame(int X1, int Y1, int Z1, int X2, int Y2, int Z2)\n {\n return (X1 == X2 && Y1 == Y2 && Z1 == Z2);\n }\n\n private static boolean areCoordinatesTheSame2D(int X1, int Z1, int X2, int Z2)\n {\n return (X1 == X2 && Z1 == Z2);\n }\n\n /**\n * Seriously why doesn't Java's instanceof check for null?\n * @return true if the object is not null and is an instance of the supplied class.\n */\n public static boolean notNullAndInstanceOf(Object object, Class clazz)\n {\n return object != null && clazz.isInstance(object);\n }\n\n public static String getFirstWord(String text)\n {\n if (text.indexOf(' ') > -1)\n { // Check if there is more than one word.\n String firstWord = text.substring(0, text.indexOf(' '));\n String secondWord = text.substring(text.indexOf(' ') + 1);\n return firstWord.equals(\"Molten\") ? secondWord : firstWord;// Extract first word.\n } else\n {\n return text; // Text is the first word itself.\n }\n }\n}" ]
import com.darkona.adventurebackpack.common.ServerActions; import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.entity.EntityFriendlySpider; import com.darkona.adventurebackpack.entity.ai.EntityAIHorseFollowOwner; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.init.ModItems; import com.darkona.adventurebackpack.item.IBackWearableItem; import com.darkona.adventurebackpack.playerProperties.BackpackProperty; import com.darkona.adventurebackpack.proxy.ServerProxy; import com.darkona.adventurebackpack.reference.BackpackNames; import com.darkona.adventurebackpack.util.LogHelper; import com.darkona.adventurebackpack.util.Utils; import com.darkona.adventurebackpack.util.Wearing; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.gameevent.TickEvent; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.ItemNameTag; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.PlayerWakeUpEvent;
package com.darkona.adventurebackpack.handlers; /** * Created on 11/10/2014 * Handle ALL the events! * * @author Darkona * @see com.darkona.adventurebackpack.client.ClientActions */ public class PlayerEventHandler { private static int tickCounter = 0; @SubscribeEvent public void registerBackpackProperty(EntityEvent.EntityConstructing event) { if (event.entity instanceof EntityPlayer && BackpackProperty.get((EntityPlayer) event.entity) == null) { BackpackProperty.register((EntityPlayer) event.entity); /*if (!event.entity.worldObj.isRemote) { AdventureBackpack.proxy.joinPlayer((EntityPlayer)event.entity); }*/ } } @SubscribeEvent public void joinPlayer(EntityJoinWorldEvent event) { if (!event.world.isRemote) {
if (Utils.notNullAndInstanceOf(event.entity, EntityPlayer.class))
5
philliphsu/ClockPlus
app/src/main/java/com/philliphsu/clock2/timers/ui/TimersFragment.java
[ "public class EditTimerActivity extends BaseActivity implements AddLabelDialog.OnLabelSetListener {\n private static final int FIELD_LENGTH = 2;\n private static final String KEY_LABEL = \"key_label\";\n\n public static final String EXTRA_HOUR = \"com.philliphsu.clock2.edittimer.extra.HOUR\";\n public static final String EXTRA_MINUTE = \"com.philliphsu.clock2.edittimer.extra.MINUTE\";\n public static final String EXTRA_SECOND = \"com.philliphsu.clock2.edittimer.extra.SECOND\";\n public static final String EXTRA_LABEL = \"com.philliphsu.clock2.edittimer.extra.LABEL\";\n public static final String EXTRA_START_TIMER = \"com.philliphsu.clock2.edittimer.extra.START_TIMER\";\n\n private AddLabelDialogController mAddLabelDialogController;\n\n @Bind(R.id.edit_fields_layout) ViewGroup mEditFieldsLayout;\n @Bind(R.id.label) TextView mLabel;\n @Bind(R.id.hour) EditText mHour;\n @Bind(R.id.minute) EditText mMinute;\n @Bind(R.id.second) EditText mSecond;\n @Bind(R.id.hour_label) TextView mHourLabel;\n @Bind(R.id.minute_label) TextView mMinuteLabel;\n @Bind(R.id.second_label) TextView mSecondLabel;\n @Bind(R.id.focus_grabber) View mFocusGrabber;\n @Bind(R.id.fab) FloatingActionButton mFab;\n // Intentionally not using a (subclass of) GridLayoutNumpad, because\n // it is expedient to not adapt it for timers.\n @Bind(R.id.numpad) GridLayout mNumpad;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (savedInstanceState != null) {\n mLabel.setText(savedInstanceState.getCharSequence(KEY_LABEL));\n }\n mAddLabelDialogController = new AddLabelDialogController(getSupportFragmentManager(), this);\n mAddLabelDialogController.tryRestoreCallback(makeTag(R.id.label));\n }\n\n @Override\n protected int layoutResId() {\n return R.layout.activity_edit_timer;\n }\n\n @Override\n protected int menuResId() {\n // TODO: Define a menu res with a save item\n return 0;\n }\n\n @Override\n public void finish() {\n super.finish();\n }\n\n @Override\n public void onLabelSet(String label) {\n mLabel.setText(label);\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putCharSequence(KEY_LABEL, mLabel.getText());\n }\n\n @OnClick({ R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four,\n R.id.five, R.id.six, R.id.seven, R.id.eight, R.id.nine })\n void onClick(TextView view) {\n if (mFocusGrabber.isFocused())\n return;\n EditText field = getFocusedField();\n int at = field.getSelectionStart();\n field.getText().replace(at, at + 1, view.getText());\n field.setSelection(at + 1);\n// updateStartButtonVisibility();\n if (field.getSelectionStart() == FIELD_LENGTH) {\n // At the end of the current field, so try to focus to the next field.\n // The search will return null if no view can be focused next.\n View next = field.focusSearch(View.FOCUS_RIGHT);\n if (next != null) {\n next.requestFocus();\n if (next instanceof EditText) {\n // Should always start off at the beginning of the field\n ((EditText) next).setSelection(0);\n }\n }\n }\n }\n\n @OnTouch({ R.id.hour, R.id.minute, R.id.second })\n boolean switchField(EditText field, MotionEvent event) {\n int inType = field.getInputType(); // backup the input type\n field.setInputType(InputType.TYPE_NULL); // disable soft input\n boolean result = field.onTouchEvent(event); // call native handler\n field.setInputType(inType); // restore input type (to show cursor)\n return result;\n }\n\n @OnClick(R.id.backspace)\n void backspace() {\n if (mFocusGrabber.isFocused()) {\n mEditFieldsLayout.focusSearch(mFocusGrabber, View.FOCUS_LEFT).requestFocus();\n }\n EditText field = getFocusedField();\n if (field == null)\n return;\n int at = field.getSelectionStart();\n if (at == 0) {\n // At the beginning of current field, so move focus\n // to the preceding field\n View prev = field.focusSearch(View.FOCUS_LEFT);\n if (null == prev) {\n // Reached the beginning of the hours field\n return;\n }\n if (prev.requestFocus()) {\n if (prev instanceof EditText) {\n // Always move the cursor to the end when moving focus back\n ((EditText) prev).setSelection(FIELD_LENGTH);\n }\n // Recursively backspace on the newly focused field\n backspace();\n }\n } else {\n field.getText().replace(at - 1, at, \"0\");\n field.setSelection(at - 1);\n// updateStartButtonVisibility();\n }\n }\n \n @OnLongClick(R.id.backspace)\n boolean clear() {\n mHour.setText(\"00\");\n mMinute.setText(\"00\");\n mSecond.setText(\"00\");\n mHour.requestFocus(); // TOneverDO: call after setSelection(0), or else the cursor returns to the end of the text\n mHour.setSelection(0); // always move the cursor WHILE the field is focused, NEVER focus after!\n mMinute.setSelection(0);\n mSecond.setSelection(0);\n// mFab.hide(); // instead of updateStartButtonVisibility() because we know everything's zero\n return true;\n }\n\n @OnClick(R.id.label)\n void openEditLabelDialog() {\n mAddLabelDialogController.show(mLabel.getText(), makeTag(R.id.label));\n }\n\n @OnClick(R.id.fab)\n void startTimer() {\n int hour = Integer.parseInt(mHour.getText().toString());\n int minute = Integer.parseInt(mMinute.getText().toString());\n int second = Integer.parseInt(mSecond.getText().toString());\n if (hour == 0 && minute == 0 && second == 0)\n return; // TODO: we could show a toast instead if we cared\n // TODO: Consider overriding finish() and doing this there.\n // TODO: Timer's group?\n Intent data = new Intent()\n .putExtra(EXTRA_HOUR, hour)\n .putExtra(EXTRA_MINUTE, minute)\n .putExtra(EXTRA_SECOND, second)\n .putExtra(EXTRA_LABEL, mLabel.getText().toString())\n .putExtra(EXTRA_START_TIMER, true);\n setResult(RESULT_OK, data);\n finish();\n }\n\n private EditText getFocusedField() {\n return (EditText) mEditFieldsLayout.findFocus();\n }\n\n private static String makeTag(@IdRes int viewId) {\n return FragmentTagUtils.makeTag(EditTimerActivity.class, viewId);\n }\n}", "public final class AsyncTimersTableUpdateHandler extends AsyncDatabaseTableUpdateHandler<Timer, TimersTableManager> {\n private static final String TAG = \"TimersTableUpdater\"; // TAG max 23 chars\n\n public AsyncTimersTableUpdateHandler(Context context, ScrollHandler scrollHandler) {\n super(context, scrollHandler);\n }\n\n @Override\n protected TimersTableManager onCreateTableManager(Context context) {\n return new TimersTableManager(context);\n }\n\n @Override\n protected void onPostAsyncDelete(Integer result, Timer timer) {\n cancelAlarm(timer, true);\n }\n\n @Override\n protected void onPostAsyncInsert(Long result, Timer timer) {\n if (timer.isRunning()) {\n scheduleAlarm(timer);\n }\n }\n\n @Override\n protected void onPostAsyncUpdate(Long result, Timer timer) {\n Log.d(TAG, \"onPostAsyncUpdate, timer = \" + timer);\n if (timer.isRunning()) {\n // We don't need to cancel the previous alarm, because this one\n // will remove and replace it.\n scheduleAlarm(timer);\n } else {\n boolean removeNotification = !timer.hasStarted();\n cancelAlarm(timer, removeNotification);\n if (!removeNotification) {\n // Post a new notification to reflect the paused state of the timer\n TimerNotificationService.showNotification(getContext(), timer);\n }\n }\n }\n\n // TODO: Consider changing to just a long id param\n private PendingIntent createTimesUpIntent(Timer timer) {\n Intent intent = new Intent(getContext(), TimesUpActivity.class);\n intent.putExtra(TimesUpActivity.EXTRA_RINGING_OBJECT, ParcelableUtil.marshall(timer));\n // There's no point to determining whether to retrieve a previous instance, because\n // we chose to ignore it since we had issues with NPEs. TODO: Perhaps these issues\n // were caused by you using the same reference variable for every Intent/PI that\n // needed to be recreated, and you reassigning the reference each time you were done with\n // one of them, which leaves the one before unreferenced and hence eligible for GC.\n return PendingIntent.getActivity(getContext(), timer.getIntId(), intent, PendingIntent.FLAG_CANCEL_CURRENT);\n }\n\n private void scheduleAlarm(Timer timer) {\n AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);\n am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, timer.endTime(), createTimesUpIntent(timer));\n TimerNotificationService.showNotification(getContext(), timer);\n }\n\n private void cancelAlarm(Timer timer, boolean removeNotification) {\n // Cancel the alarm scheduled. If one was never scheduled, does nothing.\n AlarmManager am = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);\n PendingIntent pi = createTimesUpIntent(timer);\n // Now can't be null\n am.cancel(pi);\n pi.cancel();\n if (removeNotification) {\n TimerNotificationService.cancelNotification(getContext(), timer.getId());\n }\n // Won't do anything if not actually started\n // This was actually a problem for successive Timers. We actually don't need to\n // manually stop the service in many cases. See usages of TimerController.stop().\n// getContext().stopService(new Intent(getContext(), TimerRingtoneService.class));\n // TODO: Do we need to finish TimesUpActivity?\n }\n}", "public abstract class RecyclerViewFragment<\n T extends ObjectWithId,\n VH extends BaseViewHolder<T>,\n C extends BaseItemCursor<T>,\n A extends BaseCursorAdapter<T, VH, C>>\n extends BaseFragment implements\n LoaderManager.LoaderCallbacks<C>,\n OnListItemInteractionListener<T>,\n ScrollHandler {\n\n public static final String ACTION_SCROLL_TO_STABLE_ID = \"com.philliphsu.clock2.list.action.SCROLL_TO_STABLE_ID\";\n public static final String EXTRA_SCROLL_TO_STABLE_ID = \"com.philliphsu.clock2.list.extra.SCROLL_TO_STABLE_ID\";\n\n private A mAdapter;\n private long mScrollToStableId = RecyclerView.NO_ID;\n\n // TODO: Rename id to recyclerView?\n // TODO: Rename variable to mRecyclerView?\n @Bind(R.id.list)\n RecyclerView mList;\n\n @Nullable // Subclasses are not required to use the default content layout, so this may not be present.\n @Bind(R.id.empty_view)\n TextView mEmptyView;\n\n public abstract void onFabClick();\n\n /**\n * Callback invoked when we have scrolled to the stable id as set in\n * {@link #setScrollToStableId(long)}.\n * @param id the stable id we have scrolled to\n * @param position the position of the item with this stable id\n */\n protected abstract void onScrolledToStableId(long id, int position);\n\n /**\n * @return the adapter to set on the RecyclerView. Called in onCreateView().\n */\n protected abstract A onCreateAdapter();\n\n /**\n * @return a resource to a String that will be displayed when the list is empty\n */\n @StringRes\n protected int emptyMessage() {\n // The reason this isn't abstract is so we don't require subclasses that\n // don't have an empty view to implement this.\n return 0;\n }\n\n /**\n * @return a resource to a Drawable that will be displayed when the list is empty\n */\n @DrawableRes\n protected int emptyIcon() {\n // The reason this isn't abstract is so we don't require subclasses that\n // don't have an empty view to implement this.\n return 0;\n }\n\n /**\n * @return whether the list should show an empty view when its adapter has an item count of zero\n */\n protected boolean hasEmptyView() {\n return true;\n }\n\n /**\n * @return the adapter instance created from {@link #onCreateAdapter()}\n */\n protected final A getAdapter() {\n return mAdapter;\n }\n\n /**\n * @return the LayoutManager to set on the RecyclerView. The default implementation\n * returns a vertical LinearLayoutManager.\n */\n protected RecyclerView.LayoutManager getLayoutManager() {\n // Called in onCreateView(), so the host activity is alive already.\n return new LinearLayoutManager(getActivity());\n }\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View view = super.onCreateView(inflater, container, savedInstanceState);\n mList.setLayoutManager(getLayoutManager());\n mList.setAdapter(mAdapter = onCreateAdapter());\n if (hasEmptyView() && mEmptyView != null) {\n // Configure the empty view, even if there currently are items.\n mEmptyView.setText(emptyMessage());\n mEmptyView.setCompoundDrawablesRelativeWithIntrinsicBounds(0, emptyIcon(), 0, 0);\n }\n return view;\n }\n\n @Override\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\n super.onActivityCreated(savedInstanceState);\n // http://stackoverflow.com/a/14632434/5055032\n // A Loader's lifecycle is bound to its Activity, not its Fragment.\n getLoaderManager().initLoader(0, null, this);\n }\n\n @Override\n public void onLoadFinished(Loader<C> loader, C data) {\n mAdapter.swapCursor(data);\n if (hasEmptyView() && mEmptyView != null) {\n // TODO: Last I checked after a fresh install, this worked fine.\n // However, previous attempts (without fresh installs) didn't hide the empty view\n // upon an item being added. Verify this is no longer the case.\n mEmptyView.setVisibility(mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);\n }\n // This may have been a requery due to content change. If the change\n // was an insertion, scroll to the last modified alarm.\n performScrollToStableId(mScrollToStableId);\n mScrollToStableId = RecyclerView.NO_ID;\n }\n\n @Override\n public void onLoaderReset(Loader<C> loader) {\n mAdapter.swapCursor(null);\n }\n\n /**\n * @return a layout resource that MUST contain a RecyclerView. The default implementation\n * returns a layout that has just a single RecyclerView in its hierarchy.\n */\n @Override\n protected int contentLayout() {\n return R.layout.fragment_recycler_view;\n }\n\n @Override\n public void setScrollToStableId(long id) {\n mScrollToStableId = id;\n }\n\n @Override\n public void scrollToPosition(int position) {\n mList.smoothScrollToPosition(position);\n }\n\n public final void performScrollToStableId(long stableId) {\n if (stableId != RecyclerView.NO_ID) {\n int position = -1;\n for (int i = 0; i < mAdapter.getItemCount(); i++) {\n if (mAdapter.getItemId(i) == stableId) {\n position = i;\n break;\n }\n }\n if (position >= 0) {\n scrollToPosition(position);\n onScrolledToStableId(stableId, position);\n }\n }\n }\n}", "@AutoValue\npublic abstract class Timer extends ObjectWithId implements Parcelable {\n private static final long MINUTE = TimeUnit.MINUTES.toMillis(1);\n\n private long endTime;\n private long pauseTime;\n private long duration;\n\n // Using this crashes the app when we create a Timer and start it...\n // timeRemaining() is returning a negative value... but it doesn't even\n // consider duration()....?\n // My guess is the hour, minute, and second getters are returning 0\n // at this point...?\n// private final long normalDuration = TimeUnit.HOURS.toMillis(hour())\n// + TimeUnit.MINUTES.toMillis(minute())\n// + TimeUnit.SECONDS.toMillis(second());\n\n public abstract int hour();\n public abstract int minute();\n public abstract int second();\n // 9/6/2016: Just found/fixed a very subtle bug involving mixing up the parameter orders\n // of group and label when `create()`ing a Timer in TimerCursor.\n // TODO: We have never used this at all, so consider deleting this!\n public abstract String group();\n public abstract String label();\n\n public static Timer create(int hour, int minute, int second) {\n return create(hour, minute, second, \"\", \"\");\n }\n\n public static Timer createWithGroup(int hour, int minute, int second, String group) {\n return create(hour, minute, second, group, \"\");\n }\n\n public static Timer createWithLabel(int hour, int minute, int second, String label) {\n return create(hour, minute, second, \"\", label);\n }\n\n public static Timer create(int hour, int minute, int second, String group, String label) {\n if (hour < 0 || minute < 0 || second < 0 || (hour == 0 && minute == 0 && second == 0))\n throw new IllegalArgumentException(\"Cannot create a timer with h = \"\n + hour + \", m = \" + minute + \", s = \" + second);\n return new AutoValue_Timer(hour, minute, second, group, label);\n }\n\n public void copyMutableFieldsTo(Timer target) {\n target.setId(this.getId());\n target.endTime = this.endTime;\n target.pauseTime = this.pauseTime;\n target.duration = this.duration;\n }\n\n public long endTime() {\n return endTime;\n }\n\n public boolean expired() {\n return /*!hasStarted() ||*/endTime <= SystemClock.elapsedRealtime();\n }\n\n public long timeRemaining() {\n if (!hasStarted())\n // TODO: Consider returning duration instead? So we can simplify\n // bindChronometer() in TimerVH to:\n // if (isRunning())\n // ...\n // else\n // chronom.setDuration(timeRemaining())\n // ---\n // Actually, I think we can also simplify it even further to just:\n // chronom.setDuration(timeRemaining())\n // if (isRunning)\n // chronom.start();\n return 0;\n return isRunning()\n ? endTime - SystemClock.elapsedRealtime()\n : endTime - pauseTime;\n }\n\n public long duration() {\n if (duration == 0) {\n duration = TimeUnit.HOURS.toMillis(hour())\n + TimeUnit.MINUTES.toMillis(minute())\n + TimeUnit.SECONDS.toMillis(second());\n }\n return duration;\n }\n\n public void start() {\n if (isRunning())\n throw new IllegalStateException(\"Cannot start a timer that has already started OR is already running\");\n // TOneverDO: use nanos, AlarmManager expects times in millis\n endTime = SystemClock.elapsedRealtime() + duration();\n }\n\n public void pause() {\n if (!isRunning())\n throw new IllegalStateException(\"Cannot pause a timer that is not running OR has not started\");\n pauseTime = SystemClock.elapsedRealtime();\n }\n\n public void resume() {\n if (!hasStarted() || isRunning())\n throw new IllegalStateException(\"Cannot resume a timer that is already running OR has not started\");\n endTime += SystemClock.elapsedRealtime() - pauseTime;\n pauseTime = 0;\n }\n\n public void stop() {\n endTime = 0;\n pauseTime = 0;\n duration = 0;\n }\n\n public void addOneMinute() {\n if (!isRunning()) {\n resume();\n addOneMinute(); // recursion!\n pause();\n return;\n } else if (expired()) {\n endTime = SystemClock.elapsedRealtime() + MINUTE;\n // If the timer's normal duration is >= MINUTE, then an extra run time of one minute\n // will still be within the normal duration. Thus, the progress calculation does not\n // need to change. For example, if the timer's normal duration is 2 minutes, an extra\n // 1 minute run time is fully encapsulated within the 2 minute upper bound.\n if (duration < MINUTE) {\n // This scales the progress bar to a full minute.\n duration = MINUTE;\n }\n return;\n }\n\n endTime += MINUTE;\n duration += MINUTE;\n }\n\n public boolean hasStarted() {\n return endTime > 0;\n }\n\n public boolean isRunning() {\n return hasStarted() && pauseTime == 0;\n }\n\n /**\n * TO ONLY BE CALLED BY TIMERDATABASEHELPER.\n */\n public void setEndTime(long endTime) {\n this.endTime = endTime;\n }\n\n /**\n * TO ONLY BE CALLED BY TIMERDATABASEHELPER.\n */\n public void setPauseTime(long pauseTime) {\n this.pauseTime = pauseTime;\n }\n\n /**\n * TO ONLY BE CALLED BY TIMERDATABASEHELPER.\n */\n public long pauseTime() {\n return pauseTime;\n }\n\n /**\n * TO ONLY BE CALLED BY TIMERDATABASEHELPER.\n */\n public void setDuration(long duration) {\n this.duration = duration;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(hour());\n dest.writeInt(minute());\n dest.writeInt(second());\n dest.writeString(group());\n dest.writeString(label());\n dest.writeLong(getId());\n dest.writeLong(endTime);\n dest.writeLong(pauseTime);\n dest.writeLong(duration);\n }\n\n public static final Creator<Timer> CREATOR = new Creator<Timer>() {\n @Override\n public Timer createFromParcel(Parcel source) {\n return Timer.create(source);\n }\n\n @Override\n public Timer[] newArray(int size) {\n return new Timer[size];\n }\n };\n\n private static Timer create(Parcel source) {\n Timer t = Timer.create(source.readInt(), source.readInt(), source.readInt(),\n source.readString(), source.readString());\n t.setId(source.readLong());\n t.endTime = source.readLong();\n t.pauseTime = source.readLong();\n t.duration = source.readLong();\n return t;\n }\n}", "public class TimerCursor extends BaseItemCursor<Timer> {\n\n public TimerCursor(Cursor cursor) {\n super(cursor);\n }\n\n @Override\n public Timer getItem() {\n if (isBeforeFirst() || isAfterLast())\n return null;\n int hour = getInt(getColumnIndexOrThrow(TimersTable.COLUMN_HOUR));\n int minute = getInt(getColumnIndexOrThrow(TimersTable.COLUMN_MINUTE));\n int second = getInt(getColumnIndexOrThrow(TimersTable.COLUMN_SECOND));\n String label = getString(getColumnIndexOrThrow(TimersTable.COLUMN_LABEL));\n// String group = getString(getColumnIndexOrThrow(COLUMN_GROUP));\n Timer t = Timer.create(hour, minute, second, \"\"/*group*/, label);\n t.setId(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_ID)));\n t.setEndTime(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_END_TIME)));\n t.setPauseTime(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_PAUSE_TIME)));\n t.setDuration(getLong(getColumnIndexOrThrow(TimersTable.COLUMN_DURATION)));\n return t;\n }\n}", "public class TimersListCursorLoader extends SQLiteCursorLoader<Timer, TimerCursor> {\n public static final String ACTION_CHANGE_CONTENT\n = \"com.philliphsu.clock2.timers.data.action.CHANGE_CONTENT\";\n\n public TimersListCursorLoader(Context context) {\n super(context);\n }\n\n @Override\n protected TimerCursor loadCursor() {\n return new TimersTableManager(getContext()).queryItems();\n }\n\n @Override\n protected String getOnContentChangeAction() {\n return ACTION_CHANGE_CONTENT;\n }\n}", "public static int getOrientation(Resources res) {\n return res.getConfiguration().orientation;\n}" ]
import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.Loader; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.philliphsu.clock2.timers.EditTimerActivity; import com.philliphsu.clock2.timers.data.AsyncTimersTableUpdateHandler; import com.philliphsu.clock2.R; import com.philliphsu.clock2.list.RecyclerViewFragment; import com.philliphsu.clock2.timers.Timer; import com.philliphsu.clock2.timers.data.TimerCursor; import com.philliphsu.clock2.timers.data.TimersListCursorLoader; import static butterknife.ButterKnife.findById; import static com.philliphsu.clock2.util.ConfigurationUtils.getOrientation;
/* * Copyright 2017 Phillip Hsu * * This file is part of ClockPlus. * * ClockPlus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ClockPlus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ClockPlus. If not, see <http://www.gnu.org/licenses/>. */ package com.philliphsu.clock2.timers.ui; public class TimersFragment extends RecyclerViewFragment<Timer, TimerViewHolder, TimerCursor, TimersCursorAdapter> { // TODO: Different number of columns for different display densities, instead of landscape. // Use smallest width qualifiers. I can imagine 3 or 4 columns for a large enough tablet in landscape. private static final int LANDSCAPE_LAYOUT_COLUMNS = 2; public static final int REQUEST_CREATE_TIMER = 0; public static final String EXTRA_SCROLL_TO_TIMER_ID = "com.philliphsu.clock2.timers.extra.SCROLL_TO_TIMER_ID"; private AsyncTimersTableUpdateHandler mAsyncTimersTableUpdateHandler; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAsyncTimersTableUpdateHandler = new AsyncTimersTableUpdateHandler(getActivity(), this); long scrollToStableId = getActivity().getIntent().getLongExtra(EXTRA_SCROLL_TO_TIMER_ID, -1); if (scrollToStableId != -1) { setScrollToStableId(scrollToStableId); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); final Resources r = getResources(); if (getOrientation(r) == Configuration.ORIENTATION_LANDSCAPE) { RecyclerView list = findById(view, R.id.list); int cardViewMargin = r.getDimensionPixelSize(R.dimen.cardview_margin); list.setPaddingRelative(cardViewMargin/*start*/, cardViewMargin/*top*/, 0, list.getPaddingBottom()); } return view; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK || data == null) return; // TODO: From EditTimerActivity, pass back the Timer as a parcelable and // retrieve it here directly. int hour = data.getIntExtra(EditTimerActivity.EXTRA_HOUR, -1); int minute = data.getIntExtra(EditTimerActivity.EXTRA_MINUTE, -1); int second = data.getIntExtra(EditTimerActivity.EXTRA_SECOND, -1); String label = data.getStringExtra(EditTimerActivity.EXTRA_LABEL); boolean startTimer = data.getBooleanExtra(EditTimerActivity.EXTRA_START_TIMER, false); // TODO: Timer's group? Timer t = Timer.createWithLabel(hour, minute, second, label); if (startTimer) { t.start(); } mAsyncTimersTableUpdateHandler.asyncInsert(t); } @Override public void onFabClick() { Intent intent = new Intent(getActivity(), EditTimerActivity.class); startActivityForResult(intent, REQUEST_CREATE_TIMER); } @Override protected TimersCursorAdapter onCreateAdapter() { // Create a new adapter. This is called before we can initialize mAsyncTimersTableUpdateHandler, // so right now it is null. However, after super.onCreate() returns, it is initialized, and // the reference variable will be pointing to an actual object. This assignment "propagates" // to all references to mAsyncTimersTableUpdateHandler. return new TimersCursorAdapter(this, mAsyncTimersTableUpdateHandler); } @Override protected RecyclerView.LayoutManager getLayoutManager() { switch (getOrientation(getResources())) { case Configuration.ORIENTATION_LANDSCAPE: return new GridLayoutManager(getActivity(), LANDSCAPE_LAYOUT_COLUMNS); default: return super.getLayoutManager(); } } @Override protected int emptyMessage() { return R.string.empty_timers_container; } @Override protected int emptyIcon() { return R.drawable.ic_timer_96dp; } @Override public Loader<TimerCursor> onCreateLoader(int id, Bundle args) {
return new TimersListCursorLoader(getActivity());
5
cm-heclouds/JAVA-HTTP-SDK
javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/device/GetDevicesStatus.java
[ "public abstract class AbstractAPI<T> {\n public String key;\n public String url;\n public Method method;\n public ObjectMapper mapper = initObjectMapper();\n\n private ObjectMapper initObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n //关闭字段不识别报错\n objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n //调整默认时区为北京时间\n TimeZone timeZone = TimeZone.getTimeZone(\"GMT+8\");\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\n dateFormat.setTimeZone(timeZone);\n objectMapper.setDateFormat(dateFormat);\n objectMapper.setTimeZone(timeZone);\n return objectMapper;\n }\n}", "public class OnenetApiException extends RuntimeException {\n\t private String message = null;\n\t public String getMessage() {\n\t\treturn message;\n\t}\n\t\tpublic OnenetApiException( String message) {\n\t this.message = message;\n\t }\n}", "public class HttpGetMethod extends BasicHttpMethod {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\tHttpGet httpGet;\n\n\tpublic HttpGetMethod(Method method) {\n\t\tsuper(method);\n\n\t}\n\n\tpublic HttpResponse execute() throws Exception {\n\t\tHttpResponse httpResponse = null;\n\t\thttpClient = HttpClients.createDefault();\n\n\t\thttpResponse = httpClient.execute(httpRequestBase);\n\t\tint statusCode = httpResponse.getStatusLine().getStatusCode();\n\t\tif (statusCode != HttpStatus.SC_OK && statusCode != 221) {\n\t\t\tString response = EntityUtils.toString(httpResponse.getEntity());\n\t\t\tlogger.error(\"request failed status:{}, response::{}\",statusCode, response);\n\t\t\tthrow new OnenetApiException(\"request failed: \" + response);\n\t\t}\n\n\t\treturn httpResponse;\n\t}\n}", "public enum Method{\n POST,GET,DELETE,PUT\n}", "public class BasicResponse<T> {\n\tpublic int errno;\n\tpublic String error;\n @JsonProperty(\"data\")\n public Object dataInternal;\n public T data;\n @JsonIgnore\n public String json;\n\n\tpublic String getJson() {\n\t\treturn json;\n\t}\n\n\tpublic void setJson(String json) {\n\t\tthis.json = json;\n\t}\n\n\tpublic int getErrno() {\n return errno;\n }\n\n public void setErrno(int errno) {\n this.errno = errno;\n }\n\n public String getError() {\n return error;\n }\n\n public void setError(String error) {\n this.error = error;\n }\n\n @JsonGetter(\"data\")\n public Object getDataInternal() {\n return dataInternal;\n }\n @JsonSetter(\"data\")\n public void setDataInternal(Object dataInternal) {\n this.dataInternal = dataInternal;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n}", "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class DevicesStatusList {\n\t@JsonProperty(\"total_count\")\n\tprivate int totalcount;\n\t@JsonProperty(\"devices\")\n\tprivate ArrayList<DeviceItem> devices;\n\n\t@JsonCreator\n\tpublic DevicesStatusList(@JsonProperty(\"total_count\") int totalcount,\n\t\t\t@JsonProperty(\"devices\") ArrayList<DeviceItem> devices) {\n\t\tthis.totalcount = totalcount;\n\t\tthis.devices = devices;\n\t}\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic static class DeviceItem{\n\t\n\n\t\t@JsonProperty(\"id\")\n\t\tprivate String id;\n\t\t@JsonProperty(\"title\")\n\t\tprivate String title;\n\t\t@JsonProperty(\"online\")\n\t\tprivate Boolean isonline;\n\t\t\n\t\t@JsonCreator\n\t\tpublic DeviceItem(@JsonProperty(\"id\") String id, @JsonProperty(\"title\") String title,@JsonProperty(\"online\") Boolean isonline) {\n\t\t\tsuper();\n\t\t\tthis.id = id;\n\t\t\tthis.title = title;\n\t\t\tthis.isonline = isonline;\n\t\t}\n\t\tpublic String getId() {\n\t\t\treturn id;\n\t\t}\n\n\t\tpublic void setId(String id) {\n\t\t\tthis.id = id;\n\t\t}\n\n\t\tpublic String getTitle() {\n\t\t\treturn title;\n\t\t}\n\n\t\tpublic void setTitle(String title) {\n\t\t\tthis.title = title;\n\t\t}\n\n\t\tpublic Boolean getIsonline() {\n\t\t\treturn isonline;\n\t\t}\n\n\t\tpublic void setIsonline(Boolean isonline) {\n\t\t\tthis.isonline = isonline;\n\t\t}\n\t\t\n\t}\n\tpublic ArrayList<DeviceItem> getDevices() {\n\t\treturn devices;\n\t}\n\tpublic void setDevices(ArrayList<DeviceItem> devices) {\n\t\tthis.devices = devices;\n\t}\n}", "public class Config {\n\tprivate final static Properties properties;\n private static org.slf4j.Logger logger = LoggerFactory.getLogger(Config.class);\n\tstatic {\n//\t\tLogger.getRootLogger().setLevel(Level.OFF);\n\t\tInputStream in = Config.class.getClassLoader().getResourceAsStream(\"config.properties\");\n\t\tproperties = new Properties();\n\t\ttry {\n\t\t\tproperties.load(in);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"init config error\", e);\n\t\t}\n\t}\n\n\t/**\n\t * 读取以逗号分割的字符串,作为字符串数组返回\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static List<String> getStringList(String conf) {\n\t\treturn Arrays.asList(StringUtils.split(properties.getProperty(conf), \",\"));\n\t}\n\n\t/**\n\t * 读取字符串\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static String getString(String conf) {\n\t\treturn properties.getProperty(conf);\n\t}\n\n\t/**\n\t * 读取整数\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static int getInt(String conf) {\n\t\tint ret = 0;\n\t\ttry {\n\t\t\tret = Integer.parseInt(getString(conf));\n\t\t} catch (NumberFormatException e) {\n\t\t\tlogger.error(\"format error\", e);\n\t\t}\n\t\treturn ret;\n\t}\n\n\t/**\n\t * 读取布尔值\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static boolean getBoolean(String conf) {\n\t\treturn Boolean.parseBoolean(getString(conf));\n\t}\n}" ]
import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cmcc.iot.onenet.javasdk.api.AbstractAPI; import cmcc.iot.onenet.javasdk.exception.OnenetApiException; import cmcc.iot.onenet.javasdk.http.HttpGetMethod; import cmcc.iot.onenet.javasdk.request.RequestInfo.Method; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.response.device.DevicesStatusList; import cmcc.iot.onenet.javasdk.utils.Config;
package cmcc.iot.onenet.javasdk.api.device; public class GetDevicesStatus extends AbstractAPI { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private HttpGetMethod HttpMethod; private String devIds; /** * 批量查询设备状态 * 参数顺序与构造函数顺序一致 * @param devIds:设备id用逗号隔开, 限制1000个设备,String * @param key :masterkey */ public GetDevicesStatus(String devIds,String key) { this.devIds = devIds; this.key = key;
this.method = Method.GET;
3
optimizely/android-sdk
android-sdk/src/androidTest/java/com/optimizely/ab/android/sdk/OptimizelyManagerTest.java
[ "@Deprecated\npublic interface DatafileHandler {\n /**\n * Synchronous call to download the datafile.\n *\n * @param context application context for download\n * @param datafileConfig DatafileConfig for the datafile\n * @return a valid datafile or null\n */\n String downloadDatafile(Context context, DatafileConfig datafileConfig);\n\n /**\n * Asynchronous download data file.\n *\n * @param context application context for download\n * @param datafileConfig DatafileConfig for the datafile to get\n * @param listener listener to call when datafile download complete\n */\n void downloadDatafile(Context context, DatafileConfig datafileConfig, DatafileLoadedListener listener);\n\n default void downloadDatafileToCache(final Context context, DatafileConfig datafileConfig, boolean updateConfigOnNewDatafile) {\n downloadDatafile(context, datafileConfig, null);\n }\n\n /**\n * Start background updates to the project datafile .\n *\n * @param context application context for download\n * @param datafileConfig DatafileConfig for the datafile\n * @param updateInterval frequency of updates in seconds\n * @param listener function to call when a new datafile has been detected.\n */\n void startBackgroundUpdates(Context context, DatafileConfig datafileConfig, Long updateInterval, DatafileLoadedListener listener);\n\n /**\n * Stop the background updates.\n *\n * @param context application context for download\n * @param datafileConfig DatafileConfig for the datafile\n */\n void stopBackgroundUpdates(Context context, DatafileConfig datafileConfig);\n\n /**\n * Save the datafile to cache.\n *\n * @param context application context for datafile cache\n * @param datafileConfig DatafileConfig for the datafile\n * @param dataFile the datafile to save\n */\n void saveDatafile(Context context, DatafileConfig datafileConfig, String dataFile);\n\n /**\n * Load a cached datafile if it exists\n *\n * @param context application context for datafile cache\n * @param projectId project id of the datafile to try and get from cache\n * @return the datafile cached or null if it was not available\n */\n String loadSavedDatafile(Context context, DatafileConfig projectId);\n\n /**\n * Has the file already been cached locally?\n *\n * @param context application context for datafile cache\n * @param datafileConfig DatafileConfig for the datafile\n * @return true if the datafile is cached or false if not.\n */\n Boolean isDatafileSaved(Context context, DatafileConfig datafileConfig);\n /**\n * Remove the datafile in cache.\n *\n * @param context application context for datafile cache\n * @param datafileConfig DatafileConfig for the datafile\n */\n void removeSavedDatafile(Context context, DatafileConfig datafileConfig);\n}", "public interface DatafileLoadedListener {\n\n /**\n * Called with new datafile after a download.\n *\n * @param dataFile the datafile json, can be null if datafile loading failed.\n *\n */\n void onDatafileLoaded(@Nullable String dataFile);\n}", "@Deprecated\npublic class DatafileService extends Service {\n /**\n * Extra containing the project id this instance of Optimizely was built with\n */\n public static final String EXTRA_DATAFILE_CONFIG = \"com.optimizely.ab.android.EXTRA_DATAFILE_CONFIG\";\n public static final Integer JOB_ID = 2113;\n\n @NonNull private final IBinder binder = new LocalBinder();\n Logger logger = LoggerFactory.getLogger(DatafileService.class);\n private boolean isBound;\n\n /**\n * @hide\n * @see Service#onStartCommand(Intent, int, int)\n */\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n if (intent != null) {\n if (intent.hasExtra(EXTRA_DATAFILE_CONFIG)) {\n String extraDatafileConfig = intent.getStringExtra(EXTRA_DATAFILE_CONFIG);\n DatafileConfig datafileConfig = DatafileConfig.fromJSONString(extraDatafileConfig);\n DatafileClient datafileClient = new DatafileClient(\n new Client(new OptlyStorage(this.getApplicationContext()), LoggerFactory.getLogger(OptlyStorage.class)),\n LoggerFactory.getLogger(DatafileClient.class));\n DatafileCache datafileCache = new DatafileCache(\n datafileConfig.getKey(),\n new Cache(this.getApplicationContext(), LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(DatafileCache.class));\n\n String datafileUrl = datafileConfig.getUrl();\n DatafileLoader datafileLoader = new DatafileLoader(this, datafileClient, datafileCache, LoggerFactory.getLogger(DatafileLoader.class));\n datafileLoader.getDatafile(datafileUrl, null);\n } else {\n logger.warn(\"Data file service received an intent with no project id extra\");\n }\n } else {\n logger.warn(\"Data file service received a null intent\");\n }\n\n return super.onStartCommand(intent, flags, startId);\n }\n\n /**\n * @hide\n * @see Service#onBind(Intent)\n */\n @Override\n public IBinder onBind(Intent intent) {\n isBound = true;\n return binder;\n }\n\n /**\n * @hide\n * @see Service#onUnbind(Intent)\n */\n @Override\n public boolean onUnbind(Intent intent) {\n isBound = false;\n logger.info(\"All clients are unbound from data file service\");\n return false;\n }\n\n public boolean isBound() {\n return isBound;\n }\n\n public void stop() {\n stopSelf();\n }\n\n public void getDatafile(String datafileUrl, DatafileLoader datafileLoader, DatafileLoadedListener loadedListener) {\n datafileLoader.getDatafile(datafileUrl, loadedListener);\n }\n\n public class LocalBinder extends Binder {\n public DatafileService getService() {\n // Return this instance of LocalService so clients can call public methods\n return DatafileService.this;\n }\n }\n}", "public class DefaultDatafileHandler implements DatafileHandler, ProjectConfigManager {\n private static final Logger logger = LoggerFactory.getLogger(DefaultDatafileHandler.class);\n private ProjectConfig currentProjectConfig;\n private DatafileServiceConnection datafileServiceConnection;\n private FileObserver fileObserver;\n\n /**\n * Synchronous call to download the datafile.\n * Gets the file on the current thread from the Optimizely CDN.\n *\n * @param context application context\n * @param datafileConfig DatafileConfig for the datafile\n * @return a valid datafile or null\n */\n public String downloadDatafile(Context context, DatafileConfig datafileConfig) {\n DatafileClient datafileClient = new DatafileClient(\n new Client(new OptlyStorage(context), LoggerFactory.getLogger(OptlyStorage.class)),\n LoggerFactory.getLogger(DatafileClient.class));\n\n String datafileUrl = datafileConfig.getUrl();\n\n return datafileClient.request(datafileUrl);\n }\n\n /**\n * Asynchronous download data file.\n * <p>\n * We create a DatafileService intent, create a DataService connection, and bind it to the application context.\n * After we receive the datafile, we unbind the service and cleanup the service connection.\n * This gets the project file from the Optimizely CDN.\n *\n * @param context application context\n * @param datafileConfig DatafileConfig for the datafile to get\n * @param listener listener to call when datafile download complete\n */\n public void downloadDatafile(final Context context, DatafileConfig datafileConfig, final DatafileLoadedListener listener) {\n DatafileClient datafileClient = new DatafileClient(\n new Client(new OptlyStorage(context.getApplicationContext()), LoggerFactory.getLogger(OptlyStorage.class)),\n LoggerFactory.getLogger(DatafileClient.class));\n DatafileCache datafileCache = new DatafileCache(\n datafileConfig.getKey(),\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(DatafileCache.class));\n\n String datafileUrl = datafileConfig.getUrl();\n DatafileLoader datafileLoader = new DatafileLoader(context, datafileClient, datafileCache, LoggerFactory.getLogger(DatafileLoader.class));\n datafileLoader.getDatafile(datafileUrl, new DatafileLoadedListener() {\n\n @Override\n public void onDatafileLoaded(@Nullable String dataFile) {\n if (listener != null) {\n listener.onDatafileLoaded(dataFile);\n }\n }\n });\n\n\n\n }\n\n public void downloadDatafileToCache(final Context context, DatafileConfig datafileConfig, boolean updateConfigOnNewDatafile) {\n if (updateConfigOnNewDatafile) {\n enableUpdateConfigOnNewDatafile(context, datafileConfig, null);\n }\n\n downloadDatafile(context, datafileConfig, null);\n }\n\n /**\n * Start background checks if the the project datafile jas been updated. This starts an alarm service that checks to see if there is a\n * new datafile to download at interval provided. If there is a update, the new datafile is cached.\n *\n * @param context application context\n * @param datafileConfig DatafileConfig for the datafile\n * @param updateInterval frequency of updates in seconds\n */\n public void startBackgroundUpdates(Context context, DatafileConfig datafileConfig, Long updateInterval, DatafileLoadedListener listener) {\n long updateIntervalInMinutes = updateInterval / 60;\n\n // save the project id background start is set. If we get a reboot or a replace, we can restart via the\n // DatafileRescheduler\n logger.info(\"Datafile background polling scheduled (period interval: \" + String.valueOf(updateIntervalInMinutes) + \" minutes)\");\n WorkerScheduler.scheduleService(context, DatafileWorker.workerId + datafileConfig.getKey(), DatafileWorker.class,\n DatafileWorker.getData(datafileConfig), updateIntervalInMinutes);\n enableBackgroundCache(context, datafileConfig);\n\n storeInterval(context, updateIntervalInMinutes);\n\n enableUpdateConfigOnNewDatafile(context, datafileConfig, listener);\n }\n\n synchronized public void enableUpdateConfigOnNewDatafile(Context context, DatafileConfig datafileConfig, DatafileLoadedListener listener) {\n // do not restart observer if already set\n if (fileObserver != null) {\n return;\n }\n\n DatafileCache datafileCache = new DatafileCache(\n datafileConfig.getKey(),\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(DatafileCache.class)\n );\n\n File filesFolder = context.getFilesDir();\n fileObserver = new FileObserver(filesFolder.getPath()) {\n @Override\n public void onEvent(int event, @Nullable String path) {\n\n logger.debug(\"EVENT: \" + String.valueOf(event) + \" \" + path + \" (\" + datafileCache.getFileName() + \")\");\n if (event == MODIFY && path.equals(datafileCache.getFileName())) {\n JSONObject newConfig = datafileCache.load();\n if (newConfig == null) {\n logger.error(\"Cached datafile is empty or corrupt\");\n return;\n }\n String config = newConfig.toString();\n setDatafile(config);\n if (listener != null) {\n listener.onDatafileLoaded(config);\n }\n }\n }\n };\n fileObserver.startWatching();\n }\n\n synchronized private void disableUploadConfig() {\n if (fileObserver != null) {\n fileObserver.stopWatching();\n fileObserver = null;\n }\n }\n\n private static void storeInterval(Context context, long interval) {\n OptlyStorage storage = new OptlyStorage(context);\n storage.saveLong(\"DATAFILE_INTERVAL\", interval);\n }\n\n public static long getUpdateInterval(Context context) {\n OptlyStorage storage = new OptlyStorage(context);\n return storage.getLong(\"DATAFILE_INTERVAL\", 15);\n }\n\n /**\n * Stop the background updates.\n *\n * @param context application context\n * @param datafileConfig DatafileConfig for the datafile\n */\n public void stopBackgroundUpdates(Context context, DatafileConfig datafileConfig) {\n WorkerScheduler.unscheduleService(context, DatafileWorker.workerId + datafileConfig.getKey());\n clearBackgroundCache(context, datafileConfig);\n\n storeInterval(context, -1);\n\n disableUploadConfig();\n }\n\n private void enableBackgroundCache(Context context, DatafileConfig datafileConfig) {\n BackgroundWatchersCache backgroundWatchersCache = new BackgroundWatchersCache(\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(BackgroundWatchersCache.class));\n backgroundWatchersCache.setIsWatching(datafileConfig, true);\n }\n\n private void clearBackgroundCache(Context context, DatafileConfig projectId) {\n BackgroundWatchersCache backgroundWatchersCache = new BackgroundWatchersCache(\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(BackgroundWatchersCache.class));\n backgroundWatchersCache.setIsWatching(projectId, false);\n }\n\n\n /**\n * Save the datafile to cache.\n *\n * @param context application context\n * @param datafileConfig DatafileConfig for the datafile\n * @param dataFile the datafile to save\n */\n public void saveDatafile(Context context, DatafileConfig datafileConfig, String dataFile) {\n DatafileCache datafileCache = new DatafileCache(\n datafileConfig.getKey(),\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(DatafileCache.class)\n );\n\n datafileCache.delete();\n datafileCache.save(dataFile);\n }\n\n /**\n * Load a cached datafile if it exists.\n *\n * @param context application context\n * @param datafileConfig DatafileConfig for the datafile\n * @return the datafile cached or null if it was not available\n */\n public String loadSavedDatafile(Context context, DatafileConfig datafileConfig) {\n DatafileCache datafileCache = new DatafileCache(\n datafileConfig.getKey(),\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(DatafileCache.class)\n );\n\n JSONObject datafile = datafileCache.load();\n if (datafile != null) {\n return datafile.toString();\n }\n\n return null;\n }\n\n /**\n * Is the datafile cached locally?\n *\n * @param context application context\n * @param datafileConfig DatafileConfig for the datafile\n * @return true if cached false if not\n */\n public Boolean isDatafileSaved(Context context, DatafileConfig datafileConfig) {\n DatafileCache datafileCache = new DatafileCache(\n datafileConfig.getKey(),\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(DatafileCache.class)\n );\n\n return datafileCache.exists();\n }\n\n /**\n * Remove the datafile in cache.\n *\n * @param context application context\n * @param datafileConfig DatafileConfig of the current datafile.\n */\n public void removeSavedDatafile(Context context, DatafileConfig datafileConfig) {\n DatafileCache datafileCache = new DatafileCache(\n datafileConfig.getKey(),\n new Cache(context, LoggerFactory.getLogger(Cache.class)),\n LoggerFactory.getLogger(DatafileCache.class)\n );\n\n if (datafileCache.exists()) {\n datafileCache.delete();\n }\n }\n\n public void setDatafile(String datafile) {\n\n if (datafile == null) {\n logger.info(\"datafile is null, ignoring update\");\n return;\n }\n\n if (datafile.isEmpty()) {\n logger.info(\"datafile is empty, ignoring update\");\n return;\n }\n\n try {\n currentProjectConfig = new DatafileProjectConfig.Builder().withDatafile(datafile).build();\n\n logger.info(\"Datafile successfully loaded with revision: {}\", currentProjectConfig.getRevision());\n } catch (ConfigParseException ex) {\n logger.error(\"Unable to parse the datafile\", ex);\n logger.info(\"Datafile is invalid\");\n }\n }\n @Override\n public ProjectConfig getConfig() {\n return currentProjectConfig;\n }\n}", "public class DefaultEventHandler implements EventHandler {\n\n @NonNull\n private final Context context;\n Logger logger = LoggerFactory.getLogger(DefaultEventHandler.class);\n private long dispatchInterval = -1;\n\n /**\n * Private constructor\n * @param context current context for service.\n */\n private DefaultEventHandler(@NonNull Context context) {\n this.context = context;\n }\n\n /**\n * Gets a new instance\n *\n * @param context any valid Android {@link Context}\n * @return a new instance of {@link DefaultEventHandler}\n */\n public static DefaultEventHandler getInstance(@NonNull Context context) {\n return new DefaultEventHandler(context);\n }\n\n /**\n * Sets event dispatch retry interval\n * <p>\n * Events will only be scheduled to dispatch as long as events remain in storage.\n * <p>\n * Events are put into storage when they fail to send over network.\n *\n * @param dispatchInterval the interval in milliseconds\n */\n public void setDispatchInterval(long dispatchInterval) {\n if (dispatchInterval <= 0) {\n this.dispatchInterval = -1;\n } else {\n this.dispatchInterval = dispatchInterval;\n }\n }\n\n /**\n * @see EventHandler#dispatchEvent(LogEvent)\n */\n @Override\n public void dispatchEvent(@NonNull LogEvent logEvent) {\n if (logEvent.getEndpointUrl() == null) {\n logger.error(\"Event dispatcher received a null url\");\n return;\n }\n if (logEvent.getBody() == null) {\n logger.error(\"Event dispatcher received a null request body\");\n return;\n }\n if (logEvent.getEndpointUrl().isEmpty()) {\n logger.error(\"Event dispatcher received an empty url\");\n }\n\n // NOTE: retryInterval (dispatchInterval) is passed to WorkManager:\n // - in InputData to enable/disable retries\n // - in BackOffCriteria to change retry interval\n Data inputData = EventWorker.getData(logEvent, dispatchInterval);\n WorkerScheduler.startService(context, EventWorker.workerId, EventWorker.class, inputData, dispatchInterval);\n\n if (dispatchInterval < 0) {\n logger.info(\"Sent url {} to the event handler service\", logEvent.getEndpointUrl());\n } else {\n logger.info(\"Sent url {} to the event handler service (with retry interval of {} seconds)\",\n logEvent.getEndpointUrl(), dispatchInterval/1000);\n }\n }\n}", "public class DatafileConfig {\n public static String defaultHost = \"https://cdn.optimizely.com\";\n public static String projectUrlSuffix = \"/json/%s.json\";\n public static String environmentUrlSuffix = \"/datafiles/%s.json\";\n public static String delimiter = \"::::\";\n\n private final String projectId;\n private final String sdkKey;\n private final String host;\n private final String datafileUrlString;\n\n /**\n * Constructor used to construct a DatafileConfig to get cache key, url,\n * for the appropriate environment. One or the other can be null. But, not both.\n * @param projectId project id string.\n * @param sdkKey the environment url.\n * @param host used to override the DatafileConfig.defaultHost used for datafile synchronization.\n */\n public DatafileConfig(String projectId, String sdkKey, String host) {\n assert(projectId != null || sdkKey != null);\n this.projectId = projectId;\n this.sdkKey = sdkKey;\n this.host = host;\n\n if (sdkKey != null) {\n this.datafileUrlString = String.format((this.host + environmentUrlSuffix), sdkKey);\n }\n else {\n this.datafileUrlString = String.format((this.host + projectUrlSuffix), projectId);\n }\n }\n\n /**\n * Constructor used to construct a DatafileConfig to get cache key, url,\n * for the appropriate environment. One or the other can be null. But, not both.\n * @param projectId project id string.\n * @param sdkKey the environment url.\n */\n public DatafileConfig(String projectId, String sdkKey) {\n this(projectId, sdkKey, defaultHost);\n }\n\n /**\n * This returns the current datafile key string.\n * @return datafile key string.\n */\n public String getKey() {\n return sdkKey != null ? sdkKey : projectId;\n }\n\n /**\n * Get the url associated with this project. If there is an environment,\n * that url is returned.\n * @return url of current project configuration.\n */\n public String getUrl() {\n return datafileUrlString;\n }\n\n public String toJSONString() {\n JSONObject jsonObject = new JSONObject();\n try {\n jsonObject.put(\"projectId\", projectId);\n jsonObject.put(\"sdkKey\", sdkKey);\n return jsonObject.toString();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static DatafileConfig fromJSONString(String jsonString) {\n try {\n JSONObject jsonObject = new JSONObject(jsonString);\n String projectId = null;\n if (jsonObject.has(\"projectId\")) {\n projectId = jsonObject.getString(\"projectId\");\n }\n String environmentKey = null;\n if (jsonObject.has(\"sdkKey\")) {\n environmentKey = jsonObject.getString(\"sdkKey\");\n }\n return new DatafileConfig(projectId, environmentKey);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n /**\n * To string either returns the proejct id as string or a concatenated string of project id\n * delimiter and environment key.\n * @return the string identification for the DatafileConfig\n */\n @Override\n public String toString() {\n return projectId != null ? projectId : \"null\" + delimiter + (sdkKey != null? sdkKey : \"null\");\n }\n\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof DatafileConfig)) {\n return false;\n }\n DatafileConfig p = (DatafileConfig) o;\n return this.projectId != null ? (p.projectId != null ? this.projectId.equals(p.projectId) : this.projectId == p.projectId) : p.projectId == null\n &&\n this.sdkKey != null ? (p.sdkKey != null ? this.sdkKey.equals(p.sdkKey) : this.sdkKey == p.sdkKey) : p.sdkKey == null;\n\n }\n\n public int hashCode() {\n int result = 17;\n result = 31 * result + (projectId == null ? 0 : projectId.hashCode()) + (sdkKey == null ? 0 : sdkKey.hashCode());\n return result;\n }\n\n}", "@Deprecated\npublic class ServiceScheduler {\n\n // @NonNull private final AlarmManager alarmManager;\n @NonNull private final PendingIntentFactory pendingIntentFactory;\n @NonNull private final Logger logger;\n @NonNull private final Context context;\n\n /**\n * @param context an instance of {@link Context}\n * @param pendingIntentFactory an instance of {@link PendingIntentFactory}\n * @param logger an instance of {@link Logger}\n */\n public ServiceScheduler(@NonNull Context context, @NonNull PendingIntentFactory pendingIntentFactory, @NonNull Logger logger) {\n this.pendingIntentFactory = pendingIntentFactory;\n this.logger = logger;\n this.context = context;\n }\n\n /**\n * Schedule a service starting {@link Intent} that starts on an interval\n *\n * Previously scheduled services matching this intent will be unscheduled. They will\n * match even if the interval is different.\n *\n * For API 26 and higher, the JobScheduler is used. APIs below 26 still use the AlarmService\n *\n * @param intent an {@link Intent}\n * @param interval the interval in MS\n */\n public void schedule(Intent intent, long interval) {\n if (interval < 1) {\n logger.error(\"Tried to schedule an interval less than 1\");\n return;\n }\n\n if (isScheduled(intent)) {\n unschedule(intent);\n }\n\n PendingIntent pendingIntent = pendingIntentFactory.getPendingIntent(intent);\n\n //setRepeating(interval, pendingIntent, intent);\n\n logger.info(\"Scheduled {}\", intent.getComponent().toShortString());\n }\n\n private void setRepeating(long interval, PendingIntent pendingIntent, Intent intent) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n int jobId = getJobId(intent);\n if (jobId == -1) {\n logger.error(\"Problem getting scheduled job id\");\n return;\n }\n\n if (isScheduled(context, jobId)) {\n logger.info(\"Job already started\");\n return;\n }\n\n JobScheduler jobScheduler = (JobScheduler)\n context.getSystemService(Context.JOB_SCHEDULER_SERVICE);\n JobInfo.Builder builder = new JobInfo.Builder(jobId,\n new ComponentName(context.getApplicationContext(),\n ScheduledJobService.class.getName()));\n builder.setPeriodic(interval, interval);\n builder.setPersisted(true);\n // we are only doing repeating on datafile service. it is a prefetch.\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n builder.setPrefetch(true);\n }\n builder.setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);\n\n intent.putExtra(JobWorkService.INTENT_EXTRA_JWS_PERIODIC, interval);\n PersistableBundle persistableBundle = new PersistableBundle();\n\n for (String key : intent.getExtras().keySet()) {\n Object object = intent.getExtras().get(key);\n switch (object.getClass().getSimpleName()) {\n case \"String\":\n persistableBundle.putString(key, (String) object);\n break;\n case \"long\":\n case \"Long\":\n persistableBundle.putLong(key, (Long) object);\n break;\n default:\n logger.info(\"No conversion for {}\", object.getClass().getSimpleName());\n }\n }\n\n persistableBundle.putString(ScheduledJobService.INTENT_EXTRA_COMPONENT_NAME, intent.getComponent().getClassName());\n\n builder.setExtras(persistableBundle);\n\n try {\n if (jobScheduler.schedule(builder.build()) != RESULT_SUCCESS) {\n logger.error(\"ServiceScheduler\", \"Some error while scheduling the job\");\n }\n }\n catch (Exception e) {\n logger.error(String.format(\"Problem scheduling job %s\", intent.getComponent().toShortString()), e);\n }\n }\n else {\n AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, interval, interval, pendingIntent);\n }\n }\n\n private void cancelRepeating(PendingIntent pendingIntent, Intent intent) {\n if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n JobScheduler jobScheduler = (JobScheduler)\n context.getSystemService(Context.JOB_SCHEDULER_SERVICE);\n String clazz = intent.getComponent().getClassName();\n Integer id = null;\n try {\n id = (Integer) Class.forName(clazz).getDeclaredField(\"JOB_ID\").get(null);\n // only cancel periodic services\n if (ServiceScheduler.isScheduled(context, id)) {\n jobScheduler.cancel(id);\n }\n pendingIntent.cancel();\n } catch (Exception e) {\n logger.error(\"Error in Cancel \", e);\n }\n }\n else {\n AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n alarmManager.cancel(pendingIntent);\n pendingIntent.cancel();\n }\n }\n\n private int getJobId(Intent intent) {\n String clazz = \"unknown\";\n Integer id = null;\n\n try {\n clazz = intent.getComponent().getClassName();\n id = (Integer) Class.forName(clazz).getDeclaredField(\"JOB_ID\").get(null);\n } catch (Exception e) {\n logger.error(\"Error getting JOB_ID from \" + clazz, e);\n }\n\n return id == null ? -1 : id;\n }\n\n /**\n * Unschedule a scheduled {@link Intent}\n *\n * The {@link Intent} must equal the intent that was originally sent to {@link #schedule(Intent, long)}\n * @param intent an service starting {@link Intent} instance\n */\n public void unschedule(Intent intent) {\n if (intent != null) {\n try {\n PendingIntent pendingIntent = pendingIntentFactory.getPendingIntent(intent);\n cancelRepeating(pendingIntent, intent);\n logger.info(\"Unscheduled {}\", intent.getComponent()!=null ? intent.getComponent().toShortString() : \"intent\");\n } catch (Exception e) {\n logger.debug(\"Failed to unschedule service\", e);\n }\n }\n }\n\n /**\n * Is an {@link Intent} for a service scheduled\n * @param intent the intent in question\n * @return is it scheduled or not\n */\n public boolean isScheduled(Intent intent) {\n return pendingIntentFactory.hasPendingIntent(intent);\n }\n\n /**\n * Handles the complexities around PendingIntent flags\n *\n * We need to know if the PendingIntent has already been created to prevent pushing\n * the alarm back after the last event.\n *\n * Putting this in it's class makes mocking much easier when testing out {@link ServiceScheduler#schedule(Intent, long)}\n */\n public static class PendingIntentFactory {\n\n private Context context;\n\n public PendingIntentFactory(Context context) {\n this.context = context;\n }\n\n /**\n * Has a {@link PendingIntent} already been created for the provided {@link Intent}\n * @param intent an instance of {@link Intent}\n * @return true if a {@link PendingIntent} was already created\n */\n public boolean hasPendingIntent(Intent intent) {\n // FLAG_NO_CREATE will cause null to be returned if this Intent hasn't been created yet.\n // It does matter if you send a new instance or not the equality check is done via\n // the data, action, and component of an Intent. Ours will always match.\n return getPendingIntent(intent, PendingIntent.FLAG_NO_CREATE) != null;\n }\n\n /**\n * Gets a {@link PendingIntent} for an {@link Intent}\n * @param intent an instance of {@link Intent}\n * @return a {@link PendingIntent}\n */\n public PendingIntent getPendingIntent(Intent intent) {\n return getPendingIntent(intent, PendingIntent.FLAG_UPDATE_CURRENT);\n }\n\n private PendingIntent getPendingIntent(Intent intent, int flag) {\n return PendingIntent.getService(context, 0, intent, flag);\n }\n }\n\n\n /**\n * Start a service either through the context or enqueued to the JobService to be run in a minute.\n * For example, the BroadcastReceivers use this to handle all versions of the API.\n *\n * @param context - Application context\n * @param jobId - job id for the job to start if it is a job\n * @param intent - Intent you want to run.\n */\n @Deprecated\n public static void startService(Context context, Integer jobId, Intent intent) {\n if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n\n JobInfo jobInfo = new JobInfo.Builder(jobId,\n new ComponentName(context, JobWorkService.class))\n // schedule it to run any time between 1 - 5 minutes\n .setMinimumLatency(JobWorkService.ONE_MINUTE)\n .setOverrideDeadline(5 * JobWorkService.ONE_MINUTE)\n .build();\n JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);\n\n if (jobScheduler.getAllPendingJobs().stream().filter(job -> job.getId() == jobId && job.getExtras().equals(intent.getExtras())).count() > 0) {\n // already pending job. don't run again\n LoggerFactory.getLogger(\"ServiceScheduler\").info(\"Job already pending\");\n return;\n }\n\n JobWorkItem jobWorkItem = new JobWorkItem(intent);\n try {\n jobScheduler.enqueue(jobInfo, jobWorkItem);\n }\n catch (Exception e) {\n LoggerFactory.getLogger(\"ServiceScheduler\").error(\"Problem enqueuing work item \", e);\n }\n\n }\n else {\n context.startService(intent);\n }\n\n }\n\n private static boolean isScheduled(Context context, Integer jobId) {\n if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);\n for (JobInfo jobInfo : jobScheduler.getAllPendingJobs()) {\n // we only don't allow rescheduling of periodic jobs. jobs for individual\n // intents such as events are allowed and can end up queued in the job service queue.\n if (jobInfo.getId() == jobId && jobInfo.isPeriodic()) {\n return true;\n }\n }\n }\n return false;\n }\n\n\n\n}", "public class DefaultUserProfileService implements UserProfileService {\n\n @NonNull private final UserProfileCache userProfileCache;\n @NonNull private final Logger logger;\n\n DefaultUserProfileService(@NonNull UserProfileCache userProfileCache, @NonNull Logger logger) {\n this.userProfileCache = userProfileCache;\n this.logger = logger;\n }\n\n\n /**\n * Gets a new instance of {@link DefaultUserProfileService}.\n *\n * @param projectId your project's id\n * @param context an instance of {@link Context}\n * @return the instance as {@link UserProfileService}\n */\n public static UserProfileService newInstance(@NonNull String projectId, @NonNull Context context) {\n UserProfileCache userProfileCache = new UserProfileCache(\n new UserProfileCache.DiskCache(new Cache(context, LoggerFactory.getLogger(Cache.class)),\n Executors.newSingleThreadExecutor(), LoggerFactory.getLogger(UserProfileCache.DiskCache.class),\n projectId),\n LoggerFactory.getLogger(UserProfileCache.class),\n new ConcurrentHashMap<String, Map<String, Object>>(),\n new UserProfileCache.LegacyDiskCache(new Cache(context, LoggerFactory.getLogger(Cache.class)),\n Executors.newSingleThreadExecutor(),\n LoggerFactory.getLogger(UserProfileCache.LegacyDiskCache.class), projectId));\n\n return new DefaultUserProfileService(userProfileCache,\n LoggerFactory.getLogger(DefaultUserProfileService.class));\n }\n\n public interface StartCallback {\n void onStartComplete(UserProfileService userProfileService);\n }\n\n public void startInBackground(final StartCallback callback) {\n final DefaultUserProfileService userProfileService = this;\n\n AsyncTask<Void, Void, UserProfileService> initUserProfileTask = new AsyncTask<Void, Void, UserProfileService>() {\n @Override\n protected UserProfileService doInBackground(Void[] params) {\n userProfileService.start();\n return userProfileService;\n }\n @Override\n protected void onPostExecute(UserProfileService userProfileService) {\n if (callback != null) {\n callback.onStartComplete(userProfileService);\n }\n }\n };\n\n try {\n initUserProfileTask.executeOnExecutor(Executors.newSingleThreadExecutor());\n }\n catch (Exception e) {\n logger.error(\"Error loading user profile service from AndroidUserProfileServiceDefault\");\n callback.onStartComplete(null);\n }\n\n }\n\n /**\n * Load the cache from disk to memory.\n */\n public void start() {\n userProfileCache.start();\n }\n\n /**\n * @param userId the user ID of the user profile\n * @return user profile from the cache if found\n * @see UserProfileService#lookup(String)\n */\n @Override\n @Nullable\n public Map<String, Object> lookup(String userId) {\n if (userId == null) {\n logger.error(\"Received null user ID, unable to lookup activation.\");\n return null;\n } else if (userId.isEmpty()) {\n logger.error(\"Received empty user ID, unable to lookup activation.\");\n return null;\n }\n return userProfileCache.lookup(userId);\n }\n\n /**\n * Remove a user profile.\n *\n * @param userId the user ID of the decision to remove\n */\n public void remove(String userId) {\n userProfileCache.remove(userId);\n }\n\n public void removeInvalidExperiments(Set<String> validExperiments) {\n try {\n userProfileCache.removeInvalidExperiments(validExperiments);\n }\n catch (Exception e) {\n logger.error(\"Error calling userProfileCache to remove invalid experiments\", e);\n }\n }\n /**\n * Remove a decision from a user profile.\n *\n * @param userId the user ID of the decision to remove\n * @param experimentId the experiment ID of the decision to remove\n */\n public void remove(String userId, String experimentId) {\n userProfileCache.remove(userId, experimentId);\n }\n\n /**\n * @param userProfileMap map representation of user profile\n * @see UserProfileService#save(Map)\n */\n @Override\n public void save(Map<String, Object> userProfileMap) {\n userProfileCache.save(userProfileMap);\n }\n}" ]
import android.app.AlarmManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SdkSuppress; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.datafile_handler.DatafileHandler; import com.optimizely.ab.android.datafile_handler.DatafileLoadedListener; import com.optimizely.ab.android.datafile_handler.DatafileService; import com.optimizely.ab.android.datafile_handler.DefaultDatafileHandler; import com.optimizely.ab.android.event_handler.DefaultEventHandler; import com.optimizely.ab.android.shared.DatafileConfig; import com.optimizely.ab.android.shared.ServiceScheduler; import com.optimizely.ab.android.user_profile.DefaultUserProfileService; import com.optimizely.ab.bucketing.UserProfileService; import com.optimizely.ab.config.DatafileProjectConfig; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.config.Variation; import com.optimizely.ab.config.parser.ConfigParseException; import com.optimizely.ab.event.EventHandler; import com.optimizely.ab.event.EventProcessor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
@Test public void initializeWithMalformedDatafile() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); when(appContext.getPackageName()).thenReturn("com.optly"); when(defaultDatafileHandler.getConfig()).thenReturn(null); String emptyString = "malformed data"; optimizelyManager.initialize(context, emptyString); assertFalse(optimizelyManager.getOptimizely().isValid()); } @Test public void initializeWithNullDatafile() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); when(appContext.getPackageName()).thenReturn("com.optly"); String emptyString = null; optimizelyManager.initialize(context, emptyString); verify(logger).error(eq("Invalid datafile")); } @Test public void initializeAsyncWithNullDatafile() { optimizelyManager.initialize(InstrumentationRegistry.getInstrumentation().getContext(), new OptimizelyStartListener() { @Override public void onStart(OptimizelyClient optimizely) { assertNotNull(optimizely); } }); } @Test public void load() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); when(appContext.getPackageName()).thenReturn("com.optly"); String emptyString = null; optimizelyManager.initialize(context, emptyString); verify(logger).error(eq("Invalid datafile")); } @Test public void stop() { Context context = mock(Context.class); Context appContext = mock(Context.class); when(context.getApplicationContext()).thenReturn(appContext); optimizelyManager.getDatafileHandler().downloadDatafile(context, optimizelyManager.getDatafileConfig(), null); optimizelyManager.stop(context); assertNull(optimizelyManager.getOptimizelyStartListener()); } @Test public void injectOptimizely() { Context context = mock(Context.class); UserProfileService userProfileService = mock(UserProfileService.class); OptimizelyStartListener startListener = mock(OptimizelyStartListener.class); optimizelyManager.setOptimizelyStartListener(startListener); optimizelyManager.injectOptimizely(context, userProfileService, minDatafile); try { executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("Timed out"); } verify(logger).info("Sending Optimizely instance to listener"); verify(startListener).onStart(any(OptimizelyClient.class)); verify(optimizelyManager.getDatafileHandler()).startBackgroundUpdates(eq(context), eq(new DatafileConfig(testProjectId, null)), eq(3600L), any(DatafileLoadedListener.class)); } @Test public void injectOptimizelyWithDatafileListener() { Context context = mock(Context.class); UserProfileService userProfileService = mock(UserProfileService.class); OptimizelyStartListener startListener = mock(OptimizelyStartListener.class); optimizelyManager.setOptimizelyStartListener(startListener); optimizelyManager.injectOptimizely(context, userProfileService, minDatafile); try { executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("Timed out"); } verify(optimizelyManager.getDatafileHandler()).startBackgroundUpdates(eq(context), eq(new DatafileConfig(testProjectId, null)), eq(3600L), any(DatafileLoadedListener.class)); verify(logger).info("Sending Optimizely instance to listener"); verify(startListener).onStart(any(OptimizelyClient.class)); } @Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) public void injectOptimizelyNullListener() { Context context = mock(Context.class); PackageManager packageManager = mock(PackageManager.class); when(context.getPackageName()).thenReturn("com.optly"); when(context.getApplicationContext()).thenReturn(context); when(context.getApplicationContext().getPackageManager()).thenReturn(packageManager); try { when(packageManager.getPackageInfo("com.optly", 0)).thenReturn(mock(PackageInfo.class)); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } UserProfileService userProfileService = mock(UserProfileService.class); ServiceScheduler serviceScheduler = mock(ServiceScheduler.class); ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
ArgumentCaptor<DefaultUserProfileService.StartCallback> callbackArgumentCaptor =
7
Zhuinden/simple-stack
simple-stack/src/test/java/com/zhuinden/simplestack/ScopingGlobalScopeTest.java
[ "public interface HasParentServices\n extends ScopeKey.Child {\n void bindServices(ServiceBinder serviceBinder);\n}", "public interface HasServices\n extends ScopeKey {\n void bindServices(ServiceBinder serviceBinder);\n}", "public class ServiceProvider\n implements ScopedServices {\n @Override\n public void bindServices(@Nonnull ServiceBinder serviceBinder) {\n Object key = serviceBinder.getKey();\n if(key instanceof HasServices) {\n ((HasServices) key).bindServices(serviceBinder);\n return;\n }\n if(key instanceof HasParentServices) {\n ((HasParentServices) key).bindServices(serviceBinder);\n //noinspection UnnecessaryReturnStatement\n return;\n }\n }\n}", "public class TestKey\n implements Parcelable {\n public final String name;\n\n public TestKey(String name) {\n this.name = name;\n }\n\n protected TestKey(Parcel in) {\n name = in.readString();\n }\n\n public static final Creator<TestKey> CREATOR = new Creator<TestKey>() {\n @Override\n public TestKey createFromParcel(Parcel in) {\n return new TestKey(in);\n }\n\n @Override\n public TestKey[] newArray(int size) {\n return new TestKey[size];\n }\n };\n\n @Override\n public boolean equals(Object o) {\n if(this == o) {\n return true;\n }\n if(o == null || getClass() != o.getClass()) {\n return false;\n }\n TestKey key = (TestKey) o;\n return name.equals(key.name);\n }\n\n @Override\n public int hashCode() {\n return name.hashCode();\n }\n\n @Override\n public String toString() {\n return String.format(\"%s{%h}\", name, this);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(name);\n }\n}", "public abstract class TestKeyWithScope\n extends TestKey\n implements HasServices {\n public TestKeyWithScope(String name) {\n super(name);\n }\n\n protected TestKeyWithScope(Parcel in) {\n super(in);\n }\n\n @Nonnull\n @Override\n public String getScopeTag() {\n return name;\n }\n}" ]
import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static org.assertj.core.api.Assertions.assertThat; import android.os.Parcel; import com.zhuinden.simplestack.helpers.HasParentServices; import com.zhuinden.simplestack.helpers.HasServices; import com.zhuinden.simplestack.helpers.ServiceProvider; import com.zhuinden.simplestack.helpers.TestKey; import com.zhuinden.simplestack.helpers.TestKeyWithScope; import com.zhuinden.statebundle.StateBundle; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Objects;
assertThat(backstack.canFindFromScope("beep", "parentService1", ScopeLookupMode.ALL)).isTrue(); assertThat(backstack.lookupFromScope("boop", "parentService1", ScopeLookupMode.ALL)).isSameAs(parentService1); assertThat(backstack.lookupFromScope("beep", "parentService1", ScopeLookupMode.ALL)).isSameAs(parentService1); assertThat(backstack.lookupService("parentService1")).isSameAs(parentService1); backstack.setHistory(History.of(new Key2("boop")), StateChange.REPLACE); assertThat(backstack.lookupService("parentService1")).isSameAs(globalService); } private enum ServiceEvent { CREATE, ACTIVE, INACTIVE, DESTROY } private static class Pair<S, T> { private S first; private T second; private Pair(S first, T second) { this.first = first; this.second = second; } public static <S, T> Pair<S, T> of(S first, T second) { return new Pair<>(first, second); } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(first, pair.first) && Objects.equals(second, pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "Pair{" + "first=" + first + ", second=" + second + '}'; } } @Test public void serviceLifecycleCallbacksWork() { final List<Pair<Object, ServiceEvent>> events = new ArrayList<>(); Backstack backstack = new Backstack(); backstack.setScopedServices(new ServiceProvider()); class MyService implements ScopedServices.Activated, ScopedServices.Registered { private int id = 0; MyService(int id) { this.id = id; } @Override public void onServiceActive() { events.add(Pair.of((Object) this, ServiceEvent.ACTIVE)); } @Override public void onServiceInactive() { events.add(Pair.of((Object) this, ServiceEvent.INACTIVE)); } @Override public String toString() { return "MyService{" + "id=" + id + '}'; } @Override public void onServiceRegistered() { events.add(Pair.of((Object) this, ServiceEvent.CREATE)); } @Override public void onServiceUnregistered() { events.add(Pair.of((Object) this, ServiceEvent.DESTROY)); } } final Object service0 = new MyService(0); backstack.setGlobalServices(GlobalServices.builder() .addService("SERVICE0", service0) .build()); final Object service1 = new MyService(1); final Object service2 = new MyService(2); final Object service3 = new MyService(3); final Object service4 = new MyService(4); final Object service5 = new MyService(5); final Object service6 = new MyService(6); final Object service7 = new MyService(7); final Object service8 = new MyService(8); final Object service9 = new MyService(9);
TestKeyWithScope beep = new TestKeyWithScope("beep") {
4
apptik/MultiView
app/src/main/java/io/apptik/multiview/AnimatorsFragment.java
[ "public class BasicMixedRecyclerAdapter extends RecyclerView.Adapter<BasicMixedRecyclerAdapter.ViewHolder> {\n private static final String TAG = \"BasicMixedAdapter\";\n private JsonArray jarr;\n Cursor c;\n\n\n public class ViewHolder extends RecyclerView.ViewHolder {\n public final TextView txt1;\n public final TextView txt2;\n public final TextView txt3;\n public final TextView txt4;\n public final ImageView img1;\n\n public ViewHolder(View v) {\n super(v);\n // Define click listener for the ViewHolder's View.\n v.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Log.d(TAG, \"Element \" + getAdapterPosition() + \" clicked.\");\n }\n });\n txt1 = (TextView)v.findViewById(R.id.txt1);\n txt2 = (TextView)v.findViewById(R.id.txt2);\n txt3 = (TextView)v.findViewById(R.id.txt3);\n txt4 = (TextView)v.findViewById(R.id.txt4);\n img1 = (ImageView)v.findViewById(R.id.img1);\n }\n\n }\n // END_INCLUDE(recyclerViewSampleViewHolder)\n\n /**\n * Initialize the dataset of the Adapter.\n *\n */\n public BasicMixedRecyclerAdapter(JsonArray jsonArray, Context ctx) {\n jarr = jsonArray;\n c = ctx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);\n\n }\n\n // BEGIN_INCLUDE(recyclerViewOnCreateViewHolder)\n // Create new views (invoked by the layout manager)\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n // Create a new view.\n View v = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.item_imagecard, viewGroup, false);\n\n return new ViewHolder(v);\n }\n // END_INCLUDE(recyclerViewOnCreateViewHolder)\n\n // BEGIN_INCLUDE(recyclerViewOnBindViewHolder)\n // Replace the contents of a view (invoked by the layout manager)\n @Override\n public void onBindViewHolder(ViewHolder viewHolder, int position) {\n\n Uri imageUri = null;\n if (c != null) {\n int count = c.getCount();\n if(position>=count) {\n Random rand = new Random();\n position = rand.nextInt(count);\n }\n if (c.moveToPosition(position)) {\n long id = c.getLong(c.getColumnIndex(MediaStore.Images.Media._ID));\n imageUri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + \"/\" + id);\n Log.d(\"image\", imageUri.toString());\n }\n\n }\n Log.d(TAG, \"Element \" + position + \" set.\");\n // Get element from your dataset at this position and replace the contents of the view\n // with that element\n\n viewHolder.txt1.setText(\"title\");\n viewHolder.txt2.setText(\"pos: \" + position);\n if (imageUri != null) {\n //viewHolder.img1.setImageBitmap(BitmapLruCache.get().getBitmap(imageUri, viewHolder.img1.getContext(), viewHolder.img1.getWidth(), viewHolder.img1.getHeight()));\n Glide.with(viewHolder.img1.getContext()).load(imageUri).into(viewHolder.img1);\n }\n\n\n }\n // END_INCLUDE(recyclerViewOnBindViewHolder)\n\n // Return the size of your dataset (invoked by the layout manager)\n @Override\n public int getItemCount() {\n return jarr.size();\n }\n\n\n @Override\n public int getItemViewType(int position) {\n return position%2;\n }\n}", "public class BasicRecyclerAdapter extends RecyclerView.Adapter<BasicRecyclerAdapter.ViewHolder> {\n private static final String TAG = \"RecyclerAdapter\";\n public final JsonArray jarr;\n\n\n public class ViewHolder extends RecyclerView.ViewHolder {\n public final TextView txt1;\n public final TextView txt2;\n public final TextView txt3;\n public final TextView txt4;\n\n public ViewHolder(View v) {\n super(v);\n // Define click listener for the ViewHolder's View.\n v.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Log.d(TAG, \"Element \" + getAdapterPosition() + \" clicked.\");\n }\n });\n txt1 = (TextView) v.findViewById(R.id.txt1);\n txt2 = (TextView) v.findViewById(R.id.txt2);\n txt3 = (TextView) v.findViewById(R.id.txt3);\n txt4 = (TextView) v.findViewById(R.id.txt4);\n }\n\n }\n // END_INCLUDE(recyclerViewSampleViewHolder)\n\n /**\n * Initialize the dataset of the Adapter.\n */\n public BasicRecyclerAdapter(JsonArray jsonArray) {\n jarr = jsonArray;\n }\n\n // BEGIN_INCLUDE(recyclerViewOnCreateViewHolder)\n // Create new views (invoked by the layout manager)\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {\n // Create a new view.\n View v = LayoutInflater.from(viewGroup.getContext())\n .inflate(R.layout.item_card, viewGroup, false);\n\n return new ViewHolder(v);\n }\n // END_INCLUDE(recyclerViewOnCreateViewHolder)\n\n // BEGIN_INCLUDE(recyclerViewOnBindViewHolder)\n // Replace the contents of a view (invoked by the layout manager)\n @Override\n public void onBindViewHolder(ViewHolder viewHolder, final int position) {\n Log.d(TAG, \"Element \" + position + \" set.\");\n // Get element from your dataset at this position and replace the contents of the view\n // with that element\n\n viewHolder.txt1.setText(jarr.getJsonObject(position).getString(\"title\"));\n viewHolder.txt3.setText(jarr.getJsonObject(position).getString(\"info\") + \"/\" +\n jarr.getJsonObject(position).getString(\"info2\"));\n viewHolder.txt4.setText(jarr.getJsonObject(position).getString(\"info3\"));\n viewHolder.txt2.setText(\"pos: \" + position + \", id: \" + jarr.getJsonObject(position).getInt(\"id\"));\n\n\n }\n // END_INCLUDE(recyclerViewOnBindViewHolder)\n\n // Return the size of your dataset (invoked by the layout manager)\n @Override\n public int getItemCount() {\n return jarr.size();\n }\n\n// @Override\n// public long getItemId(int position) {\n// return jarr.getJsonObject(position).getLong(\"id\");\n// }\n//\n// @Override\n// public int getItemViewType(int position) {\n// return position % 2;\n// }\n}", "public class MockData {\n\n static Random rand = new Random();\n\n public static JsonArray getMockJsonArray(int noElements, int picSize) {\n JsonArray res = new JsonArray();\n for (int i = 0; i < noElements; i++) {\n res.add(getRandomEntry(i, picSize));\n }\n\n return res;\n }\n\n public static JsonObject getRandomEntry(int id, int picSize) {\n int cc = (int) (Math.random() * 0x1000000);\n int cc2 = 0xFFFFFF00 ^ cc;\n String color = Integer.toHexString(cc);\n String color2 = Integer.toHexString((0xFFFFFF - cc));\n // String color2 = Integer.toHexString(cc2);\n double lat = 50 + rand.nextInt(300) / 100d;\n double lon = 4 + rand.nextInt(300) / 100d;\n return new JsonObject()\n .put(\"pic\", \"http://dummyimage.com/\" + picSize + \"/\" + color + \"/\" + color2)\n .put(\"title\", \"Item - \" + id)\n .put(\"info\", \"info - \" + color)\n .put(\"info2\", \"info - \" + color2)\n .put(\"info3\", \"info - \" + lat + \":\" + lon)\n .put(\"loc\", new JsonArray().put(lat).put(lon))\n .put(\"id\", id);\n }\n}", "public interface AnimatorProvider {\n\n ViewPropertyAnimatorCompat getAnim(final RecyclerView.ViewHolder viewHolder, Object... args);\n Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args);\n Runnable getAfterAction(final RecyclerView.ViewHolder viewHolder, Object... args);\n}", "public class FlexiItemAnimator extends BaseItemAnimator {\n\n\n private AnimatorProvider vpaRemove;\n private AnimatorProvider vpaAdd;\n private AnimatorProvider vpaChnageOld;\n private AnimatorProvider vpaChangeNew;\n private AnimatorProvider vpaMove;\n\n private Interpolator ipRemove;\n private Interpolator ipAdd;\n private Interpolator ipChangeOld;\n private Interpolator ipChangeNew;\n private Interpolator ipMove;\n\n public FlexiItemAnimator(AnimatorProvider vpaAdd,\n AnimatorProvider vpaChnageOld,\n AnimatorProvider vpaChangeNew,\n AnimatorProvider vpaMove,\n AnimatorProvider vpaRemove) {\n this.vpaAdd = vpaAdd;\n this.vpaChnageOld = vpaChnageOld;\n this.vpaChangeNew = vpaChangeNew;\n this.vpaMove = vpaMove;\n this.vpaRemove = vpaRemove;\n\n Log.v(\"add: \" + vpaAdd);\n Log.v(\"change old: \" + vpaChnageOld);\n Log.v(\"change new: \" + vpaChangeNew);\n Log.v(\"move: \" + vpaMove);\n Log.v(\"remove: \" + vpaRemove);\n }\n\n public Interpolator getIpAdd() {\n return ipAdd;\n }\n\n public void setIpAdd(Interpolator ipAdd) {\n this.ipAdd = ipAdd;\n }\n\n public Interpolator getIpChangeNew() {\n return ipChangeNew;\n }\n\n public void setIpChangeNew(Interpolator ipChangeNew) {\n this.ipChangeNew = ipChangeNew;\n }\n\n public Interpolator getIpChangeOld() {\n return ipChangeOld;\n }\n\n public void setIpChangeOld(Interpolator ipChangeOld) {\n this.ipChangeOld = ipChangeOld;\n }\n\n public Interpolator getIpMove() {\n return ipMove;\n }\n\n public void setIpMove(Interpolator ipMove) {\n this.ipMove = ipMove;\n }\n\n public Interpolator getIpRemove() {\n return ipRemove;\n }\n\n public void setIpRemove(Interpolator ipRemove) {\n this.ipRemove = ipRemove;\n }\n\n public FlexiItemAnimator(AnimatorSetProvider animatorSetProvider) {\n this.vpaAdd = animatorSetProvider.getAddAnimProvider();\n this.vpaChnageOld = animatorSetProvider.getChangeOldItemAnimProvider();\n this.vpaChangeNew = animatorSetProvider.getChangeNewItemAnimProvider();\n this.vpaMove = animatorSetProvider.getMoveAnimProvider();\n this.vpaRemove = animatorSetProvider.getRemoveAnimProvider();\n }\n\n protected void animateRemoveImpl(final RecyclerView.ViewHolder holder) {\n if (vpaRemove == null) {\n dispatchRemoveFinished(holder);\n dispatchFinishedWhenDone();\n return;\n }\n Runnable beforeAction = vpaRemove.getBeforeAction(holder);\n if(beforeAction!=null) {\n beforeAction.run();\n }\n final ViewPropertyAnimatorCompat animation = vpaRemove.getAnim(holder);\n if(ipRemove!=null) {\n animation.setInterpolator(ipRemove);\n }\n animation.setDuration(getRemoveDuration())\n .setListener(new VoidVpaListener() {\n @Override\n public void onAnimationStart(View view) {\n Log.v(\"start remove anim: \" + view);\n dispatchRemoveStarting(holder);\n }\n\n @Override\n public void onAnimationCancel(View view) {\n Log.v(\"cancel remove anim: \" + view);\n resetView(view);\n }\n\n @Override\n public void onAnimationEnd(View view) {\n Log.v(\"end remove anim: \" + view);\n animation.setListener(null);\n resetView(view);\n dispatchRemoveFinished(holder);\n mRemoveAnimations.remove(holder);\n dispatchFinishedWhenDone();\n }\n }).start();\n mRemoveAnimations.add(holder);\n }\n\n @Override\n protected void animateAddImpl(final RecyclerView.ViewHolder holder) {\n if (vpaAdd == null) {\n resetView(holder.itemView);\n dispatchAddFinished(holder);\n dispatchFinishedWhenDone();\n return;\n }\n mAddAnimations.add(holder);\n\n Runnable beforeAction = vpaAdd.getBeforeAction(holder);\n if(beforeAction!=null) {\n beforeAction.run();\n }\n final ViewPropertyAnimatorCompat animation = vpaAdd.getAnim(holder);\n if(ipAdd!=null) {\n animation.setInterpolator(ipAdd);\n }\n animation.setDuration(getAddDuration()).\n setListener(new VoidVpaListener() {\n @Override\n public void onAnimationStart(View view) {\n Log.v(\"start add anim: \" + view);\n dispatchAddStarting(holder);\n }\n\n @Override\n public void onAnimationCancel(View view) {\n Log.v(\"cancel add anim: \" + view);\n resetView(view);\n }\n\n @Override\n public void onAnimationEnd(View view) {\n Log.v(\"end add anim: \" + view);\n animation.setListener(null);\n resetView(view);\n dispatchAddFinished(holder);\n mAddAnimations.remove(holder);\n dispatchFinishedWhenDone();\n }\n }).start();\n }\n\n @Override\n protected void animateMoveImpl(final RecyclerView.ViewHolder holder, final MoveInfo moveInfo) {\n if (vpaMove == null) {\n dispatchMoveFinished(holder);\n dispatchFinishedWhenDone();\n return;\n }\n final int deltaX = moveInfo.toX - moveInfo.fromX;\n final int deltaY = moveInfo.toY - moveInfo.fromY;\n\n mMoveAnimations.add(holder);\n Runnable beforeAction = vpaMove.getBeforeAction(holder, moveInfo);\n if(beforeAction!=null) {\n beforeAction.run();\n }\n final ViewPropertyAnimatorCompat animation = vpaMove.getAnim(holder, moveInfo);\n if(ipMove!=null) {\n animation.setInterpolator(ipMove);\n }\n animation.setDuration(getMoveDuration()).setListener(new VoidVpaListener() {\n @Override\n public void onAnimationStart(View view) {\n Log.v(\"start move anim: \" + view);\n dispatchMoveStarting(holder);\n }\n\n @Override\n public void onAnimationCancel(View view) {\n Log.v(\"cancel move anim: \" + view);\n resetView(view);\n }\n\n @Override\n public void onAnimationEnd(View view) {\n Log.v(\"end move anim: \" + view);\n animation.setListener(null);\n resetView(view);\n dispatchMoveFinished(holder);\n mMoveAnimations.remove(holder);\n dispatchFinishedWhenDone();\n }\n }).start();\n }\n\n @Override\n protected void animateChangeImpl(final BaseItemAnimator.ChangeInfo changeInfo) {\n final RecyclerView.ViewHolder holder = changeInfo.oldHolder;\n final View view = holder == null ? null : holder.itemView;\n final RecyclerView.ViewHolder newHolder = changeInfo.newHolder;\n final View newView = newHolder != null ? newHolder.itemView : null;\n if (view != null && vpaChnageOld != null) {\n mChangeAnimations.add(changeInfo.oldHolder);\n Runnable beforeAction = vpaChnageOld.getBeforeAction(holder, changeInfo);\n if(beforeAction!=null) {\n beforeAction.run();\n }\n final ViewPropertyAnimatorCompat oldViewAnim = vpaChnageOld.getAnim(changeInfo.oldHolder, changeInfo).setDuration(\n getChangeDuration());\n if(ipChangeOld!=null) {\n oldViewAnim.setInterpolator(ipChangeOld);\n }\n oldViewAnim.setListener(new VoidVpaListener() {\n @Override\n public void onAnimationStart(View view) {\n Log.v(\"start change old anim: \" + view);\n dispatchChangeStarting(changeInfo.oldHolder, true);\n }\n\n @Override\n public void onAnimationCancel(View view) {\n Log.v(\"cancel change old anim: \" + view);\n resetView(view);\n }\n\n @Override\n public void onAnimationEnd(View view) {\n Log.v(\"end change old anim: \" + view);\n oldViewAnim.setListener(null);\n Log.v(\"end change old anim before: \" + view);\n resetView(view);\n Log.v(\"end change old anim after: \" + view);\n dispatchChangeFinished(changeInfo.oldHolder, true);\n mChangeAnimations.remove(changeInfo.oldHolder);\n dispatchFinishedWhenDone();\n }\n }).start();\n } else {\n dispatchChangeFinished(changeInfo.oldHolder, true);\n dispatchFinishedWhenDone();\n }\n if (newView != null && vpaChangeNew != null) {\n mChangeAnimations.add(changeInfo.newHolder);\n Runnable beforeAction = vpaChangeNew.getBeforeAction(holder, changeInfo);\n if(beforeAction!=null) {\n beforeAction.run();\n }\n final ViewPropertyAnimatorCompat newViewAnimation = vpaChangeNew.getAnim(changeInfo.newHolder, changeInfo);\n if(ipChangeNew!=null) {\n newViewAnimation.setInterpolator(ipChangeNew);\n }\n newViewAnimation.setDuration(getChangeDuration())\n .setListener(new VoidVpaListener() {\n @Override\n public void onAnimationStart(View view) {\n Log.v(\"start change new anim: \" + view);\n dispatchChangeStarting(changeInfo.newHolder, false);\n }\n\n @Override\n public void onAnimationCancel(View view) {\n Log.v(\"cancel change new anim: \" + view);\n resetView(view);\n }\n\n @Override\n public void onAnimationEnd(View view) {\n Log.v(\"end change new anim: \" + view);\n newViewAnimation.setListener(null);\n resetView(view);\n dispatchChangeFinished(changeInfo.newHolder, false);\n mChangeAnimations.remove(changeInfo.newHolder);\n dispatchFinishedWhenDone();\n }\n }).start();\n } else {\n// dispatchChangeFinished(changeInfo.newHolder, false);\n dispatchFinishedWhenDone();\n }\n }\n\n\n\n}", "public class Providers {\n private Providers() {\n throw new IllegalStateException(\"no instances\");\n }\n\n\n public static AnimatorProvider defaultRemoveAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... ags) {\n return Anims.fadeOut(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider defaultAddAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... ags) {\n return Anims.fadeIn(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider defaultMoveAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.defaultMoveAnim(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n BaseItemAnimator.MoveInfo moveInfo = (BaseItemAnimator.MoveInfo) args[0];\n final int deltaX = moveInfo.toX - moveInfo.fromX;\n final int deltaY = moveInfo.toY - moveInfo.fromY;\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setTranslationX(viewHolder.itemView, -deltaX);\n ViewCompat.setTranslationY(viewHolder.itemView, -deltaY);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider defaultChangeOldViewAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... ags) {\n return Anims.defaultChangeOldViewAnim(viewHolder.itemView, (BaseItemAnimator.ChangeInfo) ags[0]);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider defaultChangeNewViewAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... ags) {\n return Anims.defaultChangeNewViewAnim(viewHolder.itemView, (BaseItemAnimator.ChangeInfo) ags[0]);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider teleportChangeOldViewAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... ags) {\n return Anims.teleportChangeOldViewAnim(viewHolder.itemView, (BaseItemAnimator.ChangeInfo) ags[0]);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider teleportChangeNewViewAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... ags) {\n return Anims.teleportChangeNewViewAnim(viewHolder.itemView, (BaseItemAnimator.ChangeInfo) ags[0]);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setScaleX(viewHolder.itemView, 0);\n ViewCompat.setScaleY(viewHolder.itemView, 0);\n ViewCompat.setTranslationX(viewHolder.itemView, 0);\n ViewCompat.setTranslationY(viewHolder.itemView, 0);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider teleportAddNewViewAnimProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... ags) {\n return Anims.zoom2Normal(viewHolder.itemView).alpha(1);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setScaleX(viewHolder.itemView, 0);\n ViewCompat.setScaleY(viewHolder.itemView, 0);\n ViewCompat.setTranslationX(viewHolder.itemView, 0);\n ViewCompat.setTranslationY(viewHolder.itemView, 0);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n\n public static AnimatorProvider garageDoorAddProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.garageDoorClose(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setRotationX(viewHolder.itemView, 90);\n ViewCompat.setTranslationY(viewHolder.itemView, -(viewHolder.itemView.getMeasuredHeight() / 2));\n viewHolder.itemView.invalidate();\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider garageDoorRemoveProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.garageDoorOpen(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider slideInRightProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideInHorisontal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setTranslationX(viewHolder.itemView,\n viewHolder.itemView.getRootView().getWidth());\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n\n }\n\n public static AnimatorProvider slideOutRightProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideOutRight(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider slideInLeftProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideInHorisontal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setTranslationX(viewHolder.itemView,\n -viewHolder.itemView.getRootView().getWidth());\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider slideOutLeftProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideOutLeft(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n\n public static AnimatorProvider slideInTopProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideInVertical(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setTranslationY(viewHolder.itemView,\n viewHolder.itemView.getRootView().getHeight());\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n\n }\n\n public static AnimatorProvider slideOutTopProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideOutTop(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider slideInBottomProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideInVertical(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setTranslationY(viewHolder.itemView,\n -viewHolder.itemView.getRootView().getHeight());\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider slideOutBottomProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.slideOutBottom(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider zoomInEnterRightProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoom2Normal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth());\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight()/2);\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() / 2);\n ViewCompat.setScaleX(viewHolder.itemView, 0);\n ViewCompat.setScaleY(viewHolder.itemView, 0);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n\n }\n\n public static AnimatorProvider zoomOutExitRightProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomOut(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth());\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight()/2);\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() / 2);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider zoomInExitRightProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomIn(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() * -.1f);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight()/2);\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() / 2);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider zoomInEnterLeftProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoom2Normal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setPivotX(viewHolder.itemView, 0);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight()/2);\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() / 2);\n ViewCompat.setScaleX(viewHolder.itemView, 0);\n ViewCompat.setScaleY(viewHolder.itemView, 0);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider zoomOutExitLeftProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomOut(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, 0);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight()/2);\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() / 2);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n\n public static AnimatorProvider zoomInExitLeftProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomIn(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() * 1.1f);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight()/2);\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() / 2);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n\n public static AnimatorProvider zoomInEnterTopProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoom2Normal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() / 2);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, 0);\n viewHolder.itemView.setPivotY(0);\n ViewCompat.setScaleX(viewHolder.itemView, 0);\n ViewCompat.setScaleY(viewHolder.itemView, 0);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n\n }\n\n public static AnimatorProvider zoomOutExitTopProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomOut(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() / 2);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, 0);\n viewHolder.itemView.setPivotY(0);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider zoomInExitTopProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomIn(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() / 2);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, 0);\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() * 1.1f);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider zoomInEnterBottomProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoom2Normal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() / 2);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight());\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight());\n ViewCompat.setScaleX(viewHolder.itemView, 0);\n ViewCompat.setScaleY(viewHolder.itemView, 0);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider zoomOutExitBottomProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomOut(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() / 2);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight());\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight());\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n\n public static AnimatorProvider zoomInExitBottomProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.zoomIn(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setPivotX(viewHolder.itemView, viewHolder.itemView.getWidth() / 2);\n //TODO https://code.google.com/p/android/issues/detail?id=80863\n //ViewCompat.setPivotY(holder.itemView, holder.itemView.getHeight());\n viewHolder.itemView.setPivotY(viewHolder.itemView.getHeight() * -.1f);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider flipEnterRightProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipEnterHorizontal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setRotationY(viewHolder.itemView, -90);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n\n }\n\n public static AnimatorProvider flipExitRightProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipExitRight(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider flipEnterLeftProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipEnterHorizontal(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setRotationY(viewHolder.itemView, 90);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider flipExitLeftProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipExitLeft(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n\n public static AnimatorProvider flipEnterTopProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipEnterVertical(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setRotationX(viewHolder.itemView, 90);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n\n }\n\n public static AnimatorProvider flipExitTopProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipExitTop(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider flipEnterBottomProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipEnterVertical(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(final RecyclerView.ViewHolder viewHolder, Object... args) {\n return new Runnable() {\n @Override\n public void run() {\n ViewCompat.setAlpha(viewHolder.itemView, 1);\n ViewCompat.setRotationX(viewHolder.itemView, -90);\n }\n };\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n\n public static AnimatorProvider flipExitBottomProvider() {\n return new AnimatorProvider() {\n @Override\n public ViewPropertyAnimatorCompat getAnim(RecyclerView.ViewHolder viewHolder, Object... args) {\n return Anims.flipExitBottom(viewHolder.itemView);\n }\n\n @Override\n public Runnable getBeforeAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n\n @Override\n public Runnable getAfterAction(RecyclerView.ViewHolder viewHolder, Object... args) {\n return null;\n }\n };\n }\n}" ]
import io.apptik.multiview.adapter.BasicMixedRecyclerAdapter; import io.apptik.multiview.adapter.BasicRecyclerAdapter; import io.apptik.multiview.mock.MockData; import io.apptik.multiview.animators.AnimatorProvider; import io.apptik.multiview.animators.FlexiItemAnimator; import io.apptik.multiview.animators.Providers; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup;
/* * Copyright (C) 2015 AppTik Project * * 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 io.apptik.multiview; public class AnimatorsFragment extends Fragment { RecyclerView recyclerView = null;
BasicRecyclerAdapter recyclerAdapter;
1
Darkona/AdventureBackpack2
src/main/java/com/darkona/adventurebackpack/item/ItemAdventureBackpack.java
[ "@Mod(modid = ModInfo.MOD_ID,\n name = ModInfo.MOD_NAME,\n version = ModInfo.MOD_VERSION,\n guiFactory = ModInfo.GUI_FACTORY_CLASS\n)\npublic class AdventureBackpack\n{\n\n @SidedProxy(clientSide = ModInfo.MOD_CLIENT_PROXY, serverSide = ModInfo.MOD_SERVER_PROXY)\n public static IProxy proxy;\n @Mod.Instance(ModInfo.MOD_ID)\n public static AdventureBackpack instance;\n\n //Static things\n public static CreativeTabAB creativeTab = new CreativeTabAB();\n\n\n public boolean chineseNewYear;\n public boolean hannukah;\n public String Holiday;\n PlayerEventHandler playerEventHandler;\n ClientEventHandler clientEventHandler;\n GeneralEventHandler generalEventHandler;\n\n GuiHandler guiHandler;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event)\n {\n\n int year = Calendar.getInstance().get(Calendar.YEAR), month = Calendar.getInstance().get(Calendar.MONTH) + 1, day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);\n\n //Configuration\n FMLCommonHandler.instance().bus().register(new ConfigHandler());\n ConfigHandler.init(event.getSuggestedConfigurationFile());\n chineseNewYear = ChineseCalendar.isChineseNewYear(year, month, day);\n hannukah = JewishCalendar.isHannukah(year, month, day);\n Holiday = Utils.getHoliday();\n\n //ModStuff\n ModItems.init();\n ModBlocks.init();\n ModFluids.init();\n FluidEffectRegistry.init();\n ModEntities.init();\n ModNetwork.init();\n proxy.initNetwork();\n // EVENTS\n playerEventHandler = new PlayerEventHandler();\n generalEventHandler = new GeneralEventHandler();\n clientEventHandler = new ClientEventHandler();\n\n\n MinecraftForge.EVENT_BUS.register(generalEventHandler);\n MinecraftForge.EVENT_BUS.register(clientEventHandler);\n MinecraftForge.EVENT_BUS.register(playerEventHandler);\n\n FMLCommonHandler.instance().bus().register(playerEventHandler);\n\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event)\n {\n\n proxy.init();\n ModRecipes.init();\n\n ModWorldGen.init();\n //GUIs\n guiHandler = new GuiHandler();\n NetworkRegistry.INSTANCE.registerGuiHandler(instance, guiHandler);\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event)\n {\n\n ConfigHandler.IS_TINKERS = Loader.isModLoaded(\"TConstruct\");\n ConfigHandler.IS_THAUM = Loader.isModLoaded(\"Thaumcraft\");\n ConfigHandler.IS_TWILIGHT = Loader.isModLoaded(\"TwilightForest\");\n ConfigHandler.IS_ENVIROMINE = Loader.isModLoaded(\"EnviroMine\");\n ConfigHandler.IS_BUILDCRAFT = Loader.isModLoaded(\"BuildCraft|Core\");\n ConfigHandler.IS_RAILCRAFT = Loader.isModLoaded(\"Railcraft\");\n\n\n if (ConfigHandler.IS_BUILDCRAFT)\n {\n LogHelper.info(\"Buildcraft is present. Acting accordingly\");\n }\n\n if (ConfigHandler.IS_TWILIGHT)\n {\n LogHelper.info(\"Twilight Forest is present. Acting accordingly\");\n }\n\n ConditionalFluidEffect.init();\n ModItems.conditionalInit();\n ModRecipes.conditionalInit();\n\n\n /*\n LogHelper.info(\"DUMPING FLUID INFORMATION\");\n LogHelper.info(\"-------------------------------------------------------------------------\");\n for(Fluid fluid : FluidRegistry.getRegisteredFluids().values())\n {\n\n LogHelper.info(\"Unlocalized name: \" + fluid.getUnlocalizedName());\n LogHelper.info(\"Name: \" + fluid.getName());\n LogHelper.info(\"\");\n }\n LogHelper.info(\"-------------------------------------------------------------------------\");\n */\n /*\n LogHelper.info(\"DUMPING TILE INFORMATION\");\n LogHelper.info(\"-------------------------------------------------------------------------\");\n for (Block block : GameData.getBlockRegistry().typeSafeIterable())\n {\n LogHelper.info(\"Block= \" + block.getUnlocalizedName());\n }\n LogHelper.info(\"-------------------------------------------------------------------------\");\n */\n }\n\n}", "public class BlockAdventureBackpack extends BlockContainer\n{\n\n public BlockAdventureBackpack()\n {\n super(new BackpackMaterial());\n setHardness(1.0f);\n setStepSound(soundTypeCloth);\n setResistance(2000f);\n }\n\n /**\n * Pretty effects for the bookshelf ;)\n *\n * @param world\n * @param x\n * @param y\n * @param z\n * @param random\n */\n @Override\n @SideOnly(Side.CLIENT)\n public void randomDisplayTick(World world, int x, int y, int z, Random random)\n {\n if (getAssociatedTileColorName(world, x, y, z).equals(\"Bookshelf\"))\n {\n ChunkCoordinates enchTable = Utils.findBlock3D(world, x, y, z, Blocks.enchanting_table, 2, 2);\n if(enchTable !=null)\n {\n if (!world.isAirBlock((enchTable.posX - x) / 2 + x, enchTable.posY, (enchTable.posZ - z) / 2 + z))\n {\n return;\n }\n for (int o = 0; o < 4; o++)\n {\n world.spawnParticle(\"enchantmenttable\",enchTable.posX + 0.5D,enchTable.posY + 2.0D,enchTable.posZ + 0.5D,\n ((x - enchTable.posX) + random.nextFloat()) - 0.5D,\n ((y - enchTable.posY) - random.nextFloat() - 1.0F),\n ((z - enchTable.posZ) + random.nextFloat()) - 0.5D);\n }\n }\n }\n }\n\n public int getMobilityFlag()\n {\n return 0;\n }\n\n @Override\n public String getHarvestTool(int metadata)\n {\n return null;\n }\n\n @Override\n public int getHarvestLevel(int metadata)\n {\n return 0;\n }\n\n @Override\n public boolean isToolEffective(String type, int metadata)\n {\n return true;\n }\n\n private String getAssociatedTileColorName(IBlockAccess world, int x, int y, int z)\n {\n return ((TileAdventureBackpack) world.getTileEntity(x, y, z)).getColorName();\n }\n @Override\n public boolean canRenderInPass(int pass)\n {\n return true;\n }\n\n @Override\n public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity)\n {\n return false;\n }\n\n @Override\n public float getEnchantPowerBonus(World world, int x, int y, int z)\n {\n return getAssociatedTileColorName(world, x, y, z).equals(\"Bookshelf\") ? 10 : 0;\n }\n\n @Override\n public boolean canBeReplacedByLeaves(IBlockAccess world, int x, int y, int z)\n {\n return false;\n }\n\n @Override\n public boolean isWood(IBlockAccess world, int x, int y, int z)\n {\n return false;\n }\n\n @Override\n public boolean isLeaves(IBlockAccess world, int x, int y, int z)\n {\n return false;\n }\n\n @Override\n public boolean canCreatureSpawn(EnumCreatureType type, IBlockAccess world, int x, int y, int z)\n {\n return false;\n }\n\n @Override\n public int getFlammability(IBlockAccess world, int x, int y, int z, ForgeDirection face)\n {\n return 0;\n }\n\n @Override\n public boolean canHarvestBlock(EntityPlayer player, int meta)\n {\n return true;\n }\n\n @Override\n public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity)\n {\n if (getAssociatedTileColorName(world, x, y, z).equals(\"Cactus\"))\n {\n entity.attackEntityFrom(DamageSource.cactus, 1.0F);\n }\n }\n\n /**\n * Called when a player hits the block. Args: world, x, y, z, player\n *\n * @param p_149699_1_\n * @param p_149699_2_\n * @param p_149699_3_\n * @param p_149699_4_\n * @param p_149699_5_\n */\n @Override\n public void onBlockClicked(World p_149699_1_, int p_149699_2_, int p_149699_3_, int p_149699_4_, EntityPlayer p_149699_5_)\n {\n super.onBlockClicked(p_149699_1_, p_149699_2_, p_149699_3_, p_149699_4_, p_149699_5_);\n }\n\n /**\n * Called when a block is placed using its ItemBlock. Args: World, X, Y, Z, side, hitX, hitY, hitZ, block metadata\n *\n * @param world\n * @param x\n * @param y\n * @param z\n * @param side\n * @param hitX\n * @param hitY\n * @param hitZ\n * @param meta\n */\n @Override\n public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta)\n {\n return super.onBlockPlaced(world, x, y, z, side, hitX, hitY, hitZ, meta);\n }\n\n\n @Override\n public boolean isFlammable(IBlockAccess world, int x, int y, int z, ForgeDirection face)\n {\n return false;\n }\n\n @Override\n public String getUnlocalizedName()\n {\n return \"blockAdventureBackpack\";\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister iconRegister)\n {\n Icons.milkStill = iconRegister.registerIcon(ModInfo.MOD_ID + \":fluid.milk\");\n Icons.melonJuiceStill = iconRegister.registerIcon(ModInfo.MOD_ID + \":fluid.melonJuiceStill\");\n Icons.melonJuiceFlowing = iconRegister.registerIcon(ModInfo.MOD_ID + \":fluid.melonJuiceFlowing\");\n Icons.mushRoomStewStill = iconRegister.registerIcon(ModInfo.MOD_ID + \":fluid.mushroomStewStill\");\n Icons.mushRoomStewFlowing = iconRegister.registerIcon(ModInfo.MOD_ID + \":fluid.mushroomStewFlowing\");\n }\n\n @Override\n public int getLightValue(IBlockAccess world, int x, int y, int z)\n {\n if (getAssociatedTileColorName(world, x, y, z).equals(\"Glowstone\"))\n {\n return 15;\n } else if (world.getTileEntity(x, y, z) != null && world.getTileEntity(x, y, z) instanceof TileAdventureBackpack)\n {\n return ((TileAdventureBackpack) world.getTileEntity(x, y, z)).getLuminosity();\n } else\n {\n return 0;\n }\n }\n\n public int isProvidingWeakPower(IBlockAccess world, int x, int y, int z, int meta)\n {\n return getAssociatedTileColorName(world, x, y, z).equals(\"Redstone\") ? 15 : 0;\n }\n\n @Override\n public boolean canConnectRedstone(IBlockAccess world, int x, int y, int z, int side)\n {\n return getAssociatedTileColorName(world, x, y, z).equals(\"Redstone\");\n }\n\n @Override\n public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ)\n {\n\n FMLNetworkHandler.openGui(player, AdventureBackpack.instance, GuiHandler.BACKPACK_TILE, world, x, y, z);\n return true;\n }\n\n\n @Override\n public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player)\n {\n ItemStack backpack = new ItemStack(ModItems.adventureBackpack, 1);\n BackpackNames.setBackpackColorNameFromDamage(backpack, BackpackNames.getBackpackDamageFromName(getAssociatedTileColorName(world, x, y, z)));\n return backpack;\n }\n\n @Override\n public boolean hasTileEntity(int meta)\n {\n return true;\n }\n\n @Override\n public void setBlockBoundsBasedOnState(IBlockAccess blockAccess, int x, int y, int z)\n {\n int meta = blockAccess.getBlockMetadata(x, y, z);\n meta = (meta & 8) >= 8 ? meta - 8 : meta;\n meta = (meta & 4) >= 4 ? meta - 4 : meta;\n switch (meta)\n {\n case 0:\n case 2:\n setBlockBounds(0.0F, 0.0F, 0.4F, 1.0F, 0.6F, 0.6F);\n break;\n case 1:\n case 3:\n setBlockBounds(0.4F, 0.0F, 0.0F, 0.6F, 0.6F, 1.0F);\n break;\n }\n }\n\n @Override\n public int getRenderType()\n {\n return -1;\n }\n\n @Override\n public boolean isOpaqueCube()\n {\n return false;\n }\n\n @Override\n public boolean renderAsNormalBlock()\n {\n return false;\n }\n\n @Override\n public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack)\n {\n int dir = MathHelper.floor_double((player.rotationYaw * 4F) / 360F + 0.5D) & 3;\n if (stack != null && stack.stackTagCompound != null && stack.stackTagCompound.hasKey(\"color\"))\n {\n if (stack.stackTagCompound.getString(\"color\").contains(\"BlockRedstone\"))\n {\n dir = dir | 8;\n }\n if (stack.stackTagCompound.getString(\"color\").contains(\"Lightgem\"))\n {\n dir = dir | 4;\n }\n }\n world.setBlockMetadataWithNotify(x, y, z, dir, 3);\n createNewTileEntity(world, world.getBlockMetadata(x, y, z));\n\n }\n\n @Override\n public boolean canPlaceBlockOnSide(World par1World, int par2, int par3, int par4, int side)\n {\n return (ForgeDirection.getOrientation(side) == ForgeDirection.UP);\n }\n\n @Override\n public int quantityDropped(int meta, int fortune, Random random)\n {\n return 0;\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z)\n {\n setBlockBoundsBasedOnState(world, x, y, z);\n return super.getSelectedBoundingBoxFromPool(world, x, y, z);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int par1, int par2)\n {\n return Blocks.wool.getIcon(par1,par2);\n }\n\n @Override\n public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z)\n {\n setBlockBoundsBasedOnState(world, x, y, z);\n return super.getCollisionBoundingBoxFromPool(world, x, y, z);\n }\n\n @Override\n public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 start, Vec3 end)\n {\n setBlockBoundsBasedOnState(world, x, y, z);\n return super.collisionRayTrace(world, x, y, z, start, end);\n }\n\n @Override\n public boolean canReplace(World p_149705_1_, int p_149705_2_, int p_149705_3_, int p_149705_4_, int p_149705_5_, ItemStack p_149705_6_)\n {\n return false;\n }\n\n @Override\n public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean harvest)\n {\n TileEntity tile = world.getTileEntity(x, y, z);\n\n if (tile instanceof TileAdventureBackpack && !world.isRemote && player != null)\n {\n if ((player.isSneaking()) ?\n ((TileAdventureBackpack) tile).equip(world, player, x, y, z) :\n ((TileAdventureBackpack) tile).drop(world, player, x, y, z))\n {\n return world.func_147480_a(x, y, z, false);\n }\n } else\n {\n return world.func_147480_a(x, y, z, false);\n }\n return false;\n }\n\n @Override\n public void breakBlock(World world, int x, int y, int z, Block block, int meta)\n {\n TileEntity te = world.getTileEntity(x, y, z);\n if (te != null && te instanceof IInventory)\n {\n IInventory inventory = (IInventory) te;\n\n for (int i = 0; i < inventory.getSizeInventory(); i++)\n {\n ItemStack stack = inventory.getStackInSlotOnClosing(i);\n\n if (stack != null)\n {\n float spawnX = x + world.rand.nextFloat();\n float spawnY = y + world.rand.nextFloat();\n float spawnZ = z + world.rand.nextFloat();\n float mult = 0.05F;\n\n EntityItem droppedItem = new EntityItem(world, spawnX, spawnY, spawnZ, stack);\n\n droppedItem.motionX = -0.5F + world.rand.nextFloat() * mult;\n droppedItem.motionY = 4 + world.rand.nextFloat() * mult;\n droppedItem.motionZ = -0.5 + world.rand.nextFloat() * mult;\n\n world.spawnEntityInWorld(droppedItem);\n }\n }\n\n\n }\n\n super.breakBlock(world, x, y, z, world.getBlock(x, y, z), meta);\n }\n\n @Override\n public TileEntity createTileEntity(World world, int metadata)\n {\n return new TileAdventureBackpack();\n }\n\n @Override\n public TileEntity createNewTileEntity(World world, int metadata)\n {\n return createTileEntity(world, metadata);\n }\n\n @Override\n public boolean canDropFromExplosion(Explosion p_149659_1_)\n {\n return false;\n }\n\n @Override\n public void onBlockDestroyedByExplosion(World world, int x, int y, int z, Explosion explosion) {\n world.func_147480_a(x, y, z, false);\n }\n\n @Override\n public void onBlockExploded(World world, int x, int y, int z, Explosion explosion) {\n //DO NOTHING\n }\n}", "public class BackpackAbilities\n{\n\n public static BackpackAbilities backpackAbilities = new BackpackAbilities();\n public static BackpackRemovals backpackRemovals = new BackpackRemovals();\n\n /**\n *\n * @param colorName\n * @return\n */\n public static boolean hasAbility(String colorName)\n {\n for (String valid : validWearingBackpacks)\n {\n if (valid.equals(colorName))\n {\n return true;\n }\n }\n return false;\n }\n\n public static boolean hasRemoval(String colorName)\n {\n for (String valid : validRemovalBackpacks)\n {\n if (valid.equals(colorName))\n {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Executes the ability of any given backpack, be it on the ground or be it on a player.\n *\n * @param player An entity player, can be null in the case of the tile entity.\n * @param world This is necessary, so get it from wherever you can inside the class you're calling this.\n * @param backpack An object representing a backpack, either in its ItemStack form or its TileEntity form.\n */\n public void executeAbility(EntityPlayer player, World world, Object backpack)\n {\n if (backpack instanceof ItemStack)\n {\n String colorName = BackpackNames.getBackpackColorName((ItemStack)backpack);\n try\n {\n //This is black magic and shouldn't be attempted by the faint of heart.\n this.getClass()\n .getMethod(\"item\" + colorName, EntityPlayer.class, World.class, ItemStack.class).\n invoke(backpackAbilities, player, world, backpack);\n } catch (Exception oops)\n {\n //NOBODY CARES\n }\n }\n\n if (backpack instanceof TileAdventureBackpack)\n {\n String colorName = ((TileAdventureBackpack) backpack).getColorName();\n try\n {\n /*\n This is witchery, witchery I say!\n But seriously, if you want to know how this works just pay very close attention:\n invoke will execute any method of a given class, okay? so this should be obvious.\n Look at the names of the methods in this class and you'll figure it out.\n You have to indicate exactly the classes that the method should use as parameters so\n be very careful with \"getMethod\".\n */\n this.getClass()\n .getMethod(\"tile\" + colorName, World.class, TileAdventureBackpack.class)\n .invoke(backpackAbilities, world, backpack);\n } catch (Exception oops)\n {\n //Seriously, nobody cares if this can't work, this is just so the game won't explode.\n }\n }\n\n }\n\n public void executeRemoval(EntityPlayer player, World world,ItemStack backpack )\n {\n\n String colorName = BackpackNames.getBackpackColorName(backpack);\n try\n {\n //This is black magic and shouldn't be attempted by the faint of heart.\n backpackRemovals.getClass()\n .getMethod(\"item\" + colorName, EntityPlayer.class, World.class, ItemStack.class).\n invoke(backpackRemovals, player, world, backpack);\n } catch (Exception oops)\n {\n LogHelper.error(\"---Something bad happened when removing a backpack---\");\n oops.printStackTrace();\n }\n }\n /**\n * These are the colorNames of the backpacks that have abilities when being worn.\n */\n private static String[] validWearingBackpacks = {\n \"Bat\", \"Squid\", \"Pigman\", \"Cactus\", \"Cow\", \"Pig\", \"Dragon\", \"Slime\", \"Chicken\", \"Wolf\", \"Ocelot\", \"Creeper\", \"Rainbow\", \"Melon\", \"Sunflower\",\"Mooshroom\"};\n\n private static String[] validRemovalBackpacks = {\n \"Bat\", \"Squid\", \"Dragon\", \"Rainbow\"\n };\n /**\n * These are the colorNames of the backpacks that have abilities while being blocks. Note that not all the\n * backpacks that have particularities while in block form necessarily have abilities.\n *\n * @see com.darkona.adventurebackpack.block.BlockAdventureBackpack\n */\n private static String[] validTileBackpacks = {\"Cactus\",\"Melon\"};\n\n /**\n * Detects if a player is under the rain. For detecting when it is Under The Sea (maybe to sing a nice Disney tune)\n * it won't work, there's a different method for that, isInWater\n *\n * @param player The player\n * @return True if the player is outside and it's raining.\n */\n private boolean isUnderRain(EntityPlayer player)\n {\n return player.worldObj.canLightningStrikeAt(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY),\n MathHelper.floor_double(player.posZ))\n || player.worldObj.canLightningStrikeAt(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY + player.height),\n MathHelper.floor_double(player.posZ));\n }\n\n /**\n * This backpack will feed you while you stay in the sun, slowly. At the very least you shouldn't starve.\n * @param player\n * @param world\n * @param backpack\n */\n public void itemSunflower(EntityPlayer player, World world, ItemStack backpack)\n {\n InventoryBackpack inv = new InventoryBackpack(backpack);\n\n if (inv.getLastTime() <= 0)\n {\n if(world.isDaytime() &&\n /*!world.isRemote &&*/\n world.canBlockSeeTheSky(MathHelper.floor_double(player.posX),MathHelper.floor_double(player.posY+1),MathHelper.floor_double(player.posZ))) {\n player.getFoodStats().addStats(2, 0.2f);\n //LogHelper.info(\"OMNOMNOMNOM\");\n }\n inv.setLastTime(Utils.secondsToTicks(120));\n }else{\n inv.setLastTime(inv.getLastTime() - 1);\n }\n inv.dirtyTime();\n }\n\n /**\n * Nana nana nana nana Bat - Batpack! See in the dark!\n * @param player\n * @param world\n * @param backpack\n */\n public void itemBat(EntityPlayer player, World world, ItemStack backpack)\n {\n //Shameless rip-off from Machinemuse. Thanks Claire, I don't have to reinvent the wheel thanks to you.\n //I will use a different potion id to avoid conflicting with her modular suits\n PotionEffect nightVision = null;\n if (player.isPotionActive(Potion.nightVision.id)) {\n nightVision = player.getActivePotionEffect(Potion.nightVision);\n }\n if (nightVision == null || nightVision.getDuration() < 40 && nightVision.getAmplifier() != -4)\n {\n player.addPotionEffect(new PotionEffect(Potion.nightVision.id, 5000, -4));\n }\n }\n\n public void itemSquid(EntityPlayer player, World world, ItemStack backpack)\n {\n if (player.isInWater())\n {\n player.addPotionEffect(new PotionEffect(Potion.waterBreathing.getId(), 1, -5));\n itemBat(player, world, backpack);\n }else{\n backpackRemovals.itemSquid(player,world, backpack);\n }\n }\n\n public void itemIronGolem(EntityPlayer player, World world, ItemStack backpack)\n {\n\n }\n\n public void itemPigman(EntityPlayer player, World world, ItemStack backpack)\n {\n PotionEffect potion = null;\n if (player.isPotionActive(Potion.fireResistance.id)) {\n potion = player.getActivePotionEffect(Potion.fireResistance);\n }\n if (potion == null || potion.getDuration() < 5 && potion.getAmplifier() != -5)\n {\n player.addPotionEffect(new PotionEffect(Potion.fireResistance.id, 5000, -5));\n }\n }\n\n /**\n * Mirroring real life cactii, the Cactus Backpack fills with water slowly or rapidly depending where is the player.\n * If it's raining it will fill 1milibucket of water each tick.\n * If the player is in water it will fill 2milibuckets of water each tick.\n * The quantities can be combined.\n *\n * @param player The player. No, seriously.\n * @param world The world the player is in.\n * @param backpack The backpack the player is wearing. This should be rechecked like 20 times by now, so\n * I'm not checking.\n */\n public void itemCactus(EntityPlayer player, World world, ItemStack backpack)\n {\n //lastTime is in ticks for this backpack.\n if(world.isRemote)return;\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int drops = 0;\n if (player.isInWater())\n {\n drops += 2;\n }\n if (isUnderRain(player))\n {\n drops += 1;\n }\n\n if (inv.getLastTime() <= 0 && drops > 0)\n {\n inv.setLastTime(5);\n FluidStack raindrop = new FluidStack(FluidRegistry.WATER, drops);\n inv.getLeftTank().fill(raindrop, true);\n inv.getRightTank().fill(raindrop, true);\n }else{\n inv.setLastTime(inv.getLastTime() - 1);\n }\n inv.dirtyTime();\n inv.dirtyTanks();\n }\n\n /**\n * The Pig Backpack will annoy you and your friends! This beautiful design by 豚, will do as the pigs do when they\n * are frolicking around in the green pastures and terrifying slaughterhouses of the Minecraft world, after a random\n * number of seconds. It's not so frequent as I'd like.\n * Translation for pigs: Oink oink oink Oink! squee oink oink Minecraft Oink oink. \"Oink\" oink oink.\n *\n * @param player The player\n * @param world The world object\n * @param backpack The backpack the player is wearing.\n */\n public void itemPig(EntityPlayer player, World world, ItemStack backpack)\n {\n //lastTime is in seconds for this backpack.\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int oinkTime = inv.getLastTime() - 1;\n if (oinkTime <= 0)\n {\n world.playSoundAtEntity(player, \"mob.pig.say\", 0.8f, 1f);\n oinkTime = Utils.secondsToTicks(world.rand.nextInt(61));\n }\n inv.setLastTime(oinkTime);\n inv.dirtyTime();\n }\n\n /**\n * Squishy! The Slime Backpack has an incredibly useless \"ability\". Makes the player leave a slimy trail of\n * particles whenever he or she is running, and make that splishy splashy squishy sound on each step as well!.\n *\n * @param player\n * @param world\n * @param backpack\n */\n public void itemSlime(EntityPlayer player, World world, ItemStack backpack)\n {\n //lastTime is in Ticks for this backpack.\n //0 is Full Moon, 1 is Waning Gibbous, 2 is Last Quarter, 3 is Waning Crescent,\n // 4 is New Moon, 5 is Waxing Crescent, 6 is First Quarter and 7 is Waxing Gibbous\n if (world.getMoonPhase() == 0 && !world.isDaytime())\n {\n player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 1, 1));\n }\n if (player.onGround)\n {\n\n if ((player.moveForward == 0 && player.moveStrafing == 0) && (Math.abs(player.moveForward) < 3 && Math.abs(player.moveStrafing)<3) )\n {\n player.addVelocity(player.motionX *= 0.828, 0, player.motionZ *= 0.828);\n }\n if (player.isSprinting())\n {\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int slimeTime = inv.getLastTime() > 0 ? inv.getLastTime() - 1 : 5;\n if (slimeTime <= 0)\n {\n if (!world.isRemote)\n {\n ModNetwork.sendToNearby(new EntityParticlePacket.Message(EntityParticlePacket.SLIME_PARTICLE, player), player);\n }\n world.playSoundAtEntity(player, \"mob.slime.small\", 0.6F, (world.rand.nextFloat() - world.rand.nextFloat()) * 1F);\n slimeTime = 5;\n }\n inv.setLastTime(slimeTime);\n inv.dirtyTime();\n }\n }\n }\n\n /**\n * The Chicken Backpack will go and *plop* an egg for you randomly each so many seconds. It's very rare though.\n *\n * @param player\n * @param world\n * @param backpack\n */\n public void itemChicken(EntityPlayer player, World world, ItemStack backpack)\n {\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int eggTime = inv.getLastTime() - 1 ;\n if (eggTime <= 0)\n {\n player.playSound(\"mob.chicken.plop\", 1.0F, (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F + 1.0F);\n if (!world.isRemote) player.dropItem(Items.egg, 1);\n eggTime = Utils.secondsToTicks(200 + 10 * world.rand.nextInt(10));\n }\n inv.setLastTime(eggTime);\n inv.dirtyTime();\n }\n\n /**\n * The Melon Backpack, like his cousin the Cactus Backpack, will fill itself, but with delicious\n * and refreshing Melon Juice, if the backpack is wet in any way.\n *\n * @param player\n * @param world\n * @param backpack\n */\n public void itemMelon(EntityPlayer player, World world, ItemStack backpack)\n {\n //lastTime is in ticks for this backpack.\n if(world.isRemote)return;\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int drops = 0;\n if (player.isInWater())\n {\n drops += 2;\n }\n if (isUnderRain(player))\n {\n drops += 1;\n }\n\n if (inv.getLastTime() <= 0 && drops > 0)\n {\n inv.setLastTime(5);\n FluidStack raindrop = new FluidStack(ModFluids.melonJuice, drops);\n inv.getLeftTank().fill(raindrop, true);\n inv.getRightTank().fill(raindrop, true);\n }else{\n inv.setLastTime(inv.getLastTime() - 1);\n }\n inv.dirtyTime();\n inv.dirtyTanks();\n }\n\n /**\n * The Dragon Backpack does something awesome.\n *\n * @param player\n * @param world\n * @param backpack\n */\n public void itemDragon(EntityPlayer player, World world, ItemStack backpack)\n {\n itemPigman(player,world,backpack);\n itemSquid(player, world, backpack);\n PotionEffect potion = null;\n if (player.isPotionActive(Potion.regeneration.id)) {\n potion = player.getActivePotionEffect(Potion.regeneration);\n }\n if (potion == null || potion.getDuration() < 40 && potion.getAmplifier() != -5)\n {\n player.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), 5000, -5));\n }\n potion = null;\n if (player.isPotionActive(Potion.damageBoost.id)) {\n potion = player.getActivePotionEffect(Potion.damageBoost);\n }\n if (potion == null || potion.getDuration() < 40 && potion.getAmplifier() != -5) {\n player.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), 5000, -5));\n }\n }\n\n /**\n * Sneaky! Scare your friends! Or your enemies!\n * Sneak on another player to make them jump in confusion as they think one of those green bastards is behind him/her.\n * You can only do it once every so often. A couple of minutes. Remember, you must be sneaking.\n *\n * @param player\n * @param world\n * @param backpack\n * @see com.darkona.adventurebackpack.handlers.PlayerEventHandler\n */\n @SuppressWarnings(\"unchecked\")\n public void itemCreeper(EntityPlayer player, World world, ItemStack backpack)\n {\n //lastTime is in seconds for this ability\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int pssstTime = inv.getLastTime() - 1;\n\n if (pssstTime <= 0)\n {\n pssstTime = 20;\n if (player.isSneaking())\n {\n List<Entity> entities = player.worldObj.getEntitiesWithinAABBExcludingEntity(player,\n AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ,\n player.posX + 1.0D, player.posY + 1.0D,\n player.posZ + 1.0D).expand(5.0D, 1.0D, 5.0D));\n if (entities.isEmpty())\n {\n pssstTime -= 1;\n return;\n }\n\n for (Entity entity : entities)\n {\n if (entity instanceof EntityPlayer)\n {\n if (player.getDistanceToEntity(entity) <= 3)\n {\n world.playSoundAtEntity(player, \"creeper.primed\", 1.2F, 0.5F);\n pssstTime = Utils.secondsToTicks(120);\n }\n }\n }\n }\n }\n inv.setLastTime(pssstTime);\n inv.markDirty();\n }\n\n private FluidStack milkStack = new FluidStack(FluidRegistry.getFluid(\"milk\"), 1);\n private FluidStack soupStack = new FluidStack(FluidRegistry.getFluid(\"mushroomstew\"), 1);\n private FluidStack lavaStack = new FluidStack(FluidRegistry.LAVA, 1);\n\n /**\n * The Cow Backpack fills itself with milk when there is wheat in the backpack's inventory, but it will do so slowly\n * and will eat the wheat. It's like having a cow in your backpack. Each 16 wheat makes a bucket. It only happens\n * when it is being worn. For not-player related milk generation go get a cow. Moo!\n *\n * @param player\n * @param world\n * @param backpack\n */\n public void itemCow(EntityPlayer player, World world, ItemStack backpack)\n {\n if (world.isRemote) return;\n InventoryBackpack inv = new InventoryBackpack(backpack);\n inv.openInventory();\n\n if (inv.getLeftTank().fill(milkStack, false) <= 0 && inv.getRightTank().fill(milkStack, false) <= 0)\n {\n return;\n }\n //Set Cow Properties\n int wheatConsumed = 0;\n int milkTime = -1;\n if (inv.getExtendedProperties() != null)\n {\n if (inv.extendedProperties.hasKey(\"wheatConsumed\"))\n {\n wheatConsumed = inv.extendedProperties.getInteger(\"wheatConsumed\");\n milkTime = inv.extendedProperties.getInteger(\"milkTime\") - 1;\n }\n }\n\n int eatTime = (inv.getLastTime() - 1 >= 0) ? inv.getLastTime() - 1 : 0;\n if (inv.hasItem(Items.wheat) && eatTime <= 0 && milkTime <= 0)\n {\n eatTime = 20;\n //LogHelper.info(\"Consuming Wheat in \" + ((world.isRemote) ? \"Client\" : \"Server\"));\n inv.consumeInventoryItem(Items.wheat);\n wheatConsumed++;\n inv.dirtyInventory();\n }\n\n int factor = 1;\n if (wheatConsumed == 16)\n {\n wheatConsumed = 0;\n milkTime = (1000 * factor) - factor;\n world.playSoundAtEntity(player, \"mob.cow.say\", 1f, 1f);\n }\n\n if (milkTime >= 0 && (milkTime % factor == 0))\n {\n if (inv.getLeftTank().fill(milkStack, true) <= 0)\n {\n inv.getRightTank().fill(milkStack, true);\n }\n inv.dirtyTanks();\n }\n if (milkTime < -1) milkTime = -1;\n inv.extendedProperties.setInteger(\"wheatConsumed\", wheatConsumed);\n inv.extendedProperties.setInteger(\"milkTime\", milkTime);\n inv.setLastTime(eatTime);\n // inv.setLastTime(eatTime);\n inv.dirtyExtended();\n //inv.dirtyTanks();\n inv.dirtyTime();\n //inv.dirtyInventory();\n\n //So naughty!!!\n }\n\n public void itemMooshroom(EntityPlayer player, World world, ItemStack backpack)\n {\n if (world.isRemote) return;\n InventoryBackpack inv = new InventoryBackpack(backpack);\n inv.openInventory();\n\n if (inv.getLeftTank().fill(soupStack, false) <= 0 && inv.getRightTank().fill(soupStack, false) <= 0)\n {\n return;\n }\n //Set Cow Properties\n int wheatConsumed = 0;\n int milkTime = -1;\n if (inv.getExtendedProperties() != null)\n {\n if (inv.extendedProperties.hasKey(\"wheatConsumed\"))\n {\n wheatConsumed = inv.extendedProperties.getInteger(\"wheatConsumed\");\n milkTime = inv.extendedProperties.getInteger(\"milkTime\") - 1;\n }\n }\n\n int eatTime = (inv.getLastTime() - 1 >= 0) ? inv.getLastTime() - 1 : 0;\n if (inv.hasItem(Items.wheat) && eatTime <= 0 && milkTime <= 0)\n {\n eatTime = 20;\n //LogHelper.info(\"Consuming Wheat in \" + ((world.isRemote) ? \"Client\" : \"Server\"));\n inv.consumeInventoryItem(Items.wheat);\n wheatConsumed++;\n inv.dirtyInventory();\n }\n\n int factor = 1;\n if (wheatConsumed == 16)\n {\n wheatConsumed = 0;\n milkTime = (1000 * factor) - factor;\n world.playSoundAtEntity(player, \"mob.cow.say\", 1f, 1f);\n }\n\n if (milkTime >= 0 && (milkTime % factor == 0))\n {\n if (inv.getLeftTank().fill(soupStack, true) <= 0)\n {\n inv.getRightTank().fill(soupStack, true);\n }\n inv.dirtyTanks();\n }\n if (milkTime < -1) milkTime = -1;\n inv.extendedProperties.setInteger(\"wheatConsumed\", wheatConsumed);\n inv.extendedProperties.setInteger(\"milkTime\", milkTime);\n inv.setLastTime(eatTime);\n // inv.setLastTime(eatTime);\n inv.dirtyExtended();\n //inv.dirtyTanks();\n inv.dirtyTime();\n //inv.dirtyInventory();\n\n //So naughty!!!\n }\n\n /**\n * The Wolf Backpack is a handy one if you're out in the wild. It checks around for any wolves that may lurk around.\n * If any of them gets mad at you, it will smell the scent of it's kin on you and promptly forget about the whole\n * deal. Smelling like dog is awesome.\n *\n * @param player the player\n * @param world the world\n * @param backpack the backpack\n */\n @SuppressWarnings(\"unchecked\")\n public void itemWolf(EntityPlayer player, World world, ItemStack backpack)\n {\n //lastTime is in Ticks for this backpack\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int lastCheckTime = inv.getLastTime() - 1;\n\n if (lastCheckTime <= 0)\n {\n lastCheckTime = 20;\n List<EntityWolf> wolves = world.getEntitiesWithinAABB(\n EntityWolf.class,\n AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ,\n player.posX + 1.0D, player.posY + 1.0D,\n player.posZ + 1.0D).expand(16.0D, 4.0D, 16.0D));\n if (wolves.isEmpty()) return;\n\n for (EntityWolf wolf : wolves)\n {\n if (wolf.isAngry() && wolf.getAttackTarget() == player)\n {\n wolf.setAngry(false);\n wolf.setAttackTarget(null);\n wolf.setRevengeTarget(null);\n Iterator<?> i2 = wolf.targetTasks.taskEntries.iterator();\n while (i2.hasNext())\n {\n ((EntityAIBase) i2.next()).resetTask();\n }\n }\n }\n }\n inv.setLastTime(lastCheckTime);\n inv.dirtyTime();\n }\n\n /**\n * The Blaze Backpack will make you inmune to fire and lava and burning and heat and... not really. You're supposed\n * to die a fiery death if you are not careful, but this backpack will protect you against those burning fire\n * elemental inhabitants of the Nether. Any blast of fire directed your way will be stopped, deflected or whatever.\n *\n * @param player\n * @param world\n * @param backpack\n */\n public void itemBlaze(EntityPlayer player, World world, ItemStack backpack)\n {\n\n }\n\n /**\n * Like actual Ocelots and Cats, the Ocelot Backpack will scare the hell out of Creepers, so they won't creep on you\n * while you're busy doing something else, paying no attention whatsoever at your surroundings like a mindless chicken.\n *\n * @param player\n * @param world\n * @param backpack\n */\n @SuppressWarnings(\"unchecked\")\n public void itemOcelot(EntityPlayer player, World world, ItemStack backpack)\n {\n //lastTime in this backpack is in Ticks.\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int lastCheckTime = inv.getLastTime() - 1;\n if (lastCheckTime <= 0)\n {\n lastCheckTime = 20;\n List<EntityCreeper> creepers = player.worldObj.getEntitiesWithinAABB(\n EntityCreeper.class,\n AxisAlignedBB.getBoundingBox(player.posX, player.posY, player.posZ,\n player.posX + 1.0D, player.posY + 1.0D,\n player.posZ + 1.0D).expand(16.0D, 4.0D, 16.0D));\n\n for (EntityCreeper creeper : creepers)\n {\n boolean set = true;\n EntityAIAvoidPlayerWithBackpack task = new EntityAIAvoidPlayerWithBackpack(creeper, EntityPlayer.class, 10.0F, 1.0, 1.3, \"Ocelot\");\n\n for (Object entry : creeper.tasks.taskEntries)\n {\n if (((EntityAITasks.EntityAITaskEntry) entry).action instanceof EntityAIAvoidPlayerWithBackpack)\n {\n set = false;\n break;\n }\n }\n\n if (set)\n {\n //System.out.println(\"Found creeper who doesn't know to fear the backpack, making it a pussy now\");\n creeper.tasks.addTask(3, task);\n }\n }\n }\n inv.setLastTime(lastCheckTime);\n inv.markDirty();\n }\n\n\n public void itemRainbow(EntityPlayer player, World world, ItemStack backpack)\n {\n InventoryBackpack inv = new InventoryBackpack(backpack);\n int noteTime = inv.getLastTime() - 1;\n if (noteTime >= 0 && noteTime < Utils.secondsToTicks(147))\n {\n player.setSprinting(true);\n player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 40, 2));\n player.addPotionEffect(new PotionEffect(Potion.jump.getId(), 40, 2));\n if (noteTime % 2 == 0)\n {\n //Visuals.NyanParticles(player, world);\n if (!world.isRemote)\n {\n ModNetwork.sendToNearby(new EntityParticlePacket.Message(EntityParticlePacket.NYAN_PARTICLE, player), player);\n }\n }\n }\n PotionEffect potion = null;\n if (player.isPotionActive(Potion.moveSpeed.id)) {\n potion = player.getActivePotionEffect(Potion.moveSpeed);\n }\n if (potion == null || potion.getDuration() < 40 && potion.getAmplifier() != -5) {\n player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 5000, -5));\n }\n inv.setLastTime(noteTime);\n inv.markDirty();\n }\n /* ==================================== TILE ABILITIES ==========================================*/\n\n private void fillWithRain(World world, TileAdventureBackpack backpack, FluidStack fluid, int time)\n {\n if (world.isRaining() && world.canBlockSeeTheSky(backpack.xCoord, backpack.yCoord, backpack.zCoord))\n {\n int dropTime = backpack.getLastTime() - 1;\n if (dropTime <= 0)\n {\n backpack.getRightTank().fill(fluid, true);\n backpack.getLeftTank().fill(fluid, true);\n dropTime = time;\n backpack.markDirty();\n }\n backpack.setLastTime(dropTime);\n }\n }\n\n /**\n * Like real life cactii, this backpack will fill slowly while it's raining with refreshing water.\n *\n * @param world\n * @param backpack\n */\n public void tileCactus(World world, TileAdventureBackpack backpack)\n {\n fillWithRain(world, backpack, new FluidStack(FluidRegistry.WATER, 2), 5);\n }\n\n\n public void tileMelon(World world, TileAdventureBackpack backpack)\n {\n fillWithRain(world, backpack, new FluidStack(ModFluids.melonJuice, 2), 5);\n }\n\n}", "public class ConfigHandler\n{\n\n\n public static Configuration config;\n\n public static boolean IS_BUILDCRAFT = false;\n public static boolean IS_BAUBLES = false;\n public static boolean IS_TINKERS = false;\n public static boolean IS_THAUM = false;\n public static boolean IS_TWILIGHT = false;\n public static boolean IS_ENVIROMINE = false;\n public static boolean IS_RAILCRAFT = false;\n\n public static int GUI_TANK_RENDER = 2;\n public static boolean BONUS_CHEST_ALLOWED = false;\n public static boolean PIGMAN_ALLOWED = false;\n\n public static boolean BACKPACK_DEATH_PLACE = true;\n public static boolean BACKPACK_ABILITIES = true;\n\n public static boolean ALLOW_COPTER_SOUND = true;\n public static boolean ALLOW_JETPACK_SOUNDS = true;\n\n\n public static boolean STATUS_OVERLAY = true;\n public static boolean TANKS_OVERLAY = true;\n public static boolean HOVERING_TEXT_TANKS = false;\n public static boolean SADDLE_RECIPE = true;\n public static boolean FIX_LEAD = true;\n\n\n public static void init(File configFile)\n {\n if (config == null)\n {\n config = new Configuration(configFile);\n loadConfiguration();\n }\n }\n\n\n private static void loadConfiguration()\n {\n GUI_TANK_RENDER = config.getInt(\"TankRenderType\", config.CATEGORY_GENERAL, 3, 1, 3, \"1,2 or 3 for different rendering of fluids in the Backpack GUI\");\n BONUS_CHEST_ALLOWED = config.getBoolean(\"BonusBackpack\", config.CATEGORY_GENERAL, false, \"Include a Standard Adventure Backpack in bonus chest?\");\n PIGMAN_ALLOWED = config.getBoolean(\"PigmanBackpacks\", config.CATEGORY_GENERAL, false, \"Allow generation of Pigman Backpacks in dungeon loot and villager trades\");\n ALLOW_COPTER_SOUND = config.getBoolean(\"CopterPackSound\", config.CATEGORY_GENERAL, true, \"Allow playing the CopterPack sound (Client Only, other players may hear it)\");\n BACKPACK_ABILITIES = config.getBoolean(\"BackpackAbilities\", config.CATEGORY_GENERAL, true, \"Allow the backpacks to execute their special abilities, or be only cosmetic (Doesn't affect lightning transformation) Must be \" +\n \"disabled in both Client and Server to work properly\");\n STATUS_OVERLAY = config.getBoolean(\"StatusOverlay\", config.CATEGORY_GENERAL,true, \"Show player status effects on screen?\");\n TANKS_OVERLAY = config.getBoolean(\"BackpackOverlay\", config.CATEGORY_GENERAL,true, \"Show the different wearable overlays on screen?\");\n HOVERING_TEXT_TANKS = config.getBoolean(\"HoveringText\", config.CATEGORY_GENERAL,false, \"Show hovering text on fluid tanks?\");\n FIX_LEAD = config.getBoolean(\"FixVanillaLead\", config.CATEGORY_GENERAL,true, \"Fix the vanilla Lead? (Checks mobs falling on a leash to not die of fall damage if they're not falling so fast)\");\n BACKPACK_DEATH_PLACE = config.getBoolean(\"BackpackDeathPlace\", config.CATEGORY_GENERAL,true,\"Place backpacks as a block when you die?\");\n //RECIPES\n SADDLE_RECIPE = config.getBoolean(\"SaddleRecipe\", config.CATEGORY_GENERAL,true, \"Add recipe for saddle?\");\n if (config.hasChanged())\n {\n config.save();\n }\n }\n\n @SubscribeEvent\n public void onConfigChangeEvent(ConfigChangedEvent.OnConfigChangedEvent event)\n {\n if (event.modID.equalsIgnoreCase(ModInfo.MOD_ID))\n {\n loadConfiguration();\n }\n }\n\n\n}", "public class BackpackProperty implements IExtendedEntityProperties\n{\n\n public static final String PROPERTY_NAME = \"abp.property\";\n protected EntityPlayer player = null;\n private ItemStack wearable = null;\n private ChunkCoordinates campFire = null;\n private NBTTagCompound wearableData = new NBTTagCompound();\n private boolean forceCampFire = false;\n private int dimension = 0;\n\n public NBTTagCompound getWearableData()\n {\n return wearableData;\n }\n\n\n public static void sync(EntityPlayer player)\n {\n if(player instanceof EntityPlayerMP)\n {\n syncToNear(player);\n }\n }\n\n public static void syncToNear(EntityPlayer player)\n {\n //Thanks diesieben07!!!\n if(player != null && player instanceof EntityPlayerMP)\n {\n try\n {\n ((EntityPlayerMP) player)\n .getServerForPlayer()\n .getEntityTracker()\n .func_151248_b(player, ModNetwork.net.getPacketFrom(new SyncPropertiesPacket.Message(player.getEntityId(), get(player).getData())));\n }catch(Exception ex){\n ex.printStackTrace();\n }\n }\n }\n\n public BackpackProperty(EntityPlayer player)\n {\n this.player = player;\n }\n\n public NBTTagCompound getData()\n {\n NBTTagCompound data = new NBTTagCompound();\n saveNBTData(data);\n\n return data;\n }\n\n public static void register(EntityPlayer player)\n {\n player.registerExtendedProperties(PROPERTY_NAME, new BackpackProperty(player));\n }\n\n public static BackpackProperty get(EntityPlayer player)\n {\n return (BackpackProperty) player.getExtendedProperties(PROPERTY_NAME);\n }\n\n /**\n * Called when the entity that this class is attached to is saved.\n * Any custom entity data that needs saving should be saved here.\n *\n * @param compound The compound to save to.\n */\n @Override\n public void saveNBTData(NBTTagCompound compound)\n {\n if(wearable != null) compound.setTag(\"wearable\", wearable.writeToNBT(new NBTTagCompound()));\n if (campFire != null)\n {\n compound.setInteger(\"campFireX\", campFire.posX);\n compound.setInteger(\"campFireY\", campFire.posY);\n compound.setInteger(\"campFireZ\", campFire.posZ);\n compound.setInteger(\"campFireDim\", dimension);\n\n }\n compound.setBoolean(\"forceCampFire\",forceCampFire);\n }\n\n /**\n * Called when the entity that this class is attached to is loaded.\n * In order to hook into this, you will need to subscribe to the EntityConstructing event.\n * Otherwise, you will need to initialize manually.\n *\n * @param compound The compound to load from.\n */\n @Override\n public void loadNBTData(NBTTagCompound compound)\n {\n if(compound!=null)\n {\n setWearable( compound.hasKey(\"wearable\") ? ItemStack.loadItemStackFromNBT(compound.getCompoundTag(\"wearable\")) : null);\n setCampFire( new ChunkCoordinates(compound.getInteger(\"campFireX\"), compound.getInteger(\"campFireY\"), compound.getInteger(\"campFireZ\")));\n dimension = compound.getInteger(\"compFireDim\");\n forceCampFire = compound.getBoolean(\"forceCampfire\");\n }\n }\n\n /**\n * Used to initialize the extended properties with the entity that this is attached to, as well\n * as the world object.\n * Called automatically if you register with the EntityConstructing event.\n * May be called multiple times if the extended properties is moved over to a new entity.\n * Such as when a player switches dimension {Minecraft re-creates the player entity}\n *\n * @param entity The entity that this extended properties is attached to\n * @param world The world in which the entity exists\n */\n @Override\n public void init(Entity entity, World world)\n {\n this.player = (EntityPlayer)entity;\n }\n\n public void setWearable(ItemStack bp)\n {\n wearable = bp;\n }\n\n\n public ItemStack getWearable()\n {\n return wearable != null ? wearable : null ;\n }\n\n public void setCampFire(ChunkCoordinates cf)\n {\n campFire = cf;\n }\n\n public boolean hasWearable()\n {\n return wearable != null;\n }\n\n public ChunkCoordinates getCampFire()\n {\n return campFire;\n }\n\n public EntityPlayer getPlayer()\n {\n return player;\n }\n\n public void setDimension(int dimension)\n {\n this.dimension = dimension;\n }\n\n public int getDimension()\n {\n return dimension;\n }\n\n public boolean isForcedCampFire()\n {\n return forceCampFire;\n }\n\n public void setForceCampFire(boolean forceCampFire)\n {\n this.forceCampFire = forceCampFire;\n }\n\n //Scary names for methods because why not\n public void executeWearableUpdateProtocol()\n {\n if(Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class))\n {\n ((IBackWearableItem)wearable.getItem()).onEquippedUpdate(player.getEntityWorld(), player, wearable);\n }\n }\n\n public void executeWearableDeathProtocol()\n {\n if (Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class))\n {\n ((IBackWearableItem) wearable.getItem()).onPlayerDeath(player.getEntityWorld(), player, wearable);\n }\n }\n\n public void executeWearableEquipProtocol()\n {\n if (Utils.notNullAndInstanceOf(wearable.getItem(), IBackWearableItem.class))\n {\n ((IBackWearableItem) wearable.getItem()).onEquipped(player.getEntityWorld(), player, wearable);\n }\n }\n\n public void executeWearableUnequipProtocol()\n {\n if (Utils.notNullAndInstanceOf(wearable.getItem() , IBackWearableItem.class))\n {\n ((IBackWearableItem) wearable.getItem()).onUnequipped(player.getEntityWorld(), player, wearable);\n }\n }\n}", "public class ClientProxy implements IProxy\n{\n\n public static RendererItemAdventureBackpack rendererItemAdventureBackpack;\n public static RendererItemAdventureHat rendererItemAdventureHat;\n public static RendererHose rendererHose;\n public static RendererWearableEquipped rendererWearableEquipped;\n public static RenderHandler renderHandler;\n public static RendererInflatableBoat renderInflatableBoat;\n public static RenderRideableSpider renderRideableSpider;\n public static RendererItemClockworkCrossbow renderCrossbow;\n public static ModelSteamJetpack modelSteamJetpack = new ModelSteamJetpack();\n public static ModelBackpackArmor modelAdventureBackpack = new ModelBackpackArmor();\n public static ModelCopterPack modelCopterPack = new ModelCopterPack();\n\n\n public void init()\n {\n initRenderers();\n registerKeybindings();\n MinecraftForge.EVENT_BUS.register(new GuiOverlay(Minecraft.getMinecraft()));\n }\n\n public void initNetwork()\n {\n\n }\n\n @Override\n public void joinPlayer(EntityPlayer player)\n {\n LogHelper.info(\"Joined Player in client\");\n }\n\n @Override\n public void synchronizePlayer(int id, NBTTagCompound properties)\n {\n Entity entity = Minecraft.getMinecraft().theWorld.getEntityByID(id);\n if(Utils.notNullAndInstanceOf(entity, EntityPlayer.class)&& properties != null)\n {\n EntityPlayer player = (EntityPlayer)entity;\n if(BackpackProperty.get(player) == null) BackpackProperty.register(player);\n BackpackProperty.get(player).loadNBTData(properties);\n }\n }\n\n public void initRenderers()\n {\n renderHandler = new RenderHandler();\n MinecraftForge.EVENT_BUS.register(renderHandler);\n rendererWearableEquipped = new RendererWearableEquipped();\n\n rendererItemAdventureBackpack = new RendererItemAdventureBackpack();\n MinecraftForgeClient.registerItemRenderer(ModItems.adventureBackpack, rendererItemAdventureBackpack);\n MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(ModBlocks.blockBackpack), rendererItemAdventureBackpack);\n ClientRegistry.bindTileEntitySpecialRenderer(TileAdventureBackpack.class, new RendererAdventureBackpackBlock());\n\n rendererItemAdventureHat = new RendererItemAdventureHat();\n MinecraftForgeClient.registerItemRenderer(ModItems.adventureHat, rendererItemAdventureHat);\n\n if(!ConfigHandler.TANKS_OVERLAY)\n {\n rendererHose = new RendererHose();\n MinecraftForgeClient.registerItemRenderer(ModItems.hose, rendererHose);\n }\n\n ClientRegistry.bindTileEntitySpecialRenderer(TileCampfire.class, new RendererCampFire());\n\n renderInflatableBoat = new RendererInflatableBoat();\n RenderingRegistry.registerEntityRenderingHandler(EntityInflatableBoat.class, renderInflatableBoat);\n renderRideableSpider = new RenderRideableSpider();\n RenderingRegistry.registerEntityRenderingHandler(EntityFriendlySpider.class, renderRideableSpider);\n\n renderCrossbow = new RendererItemClockworkCrossbow();\n MinecraftForgeClient.registerItemRenderer(ModItems.cwxbow, renderCrossbow);\n }\n\n public void registerKeybindings()\n {\n ClientRegistry.registerKeyBinding(Keybindings.openBackpack);\n ClientRegistry.registerKeyBinding(Keybindings.toggleHose);\n FMLCommonHandler.instance().bus().register(new KeybindHandler());\n }\n\n}", "public class BackpackNames\n{\n\n public static String[] backpackNames = {\n \"Standard\",\n \"Cow\",\n \"Bat\",\n \"Black\",\n \"Blaze\",\n \"Carrot\",\n \"Coal\",\n \"Diamond\",\n \"Emerald\",\n \"Gold\",\n \"Iron\",\n \"IronGolem\",\n \"Lapis\",\n \"Redstone\",\n \"Blue\",\n \"Bookshelf\",\n \"Brown\",\n \"Cactus\",\n \"Cake\",\n \"Chest\",\n \"Cookie\",\n \"Cyan\",\n \"Dragon\",\n \"Egg\",\n \"Electric\",\n \"Deluxe\",\n \"Enderman\",\n \"End\",\n \"Chicken\",\n \"Ocelot\",\n \"Ghast\",\n \"Gray\",\n \"Green\",\n \"Haybale\",\n \"Horse\",\n \"Leather\",\n \"LightBlue\",\n \"Glowstone\",\n \"LightGray\",\n \"Lime\",\n \"Magenta\",\n \"MagmaCube\",\n \"Melon\",\n \"BrownMushroom\",\n \"RedMushroom\",\n \"Mooshroom\",\n \"Nether\",\n \"Wither\",\n \"Obsidian\",\n \"Orange\",\n \"Overworld\",\n \"Pigman\",\n \"Pink\",\n \"Pig\",\n \"Pumpkin\",\n \"Purple\",\n \"Quartz\",\n \"Rainbow\",\n \"Red\",\n \"Sandstone\",\n \"Sheep\",\n \"Silverfish\",\n \"Squid\",\n \"Sunflower\",\n \"Creeper\",\n \"Skeleton\",\n \"WitherSkeleton\",\n \"Slime\",\n \"Snow\",\n \"Spider\",\n \"Sponge\",\n \"Villager\",\n \"White\",\n \"Wolf\",\n \"Yellow\",\n \"Zombie\"\n };\n\n public static ItemStack setBackpackColorNameFromDamage(ItemStack backpack, int damage)\n {\n\n if (backpack == null) return null;\n if (!(backpack.getItem() instanceof ItemAdventureBackpack)) return null;\n NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ;\n backpack.setItemDamage(damage);\n assert backpackData != null;\n backpackData.setString(\"colorName\", backpackNames[damage]);\n BackpackUtils.setBackpackData(backpack,backpackData);\n return backpack;\n }\n\n public static int getBackpackDamageFromName(String name)\n {\n for (int i = 0; i < backpackNames.length; i++)\n {\n if (backpackNames[i].equals(name)) return i;\n }\n return 0;\n }\n\n public static String getBackpackColorName(TileAdventureBackpack te)\n {\n return te.getColorName();\n }\n\n public static String getBackpackColorName(ItemStack backpack)\n {\n if (backpack == null) return \"\";\n NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ;\n assert backpackData != null;\n if (backpackData.getString(\"colorName\").isEmpty())\n {\n backpackData.setString(\"colorName\", \"Standard\");\n }\n return backpackData.getString(\"colorName\");\n }\n\n public static void setBackpackColorName(ItemStack backpack, String newName)\n {\n if (backpack != null)\n {\n NBTTagCompound backpackData = BackpackUtils.getBackpackData(backpack) != null ? BackpackUtils.getBackpackData(backpack) : new NBTTagCompound() ;\n assert backpackData != null;\n backpackData.setString(\"colorName\", newName);\n BackpackUtils.setBackpackData(backpack, backpackData);\n }\n }\n}", "public class BackpackUtils\n{\n\n public enum reasons{\n SUCCESFUL,ALREADY_EQUIPPED\n }\n public static reasons equipWearable(ItemStack backpack, EntityPlayer player)\n {\n BackpackProperty prop = BackpackProperty.get(player);\n if(prop.getWearable() == null)\n {\n player.openContainer.onContainerClosed(player);\n prop.setWearable(backpack.copy());\n BackpackProperty.get(player).executeWearableEquipProtocol();\n backpack.stackSize--;\n WearableEvent event = new WearableEvent.EquipWearableEvent(player, prop.getWearable());\n MinecraftForge.EVENT_BUS.post(event);\n BackpackProperty.sync(player);\n return reasons.SUCCESFUL;\n }else\n {\n return reasons.ALREADY_EQUIPPED;\n }\n }\n\n public static void unequipWearable(EntityPlayer player)\n {\n BackpackProperty prop = BackpackProperty.get(player);\n if(prop.getWearable() != null)\n {\n player.openContainer.onContainerClosed(player);\n ItemStack gimme = prop.getWearable().copy();\n BackpackProperty.get(player).executeWearableUnequipProtocol();\n prop.setWearable(null);\n if(!player.inventory.addItemStackToInventory(gimme))\n {\n player.dropPlayerItemWithRandomChoice(gimme,false);\n }\n WearableEvent event = new WearableEvent.UnequipWearableEvent(player, gimme);\n MinecraftForge.EVENT_BUS.post(event);\n BackpackProperty.sync(player);\n }else\n {\n player.addChatComponentMessage(new ChatComponentTranslation(\"adventurebackpack:messages.already.impossibru\"));\n }\n }\n\n public static NBTTagCompound getBackpackData(ItemStack backpack)\n {\n if(backpack.hasTagCompound() && backpack.stackTagCompound.hasKey(\"backpackData\"))\n {\n return backpack.stackTagCompound.getCompoundTag(\"backpackData\");\n }\n return null;\n }\n\n public static void setBackpackData(ItemStack stack, NBTTagCompound compound)\n {\n if(!stack.hasTagCompound())stack.stackTagCompound = new NBTTagCompound();\n stack.stackTagCompound.setTag(\"backpackData\",compound);\n }\n\n}", "public class Utils\n{\n\n public static float degreesToRadians(float degrees)\n {\n return degrees / 57.2957795f;\n }\n\n public static float radiansToDegrees(float radians)\n {\n return radians * 57.2957795f;\n }\n\n public static int[] calculateEaster(int year)\n {\n\n\n int a = year % 19,\n b = year / 100,\n c = year % 100,\n d = b / 4,\n e = b % 4,\n g = (8 * b + 13) / 25,\n h = (19 * a + b - d - g + 15) % 30,\n j = c / 4,\n k = c % 4,\n m = (a + 11 * h) / 319,\n r = (2 * e + 2 * j - k - h + m + 32) % 7,\n n = (h - m + r + 90) / 25,\n p = (h - m + r + n + 19) % 32;\n\n return new int[]{n, p};\n }\n\n public static String getHoliday()\n {\n\n Calendar calendar = Calendar.getInstance();\n int year = calendar.get(Calendar.YEAR),\n month = calendar.get(Calendar.MONTH) + 1,\n day = calendar.get(Calendar.DAY_OF_MONTH);\n\n if (AdventureBackpack.instance.chineseNewYear) return \"ChinaNewYear\";\n if (AdventureBackpack.instance.hannukah) return \"Hannukah\";\n if (month == Utils.calculateEaster(year)[0] && day == Utils.calculateEaster(year)[1]) return \"Easter\";\n String dia = \"Standard\";\n if (month == 1)\n {\n if (day == 1) dia = \"NewYear\";\n if (day == 28) dia = \"Shuttle\";//Challenger\n }\n if (month == 2)\n {\n if (day == 1) dia = \"Shuttle\";//Columbia\n if (day == 14) dia = \"Valentines\";\n if (day == 23) dia = \"Fatherland\";\n }\n if (month == 3)\n {\n if (day == 17) dia = \"Patrick\";\n }\n if (month == 4)\n {\n if (day == 1) dia = \"Fools\";\n if (day == 25) dia = \"Italy\";\n }\n if (month == 5)\n {\n if (day == 8 || day == 9 || day == 10) dia = \"Liberation\";\n }\n if (month == 6)\n {\n }\n if (month == 7)\n {\n if (day == 4) dia = \"USA\";\n if (day == 24) dia = \"Bolivar\";\n if (day == 14) dia = \"Bastille\";\n }\n if (month == 8)\n {\n }\n if (month == 9)\n {\n if (day == 19) dia = \"Pirate\";\n }\n if (month == 10)\n {\n if (day == 3) dia = \"Germany\";\n if (day == 12) dia = \"Columbus\";\n if (day == 31) dia = \"Halloween\";\n }\n if (month == 11)\n {\n if (day == 2) dia = \"Muertos\";\n }\n if (month == 12)\n {\n if (day >= 22 && day <= 26) dia = \"Christmas\";\n if (day == 31) dia = \"NewYear\";\n }\n //LogHelper.info(\"Today is: \" + day + \"/\" + month + \"/\" + year + \". Which means today is: \" + dia);\n return dia;\n\n }\n\n public static int isBlockRegisteredAsFluid(Block block)\n {\n /*\n * for (Map.Entry<String,Fluid> fluid :\n\t\t * getRegisteredFluids().entrySet()) { int ID =\n\t\t * (fluid.getValue().getBlockID() == BlockID) ? fluid.getValue().getID()\n\t\t * : -1; if (ID > 0) return ID; }\n\t\t */\n int fluidID = -1;\n for (Fluid fluid : FluidRegistry.getRegisteredFluids().values())\n {\n fluidID = (fluid.getBlock() == block) ? fluid.getID() : -1;\n if (fluidID > 0)\n {\n return fluidID;\n }\n }\n return fluidID;\n }\n\n public static boolean shouldGiveEmpty(ItemStack cont)\n {\n boolean valid = true;\n // System.out.println(\"Item class name is: \"+cont.getItem().getClass().getName());\n\n try\n {\n // Industrialcraft cells\n // if (apis.ic2.api.item.Items.getItem(\"cell\").getClass().isInstance(cont.getItem()))\n // {\n // valid = false;\n // }\n // Forestry capsules\n if (java.lang.Class.forName(\"forestry.core.items.ItemLiquidContainer\").isInstance(cont.getItem()))\n {\n valid = false;\n }\n } catch (Exception oops)\n {\n\n }\n // Others\n\n return valid;\n }\n\n public static ChunkCoordinates findBlock2D(World world, int x, int y, int z, Block block, int range)\n {\n for (int i = x - range; i <= x + range; i++)\n {\n for (int j = z - range; j <= z + range; j++)\n {\n if (world.getBlock(i, y, j) == block)\n {\n return new ChunkCoordinates(i, y, j);\n }\n }\n }\n return null;\n }\n\n public static ChunkCoordinates findBlock3D(World world, int x, int y, int z, Block block, int hRange, int vRange)\n {\n for (int i = (y - vRange); i <= (y + vRange); i++)\n {\n for (int j = (x - hRange); j <= (x + hRange); j++)\n {\n for (int k = (z - hRange); k <= (z + hRange); k++)\n {\n if (world.getBlock(j, i, k) == block)\n {\n return new ChunkCoordinates(j, i, k);\n }\n }\n }\n }\n return null;\n }\n\n public static String capitalize(String s)\n {\n // Character.toUpperCase(itemName.charAt(0)) + itemName.substring(1);\n return s.substring(0, 1).toUpperCase().concat(s.substring(1));\n }\n\n public static int getOppositeCardinalFromMeta(int meta)\n {\n return (meta % 2 == 0) ? (meta == 0) ? 2 : 0 : ((meta + 1) % 4) + 1;\n }\n\n //This is some black magic that returns a block or entity as far as the argument reach goes.\n public static MovingObjectPosition getMovingObjectPositionFromPlayersHat(World world, EntityPlayer player, boolean flag, double reach)\n {\n float f = 1.0F;\n float playerPitch = player.prevRotationPitch\n + (player.rotationPitch - player.prevRotationPitch) * f;\n float playerYaw = player.prevRotationYaw\n + (player.rotationYaw - player.prevRotationYaw) * f;\n double playerPosX = player.prevPosX + (player.posX - player.prevPosX)\n * f;\n double playerPosY = (player.prevPosY + (player.posY - player.prevPosY)\n * f + 1.6200000000000001D)\n - player.yOffset;\n double playerPosZ = player.prevPosZ + (player.posZ - player.prevPosZ)\n * f;\n Vec3 vecPlayer = Vec3.createVectorHelper(playerPosX, playerPosY,\n playerPosZ);\n float cosYaw = (float) Math.cos(-playerYaw * 0.01745329F - 3.141593F);\n float sinYaw = (float) Math.sin(-playerYaw * 0.01745329F - 3.141593F);\n float cosPitch = (float) -Math.cos(-playerPitch * 0.01745329F);\n float sinPitch = (float) Math.sin(-playerPitch * 0.01745329F);\n float pointX = sinYaw * cosPitch;\n float pointY = sinPitch;\n float pointZ = cosYaw * cosPitch;\n Vec3 vecPoint = vecPlayer.addVector(pointX * reach, pointY * reach,\n pointZ * reach);\n return world.func_147447_a/*rayTraceBlocks_do_do*/(\n vecPlayer, vecPoint, flag, !flag, flag);\n }\n\n public static String printCoordinates(int x, int y, int z)\n {\n return \"X= \" + x + \", Y= \" + y + \", Z= \" + z;\n }\n\n\n public static int secondsToTicks(int seconds)\n {\n return seconds * 20;\n }\n\n public static int secondsToTicks(float seconds)\n {\n return (int) seconds * 20;\n }\n\n public static boolean inServer()\n {\n Side side = FMLCommonHandler.instance().getEffectiveSide();\n return side == Side.SERVER;\n }\n\n private static ChunkCoordinates checkCoordsForBackpack(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, boolean except)\n {\n //LogHelper.info(\"Checking coordinates in X=\"+X+\", Y=\"+Y+\", Z=\"+Z);\n if (except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z) && !areCoordinatesTheSame(origX, Y, origZ, X, Y, Z))\n {\n //LogHelper.info(\"Found spot with the exception of the death point\");\n return new ChunkCoordinates(X, Y, Z);\n }\n if (!except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z))\n {\n //LogHelper.info(\"Found spot without exceptions\");\n return new ChunkCoordinates(X, Y, Z);\n }\n return null;\n }\n\n private static ChunkCoordinates checkCoordsForPlayer(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, boolean except)\n {\n LogHelper.info(\"Checking coordinates in X=\"+X+\", Y=\"+Y+\", Z=\"+Z);\n if (except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z) && world.isAirBlock(X,Y+1,Z) && !areCoordinatesTheSame2D(origX, origZ, X, Z))\n {\n LogHelper.info(\"Found spot with the exception of the origin point\");\n return new ChunkCoordinates(X, Y, Z);\n }\n if (!except && world.isSideSolid(X, Y - 1, Z, ForgeDirection.UP,true) && world.isAirBlock(X, Y, Z)&& world.isAirBlock(X,Y+1,Z))\n {\n LogHelper.info(\"Found spot without exceptions\");\n return new ChunkCoordinates(X, Y, Z);\n }\n return null;\n }\n\n /**\n * Gets you the nearest Empty Chunk Coordinates, free of charge! Looks in two dimensions and finds a block\n * that a: can have stuff placed on it and b: has space above it.\n * This is a spiral search, will begin at close range and move out.\n * @param world The world object.\n * @param origX Original X coordinate\n * @param origZ Original Z coordinate\n * @param X Moving X coordinate, should be the same as origX when called.\n * @param Y Y coordinate, does not move.\n * @param Z Moving Z coordinate, should be the same as origZ when called.\n * @param radius The radius of the search. If set to high numbers, will create a ton of lag\n * @param except Wether to include the origin of the search as a valid block.\n * @param steps Number of steps of the recursive recursiveness that recurses through the recursion. It is the first size of the spiral, should be one (1) always at the first call.\n * @param pass Pass switch for the witchcraft I can't quite explain. Set to 0 always at the beggining.\n * @param type True = for player, False = for backpack\n * @return The coordinates of the block in the chunk of the world of the game of the server of the owner of the computer, where you can place something above it.\n */\n public static ChunkCoordinates getNearestEmptyChunkCoordinatesSpiral(IBlockAccess world, int origX, int origZ, int X, int Y, int Z, int radius, boolean except, int steps, byte pass, boolean type)\n {\n //Spiral search, because I'm awesome :)\n //This is so the backpack tries to get placed near the death point first\n //And then goes looking farther away at each step\n //Steps mod 2 == 0 => X++, Z--\n //Steps mod 2 == 1 => X--, Z++\n\n //\n if (steps >= radius) return null;\n int i = X, j = Z;\n if (steps % 2 == 0)\n {\n if (pass == 0)\n {\n for (; i <= X + steps; i++)\n {\n\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n if (pass == 1)\n {\n for (; j >= Z - steps; j--)\n {\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass--;\n steps++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n }\n\n if (steps % 2 == 1)\n {\n if (pass == 0)\n {\n for (; i >= X - steps; i--)\n {\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n if (pass == 1)\n {\n for (; j <= Z + steps; j++)\n {\n ChunkCoordinates coords = type ? checkCoordsForPlayer(world, origX, origZ, X, Y, Z, except) : checkCoordsForBackpack(world, origX, origZ, X, Y, Z, except);\n if (coords != null)\n {\n return coords;\n }\n }\n pass--;\n steps++;\n return getNearestEmptyChunkCoordinatesSpiral(world, origX, origZ, i, Y, j, radius, except, steps, pass, type);\n }\n }\n\n /* Old code. Still works, though.\n for (int i = x - radius; i <= x + radius; i++)\n {\n for (int j = y - (radius / 2); j <= y + (radius / 2); j++)\n {\n for (int k = z + radius; k <= z + (radius); k++)\n {\n if (except && world.isSideSolid(i, j - 1, k, ForgeDirection.UP) && world.isAirBlock(i, j, k) && !areCoordinatesTheSame(x, y, z, i, j, k))\n {\n return new ChunkCoordinates(i, j, k);\n }\n if (!except && world.isSideSolid(i, j - 1, k, ForgeDirection.UP) && world.isAirBlock(i, j, k))\n {\n return new ChunkCoordinates(i, j, k);\n }\n }\n }\n }*/\n return null;\n }\n\n /**\n * Compares two coordinates. Heh.\n *\n * @param X1 First coordinate X.\n * @param Y1 First coordinate Y.\n * @param Z1 First coordinate Z.\n * @param X2 Second coordinate X.\n * @param Y2 Second coordinate Y.\n * @param Z2 Second coordinate Z. I really didn't need to type all that, its obvious.\n * @return If both coordinates are the same, returns true. This is the least helpful javadoc ever.\n */\n private static boolean areCoordinatesTheSame(int X1, int Y1, int Z1, int X2, int Y2, int Z2)\n {\n return (X1 == X2 && Y1 == Y2 && Z1 == Z2);\n }\n\n private static boolean areCoordinatesTheSame2D(int X1, int Z1, int X2, int Z2)\n {\n return (X1 == X2 && Z1 == Z2);\n }\n\n /**\n * Seriously why doesn't Java's instanceof check for null?\n * @return true if the object is not null and is an instance of the supplied class.\n */\n public static boolean notNullAndInstanceOf(Object object, Class clazz)\n {\n return object != null && clazz.isInstance(object);\n }\n\n public static String getFirstWord(String text)\n {\n if (text.indexOf(' ') > -1)\n { // Check if there is more than one word.\n String firstWord = text.substring(0, text.indexOf(' '));\n String secondWord = text.substring(text.indexOf(' ') + 1);\n return firstWord.equals(\"Molten\") ? secondWord : firstWord;// Extract first word.\n } else\n {\n return text; // Text is the first word itself.\n }\n }\n}" ]
import com.darkona.adventurebackpack.AdventureBackpack; import com.darkona.adventurebackpack.block.BlockAdventureBackpack; import com.darkona.adventurebackpack.block.TileAdventureBackpack; import com.darkona.adventurebackpack.client.models.ModelBackpackArmor; import com.darkona.adventurebackpack.common.BackpackAbilities; import com.darkona.adventurebackpack.config.ConfigHandler; import com.darkona.adventurebackpack.events.WearableEvent; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.init.ModItems; import com.darkona.adventurebackpack.init.ModNetwork; import com.darkona.adventurebackpack.network.GUIPacket; import com.darkona.adventurebackpack.playerProperties.BackpackProperty; import com.darkona.adventurebackpack.proxy.ClientProxy; import com.darkona.adventurebackpack.reference.BackpackNames; import com.darkona.adventurebackpack.util.BackpackUtils; import com.darkona.adventurebackpack.util.Resources; import com.darkona.adventurebackpack.util.Utils; import com.darkona.adventurebackpack.util.Wearing; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.client.model.ModelBiped; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; import java.util.List;
super.onCreated(stack, par2World, par3EntityPlayer); BackpackNames.setBackpackColorNameFromDamage(stack, stack.getItemDamage()); } public boolean placeBackpack(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, boolean from) { if (!stack.hasTagCompound()) stack.setTagCompound(new NBTTagCompound()); if (!player.canPlayerEdit(x, y, z, side, stack)) return false; if (!stack.stackTagCompound.hasKey("colorName") || stack.stackTagCompound.getString("colorName").isEmpty()) { stack.stackTagCompound.setString("colorName", "Standard"); } // world.spawnEntityInWorld(new EntityLightningBolt(world, x, y, z)); BlockAdventureBackpack backpack = ModBlocks.blockBackpack; if (y <= 0 || y >= world.getHeight()) { return false; } if (backpack.canPlaceBlockOnSide(world, x, y, z, side)) { if (world.getBlock(x, y, z).getMaterial().isSolid()) { switch (side) { case 0: --y; break; case 1: ++y; break; case 2: --z; break; case 3: ++z; break; case 4: --x; break; case 5: ++x; break; } } if (y <= 0 || y >= world.getHeight()) { return false; } if (backpack.canPlaceBlockAt(world, x, y, z)) { if (world.setBlock(x, y, z, ModBlocks.blockBackpack)) { backpack.onBlockPlacedBy(world, x, y, z, player, stack); world.playSoundAtEntity(player, BlockAdventureBackpack.soundTypeCloth.getStepResourcePath(), 0.5f, 1.0f); ((TileAdventureBackpack) world.getTileEntity(x, y, z)).loadFromNBT(stack.stackTagCompound); if (from) { player.inventory.decrStackSize(player.inventory.currentItem, 1); } else { BackpackProperty.get(player).setWearable(null); } WearableEvent event = new WearableEvent(player, stack); MinecraftForge.EVENT_BUS.post(event); return true; } } } return false; } @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { return player.canPlayerEdit(x, y, z, side, stack) && placeBackpack(stack, player, world, x, y, z, side, true); } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { MovingObjectPosition mop = getMovingObjectPositionFromPlayer(world, player, true); if (mop == null || mop.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) { if (world.isRemote) { ModNetwork.net.sendToServer(new GUIPacket.GUImessage(GUIPacket.BACKPACK_GUI, GUIPacket.FROM_HOLDING)); } } return stack; } @Override public boolean isDamageable() { return false; } @Override public boolean onDroppedByPlayer(ItemStack stack, EntityPlayer player) { return true; } @SideOnly(Side.CLIENT) @Override public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack stack, int armorSlot) { return new ModelBackpackArmor(); } @SideOnly(Side.CLIENT) @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { String modelTexture; if (BackpackNames.getBackpackColorName(stack).equals("Standard")) {
modelTexture = Resources.backpackTextureFromString(AdventureBackpack.instance.Holiday).toString();
0
cdelmas/microservices-comparison
vertx/src/main/java/io/github/cdelmas/spike/vertx/Main.java
[ "public class Car {\n\n private Integer id;\n private String name;\n\n public Car(String name) {\n this.name = name;\n }\n\n Car() {\n\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getId() {\n return id;\n }\n\n public String getName() {\n return name;\n }\n}", "public interface CarRepository {\n\n Optional<Car> byId(int id);\n\n List<Car> all();\n\n void save(Car car);\n\n void update(Car car);\n\n void delete(Car car);\n}", "@Singleton\npublic class InMemoryCarRepository implements CarRepository {\n\n private final AtomicInteger idGenerator = new AtomicInteger(1);\n private final Map<Integer, Car> repository = new ConcurrentHashMap<>();\n\n @Override\n public Optional<Car> byId(int id) {\n return Optional.ofNullable(repository.get(id));\n }\n\n @Override\n public List<Car> all() {\n return new ArrayList<>(repository.values());\n }\n\n @Override\n public void save(Car car) {\n if (car.getId() == null) {\n car.setId(idGenerator.getAndIncrement());\n }\n repository.put(car.getId(), car);\n }\n\n @Override\n public void update(Car car) {\n save(car);\n }\n\n @Override\n public void delete(Car car) {\n repository.remove(car.getId());\n }\n}", "public class CarResource {\n\n private final CarRepository carRepository;\n\n public CarResource(CarRepository carRepository) {\n this.carRepository = carRepository;\n }\n\n public void byId(RoutingContext routingContext) {\n HttpServerResponse response = routingContext.response();\n String idParam = routingContext.request().getParam(\"id\");\n if (idParam == null) {\n response.setStatusCode(400).end();\n } else {\n Optional<Car> car = carRepository.byId(Integer.parseInt(idParam));\n if (car.isPresent()) {\n CarRepresentation carRepresentation = new CarRepresentation(car.get());\n carRepresentation.addLink(self(routingContext.request().absoluteURI()));\n response.putHeader(\"content-type\", \"application/json\")\n .end(Json.encode(carRepresentation));\n } else {\n response.setStatusCode(404).end();\n }\n }\n }\n}", "public class CarsResource {\n\n private final CarRepository carRepository;\n\n\n public CarsResource(CarRepository carRepository) {\n this.carRepository = carRepository;\n }\n\n public void all(RoutingContext routingContext) {\n List<Car> all = carRepository.all();\n HttpServerResponse response = routingContext.response();\n response.putHeader(\"content-type\", \"application/json\")\n .putHeader(\"total-count\", String.valueOf(all.size()))\n .end(encode(all.stream().map(car -> {\n CarRepresentation carRepresentation = new CarRepresentation(car);\n carRepresentation.addLink(self(routingContext.request().absoluteURI() + \"/\" + car.getId()));\n return carRepresentation;\n }).collect(toList())));\n }\n\n public void create(RoutingContext routingContext) {\n Car car = Json.decodeValue(routingContext.getBodyAsString(), Car.class);\n carRepository.save(car);\n HttpServerResponse response = routingContext.response();\n response.putHeader(\"Location\", routingContext.request().absoluteURI() + \"/\" + car.getId())\n .setStatusCode(201)\n .end();\n }\n}", "public class HelloResource {\n\n private final HttpClient httpClient;\n\n public HelloResource(HttpClient httpClient) {\n\n this.httpClient = httpClient;\n }\n\n public void hello(RoutingContext routingContext) {\n httpClient.getAbs(\"https://localhost:8090/cars\")\n .putHeader(\"Accept\", \"application/json\")\n .putHeader(\"Authorization\", \"Bearer \" + routingContext.user().principal().getString(\"token\"))\n .handler(response ->\n response.bodyHandler(buffer -> {\n if (response.statusCode() == 200) {\n List<Car> cars = new ArrayList<>(asList(Json.decodeValue(buffer.toString(), Car[].class)));\n routingContext.response()\n .putHeader(\"content-type\", \"test/plain\")\n .setChunked(true)\n .write(cars.stream().map(Car::getName).collect(toList()).toString())\n .write(\", and then Hello World from Vert.x-Web!\")\n .end();\n } else {\n routingContext.response()\n .setStatusCode(response.statusCode())\n .putHeader(\"content-type\", \"test/plain\")\n .setChunked(true)\n .write(\"Oops, something went wrong: \" + response.statusMessage())\n .end();\n }\n }))\n .end();\n }\n}", "public class BearerAuthHandler extends AuthHandlerImpl {\r\n\r\n public BearerAuthHandler(AuthProvider authProvider) {\r\n super(authProvider);\r\n }\r\n\r\n @Override\r\n public void handle(RoutingContext routingContext) {\r\n HttpServerRequest request = routingContext.request();\r\n request.pause();\r\n String authorization = request.headers().get(HttpHeaders.AUTHORIZATION);\r\n if (authorization == null) {\r\n routingContext.fail(401);\r\n } else {\r\n String[] parts = authorization.split(\" \");\r\n if (parts.length != 2) {\r\n routingContext.fail(401);\r\n } else {\r\n String scheme = parts[0];\r\n if (!\"bearer\".equalsIgnoreCase(scheme)) {\r\n routingContext.fail(401);\r\n } else {\r\n String token = parts[1];\r\n JsonObject credentials = new JsonObject();\r\n credentials.put(\"token\", token);\r\n\r\n authProvider.authenticate(credentials, res -> {\r\n if (res.succeeded()) {\r\n routingContext.setUser(res.result());\r\n request.resume();\r\n routingContext.next();\r\n } else {\r\n routingContext.fail(401);\r\n }\r\n });\r\n }\r\n }\r\n }\r\n }\r\n}\r", "public class FacebookOauthTokenVerifier implements AuthProvider {\r\n\r\n private final HttpClient httpClient;\r\n\r\n public FacebookOauthTokenVerifier(HttpClient httpClient) {\r\n this.httpClient = httpClient;\r\n }\r\n\r\n @Override\r\n public void authenticate(JsonObject credentials, Handler<AsyncResult<User>> resultHandler) {\r\n String token = credentials.getString(\"token\");\r\n\r\n httpClient.getAbs(\"https://graph.facebook.com:443/v2.4/me?access_token=\" + token)\r\n .handler(response ->\r\n response.bodyHandler(buffer -> {\r\n JsonObject json = new JsonObject(buffer.toString());\r\n if (response.statusCode() != 200) {\r\n String message = json.getJsonObject(\"error\").getString(\"message\");\r\n resultHandler.handle(Future.failedFuture(message));\r\n } else {\r\n resultHandler.handle(Future.succeededFuture(\r\n new MyUser(Long.parseLong(json.getString(\"id\")),\r\n json.getString(\"name\"),\r\n token)));\r\n }\r\n }))\r\n .exceptionHandler(error ->\r\n resultHandler.handle(Future.failedFuture(error.getMessage())))\r\n .end();\r\n }\r\n\r\n}\r" ]
import com.fasterxml.jackson.databind.DeserializationFeature; import io.github.cdelmas.spike.common.domain.Car; import io.github.cdelmas.spike.common.domain.CarRepository; import io.github.cdelmas.spike.common.persistence.InMemoryCarRepository; import io.github.cdelmas.spike.vertx.car.CarResource; import io.github.cdelmas.spike.vertx.car.CarsResource; import io.github.cdelmas.spike.vertx.hello.HelloResource; import io.github.cdelmas.spike.vertx.infrastructure.auth.BearerAuthHandler; import io.github.cdelmas.spike.vertx.infrastructure.auth.FacebookOauthTokenVerifier; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.json.Json; import io.vertx.core.net.JksOptions; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.AuthHandler; import io.vertx.ext.web.handler.BodyHandler; import static java.util.stream.Collectors.toList;
/* Copyright 2015 Cyril Delmas 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 io.github.cdelmas.spike.vertx; public class Main { public static void main(String[] args) { // TODO start a vertx instance // deploy verticles / one per resource in this case Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Vertx vertx = Vertx.vertx(); HttpClientOptions clientOptions = new HttpClientOptions() .setSsl(true) .setTrustStoreOptions(new JksOptions() .setPath(System.getProperty("javax.net.ssl.trustStore")) .setPassword(System.getProperty("javax.net.ssl.trustStorePassword"))); HttpClient httpClient = vertx.createHttpClient(clientOptions); Router router = Router.router(vertx); AuthHandler auth = new BearerAuthHandler(new FacebookOauthTokenVerifier(httpClient)); router.route("/*").handler(auth); HelloResource helloResource = new HelloResource(httpClient); router.get("/hello").produces("text/plain").handler(helloResource::hello); CarRepository carRepository = new InMemoryCarRepository();
CarsResource carsResource = new CarsResource(carRepository);
4
asascience-open/ncSOS
src/main/java/com/asascience/ncsos/outputformatter/go/JsonFormatter.java
[ "public class Grid extends baseCDMClass implements iStationData {\n\n public static final String DEPTH = \"depth\";\n public static final String LAT = \"latitude\";\n public static final String LON = \"longitude\";\n private List<String> stationNameList;\n private List<String> stationDescripList;\n private final String[] variableNames;\n private final ArrayList<String> eventTimes;\n private GridDataset GridData;\n private final Map<String, String> latLonRequest;\n DateFormatter dateFormatter = new DateFormatter();\n\n /**\n * Constructs a new Grid with parameters passed in\n * @param requestedStationNames the names of the stations from the request query string\n * @param eventTime the time(s) from the request query string\n * @param variableNames the observed properties from the request query string\n * @param latLonRequest HashMap that contains the requested Lat,Lon coordinates from the request query string\n */\n public Grid(String[] requestedStationNames, String[] eventTime, String[] variableNames, Map<String, String> latLonRequest) {\n startDate = null;\n endDate = null;\n this.variableNames = (variableNames);\n\n this.reqStationNames = new ArrayList<String>();\n this.reqStationNames.addAll(Arrays.asList(requestedStationNames));\n \n if (eventTime != null) {\n this.eventTimes = new ArrayList<String>();\n this.eventTimes.addAll(Arrays.asList(eventTime));\n } else\n this.eventTimes = null;\n \n this.latLonRequest = latLonRequest;\n this.stationNameList = new ArrayList<String>();\n this.stationDescripList = new ArrayList<String>();\n \n lowerAlt = upperAlt = 0;\n }\n\n public Map<String, String> getLatLonRequest() {\n\t\treturn latLonRequest;\n\t}\n\n\t/**\n * Adds a Date entry to the builder from the dates array\n * @param builder the StringBuilder being built\n * @param dates Date array from which the first date value (0 index) is pulled from\n */\n private String addDateEntry( CalendarDate date) {\n return (\"time=\")+(date.toString())+\",\";\n // builder.append(\",\");\n }\n\n /**\n * Attempts to collect the depth values from latLons and returns them in an array\n * @param latLons hash map that has lat,lon and maybe depth\n * @return integer array with the indices of the depth values\n */\n private int[] checkAndGetDepthIndices(Map<String, Integer[]> latLons) {\n \t// setup for finding our depth values\n \tint[] retVal = new int[latLons.get(LAT).length];\n \tCoordinateAxis1D depthData = (CoordinateAxis1D) GridData.getDataVariable(DEPTH);\n \tif (depthData != null) {\n \t\tdouble[] depthDbl = depthData.getCoordValues();\n \t\tString[] requestedDepths = null;\n \t\tif(latLonRequest.containsKey(DEPTH)){\n \t\t\trequestedDepths = latLonRequest.get(DEPTH).split(\"[,]\");\n\n \t\t\tint currIndex = 0;\n \t\t\tfor (int i=0;i<retVal.length;i++) {\n \t\t\t\tcurrIndex = (i < requestedDepths.length) ? i : requestedDepths.length - 1;\n \t\t\t\ttry {\n \t\t\t\t\tretVal[i] = findBestIndex(depthDbl, Double.parseDouble(requestedDepths[currIndex]));\n \t\t\t\t} catch (Exception e) {\n \t\t\t\t\tSystem.out.println(\"Could not parse: \" + requestedDepths[currIndex] + \" - \" + e.getMessage());\n \t\t\t\t\tretVal[i] = 0;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t} else {\n \t\tfor (int r=0;r<retVal.length;r++) {\n \t\t\tretVal[r] = 0;\n \t\t}\n \t}\n \treturn retVal;\n }\n\n \n public Integer getGridZIndex(String grid){\n \tInteger zIndex = -1;\n \tGridDatatype gridType= this.GridData.findGridDatatype(grid);\n \tif(gridType != null){\n \t\tzIndex = gridType.getZDimensionIndex();\n \t}\n \treturn zIndex;\n }\n \n \n public String getDepthUnits(String grid){\n \tString units = null;\n \tGridDatatype gridType= this.GridData.findGridDatatype(grid);\n \tif(gridType != null){\n \t\tint zIndex = gridType.getZDimensionIndex();\n \t\tif(zIndex > -1){\n \t\t\t\tunits = gridType.getCoordinateSystem().getVerticalAxis().getUnitsString();\n \t\t}\n \t}\n \t\n \treturn units;\n }\n public List<Double> getDepths(String grid){\n \tGridDatatype gridType= this.GridData.findGridDatatype(grid);\n \tList<Double> heightVals = new ArrayList<Double>();\n \tif(gridType != null){\n \t\tint zIndex = gridType.getZDimensionIndex();\n \t\tif(zIndex > -1){\n\n \t\t\ttry {\n \t\t\t\tArray heights = gridType.getCoordinateSystem().getVerticalAxis().read();\n \t\t\t\tfor(int i =0; i < heights.getSize(); i++){\n \t\t\t\t\theightVals.add(heights.getDouble(i));\n \t\t\t\t}\n \t\t\t} catch (IOException e) {\n \t\t\t\t// TODO Auto-generated catch block\n \t\t\t\te.printStackTrace();\n \t\t\t}\n \t\t}\n \t}\n \treturn heightVals;\n }\n \n /************************/\n /* iStationData Methods */\n /**************************************************************************/\n \n @Override\n public void setData(Object griddedDataset) throws IOException {\n this.GridData = (GridDataset) griddedDataset;\n\n setStartDate(df.toDateTimeStringISO(GridData.getCalendarDateStart().toDate()));\n setEndDate(df.toDateTimeStringISO(GridData.getCalendarDateEnd().toDate()));\n\n //check and only add stations that are of interest\n int stCount = 0;\n for (int i = 0; i < GridData.getGrids().size(); i++) {\n List<String> varList = Arrays.asList(variableNames);\n if (varList.contains(GridData.getGrids().get(i).getFullName())) {\n // Does the varname equal?\n stCount++;\n stationNameList.add(GridData.getGrids().get(i).getFullName());\n stationDescripList.add(GridData.getGrids().get(i).getDescription());\n setBoundingBox(GridData.getGrids().get(i).getCoordinateSystem().getLatLonBoundingBox());\n } else {\n // Does the standard_name equal?\n String snd = GridData.getGrids().get(i).findAttValueIgnoreCase(CF.STANDARD_NAME, \"NOPE\");\n if (varList.contains(snd)) {\n stCount++;\n stationNameList.add(GridData.getGrids().get(i).getFullName());\n stationDescripList.add(GridData.getGrids().get(i).getDescription());\n setBoundingBox(GridData.getGrids().get(i).getCoordinateSystem().getLatLonBoundingBox());\n }\n }\n }\n setNumberOfStations(stCount);\n }\n\n public void setBoundingBox(LatLonRect llr) {\n upperLon = llr.getUpperRightPoint().getLongitude();\n upperLat = llr.getUpperRightPoint().getLatitude();\n lowerLon = llr.getLowerLeftPoint().getLongitude();\n lowerLat = llr.getLowerLeftPoint().getLatitude();\n }\n\n @Override\n public void setInitialLatLonBoundaries(List<Station> tsStationList) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public String getDataResponse(int stNum) {\n if (GridData != null) {\n StringBuilder builder = new StringBuilder();\n Array data = null;\n\n GridDatatype grid = GridData.getGrids().get(0);\n GridCoordSystem gcs = grid.getCoordinateSystem();\n \n String lat_name = gcs.getYHorizAxis().getOriginalVariable().getFullName();\n String lon_name = gcs.getXHorizAxis().getOriginalVariable().getFullName();\n String depth_name = null;\n Integer timeIstart = null;\n Integer timeIend = -1;\n CoordinateAxis1DTime coordTime = gcs.getTimeAxis1D();\n\n if (this.eventTimes == null){\n \ttimeIstart = 0;\n \ttimeIend = (int) (coordTime.getSize() -1);\n }\n else if (eventTimes.size() > 1) {\n \t// find all times between two specified\n \tCalendarDate dtStart = CalendarDateFormatter.isoStringToCalendarDate(null, eventTimes.get(0));\n CalendarDate dtEnd = CalendarDateFormatter.isoStringToCalendarDate(null, eventTimes.get(1));\n for(Integer timeIndex = 0; timeIndex < coordTime.getSize(); timeIndex++){\n \tCalendarDate cD = coordTime.getCalendarDate(timeIndex);\n \tif(timeIstart == null && (cD.getDifferenceInMsecs(dtStart) == 0 || cD.isAfter(dtStart))){\n \t\ttimeIstart = timeIndex;\n \t}\n \tif(cD.getDifferenceInMsecs(dtEnd) == 0 || (cD.isBefore(dtEnd) && timeIstart != null)){\n \t\ttimeIend = timeIndex;\n \t}\n }\n } //if single event time \n else {\n // get closest time\n \tCalendarDate dtStart = CalendarDateFormatter.isoStringToCalendarDate(null, eventTimes.get(0));\n \tlong cDiff;\n \tlong savedDiff = Long.MAX_VALUE;\n \tInteger currIndex = null;\n \tfor(Integer timeIndex = 0; timeIndex <= timeIend; timeIndex++){\n \tCalendarDate cD = coordTime.getCalendarDate(timeIndex);\n\n \t\tcDiff = cD.getDifferenceInMsecs(dtStart);\n \t\t\n \t\tif(currIndex == null || Math.abs(cDiff) < savedDiff){\n \t\t\tsavedDiff = Math.abs(cDiff);\n \t\t\tcurrIndex = timeIndex;\n \t\t}\n \t}\n \ttimeIstart = currIndex;\n \ttimeIend = currIndex;\n }\n double[] lonDbl = ((CoordinateAxis1D)GridData.getDataVariable(lon_name)).getCoordValues();\n double[] latDbl = ((CoordinateAxis1D)GridData.getDataVariable(lat_name)).getCoordValues();\n double[] depthDbl = null;\n\n CoordinateAxis1D depthAxis = GridData.getGrids().get(0).getCoordinateSystem().getVerticalAxis();\n if (depthAxis != null) {\n depth_name = depthAxis.getOriginalVariable().getFullName();\n depthDbl = ((CoordinateAxis1D)GridData.getDataVariable(depth_name)).getCoordValues();\n }\n\n Map<String, Integer[]> latLonDepthHash = findDataIndexs(lonDbl, latDbl, latLonRequest);\n\n int[] depthHeights = new int[latLonDepthHash.get(LON).length];\n Map<Integer, List<Integer>> allDepths = new HashMap<Integer, List<Integer>>();\n Boolean zeroDepths = true;\n\n for(String vars : variableNames) {\n if(vars.equalsIgnoreCase(DEPTH)) {\n // we do want depths\n zeroDepths = false;\n if(this.latLonRequest.containsKey(DEPTH)){\n \tdepthHeights = checkAndGetDepthIndices(latLonDepthHash);\n \t for(int i=0; i<depthHeights.length; i++) {\n \t\t List<Integer> oneVal = new ArrayList<Integer>();\n \t\t oneVal.add(depthHeights[i]);\n \t\t allDepths.put(i, oneVal);\n \t }\n }\n else {\n \t\n \tList<Double> depthVals = this.getDepths(grid.getShortName());\n \tList<Integer> depthIndexList = new ArrayList<Integer>();\n \tfor(int i=0; i <depthVals.size(); i++){\n \t\tdepthIndexList.add(i);\n \t}\n \tfor(int i=0; i<latLonDepthHash.get(LON).length; i++) {\n \t\tallDepths.put(i, depthIndexList);\n \t}\n }\n break;\n }\n }\n \n if (zeroDepths) {\n for(int i=0; i<depthHeights.length; i++) {\n List<Integer> oneVal = new ArrayList<Integer>();\n \t\t \toneVal.add(0);\n \t\t \tallDepths.put(i, oneVal);\n }\n }\n\n for(Integer timeIndex = timeIstart; timeIndex <= timeIend; timeIndex++){\n \tfor (int k=0; k<latLonDepthHash.get(LAT).length; k++) {\n \t\tfor(Integer depthIndex : allDepths.get(k)){\n\n \t\t\tCalendarDate cD = coordTime.getCalendarDate(timeIndex);\n \t\t\tString startStr = \"\";\n\n \t\t\t//modify for requested dates, add in for loop\n \t\t\tstartStr = addDateEntry(cD);\n\n \t\t\t// add depth\n \t\t\tif(depthDbl != null) {\n \t\t\t\tstartStr += (depth_name)+(\"=\")+(depthDbl[depthIndex])+(\",\");\n \t\t\t\tstartStr += (BIN_STR)+(depthIndex)+(\",\");\n \t\t\t\t//builder.append(depth_name).append(\"=\").append(depthDbl[depthIndex]).append(\",\");\n \t\t\t\t//builder.append(BIN_STR).append(depthIndex).append(\",\");\n \t\t\t}\n \t\t\tstartStr += (STATION_STR + stNum) +(\",\");\n\n \t\t\tstartStr += lat_name + \"=\"+latDbl[latLonDepthHash.get(LAT)[k]]+(\",\");\n \t\t\tstartStr += lon_name + (\"=\") + (lonDbl[latLonDepthHash.get(LON)[k]]) +(\",\");\n \t\t\t\n \t\t\t\n \t\t\t//builder.append(STATION_STR + stNum).append(\",\");\n\n \t\t\t//builder.append(lat_name).append(\"=\").append(latDbl[latLonDepthHash.get(LAT)[k]]).append(\",\");\n \t\t\t//builder.append(lon_name).append(\"=\").append(lonDbl[latLonDepthHash.get(LON)[k]]).append(\",\");\n \t\t\t// get data slices\n \t\t\tString dataName;\n \t\t\tfor (int l=0; l<GridData.getGrids().size();l++) {\n \t\t\t\tdataName = GridData.getGrids().get(l).getName();\n \t\t\t\tif (isInVariableNames(GridData.getGrids().get(l).getName())) {\n \t\t\t\t\ttry {\n \t\t\t\tbuilder.append(startStr);\n\n \t\t\t\t\t\tgrid = GridData.getGrids().get(l);\n \t\t\t\t\t\tint latI = latLonDepthHash.get(LAT)[k];\n \t\t\t\t\t\tint lonI = latLonDepthHash.get(LON)[k];\n \t\t\t\t\t\tdata = grid.readDataSlice(timeIndex, depthIndex, latI, lonI);\n \t\t\t\t\t\tbuilder.append(dataName).append(\"=\").append(data.getFloat(0)).append(\";\");\n \t\t\t\t\t} catch (Exception ex) {\n \t\t\t\t\t\tSystem.out.println(\"Error in reading data slice, index \" + l + \" - \" + ex.getMessage());\n \t\t\t\t\t\tbuilder.delete(0, builder.length());\n \t\t\t\t\t\tbuilder.append(\"ERROR= reading data slice from GridData: \").append(ex.getLocalizedMessage());\n \t\t\t\t\t\treturn builder.toString();\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t\t//if(builder.length() > 0)\n \t\t\t//\tbuilder.deleteCharAt(builder.length()-1);\n \t\t\t//builder.append(\";\");\n \t\t}\n \t}\n }\n //builder.append(\" \").append(\"\\n\");\n return builder.toString();\n }\n return DATA_RESPONSE_ERROR + Grid.class;\n\n }\n\n @Override\n public String getStationName(int idNum) {\n return stationNameList.get(idNum);\n }\n\n @Override\n public String getTimeEnd(int stNum) {\n return getBoundTimeEnd();\n }\n\n @Override\n public String getTimeBegin(int stNum) {\n return getBoundTimeBegin();\n }\n\n @Override\n public double getLowerLat(int stNum) {\n// return Double.parseDouble(latLonRequest.get(LAT));\n String[] latStr = latLonRequest.get(LAT).split((\"[,]\"));\n double retVal = Double.MAX_VALUE;\n for(int i=0; i<latStr.length;i++) {\n try {\n double val;\n if(latStr[i].contains(\"_\")) {\n String[] bounds = latStr[i].split(\"_\");\n if(Double.parseDouble(bounds[0]) > Double.parseDouble(bounds[1])) {\n val = Double.parseDouble(bounds[1]);\n } else {\n val = Double.parseDouble(bounds[0]);\n }\n } else {\n val = Double.parseDouble(latStr[i]);\n }\n if (val < retVal)\n retVal = val;\n } catch (Exception e) {\n System.out.println(\"Error getLowerLat: \" + e.getMessage());\n }\n }\n \n return retVal;\n }\n\n public double getClosestLat(int stNum){\n \n String lat_name = GridData.getGrids().get(0).getCoordinateSystem().getYHorizAxis().getOriginalVariable().getFullName();\n String lon_name = GridData.getGrids().get(0).getCoordinateSystem().getXHorizAxis().getOriginalVariable().getFullName();\n double[] lonDbl = ((CoordinateAxis1D)GridData.getDataVariable(lon_name)).getCoordValues();\n double[] latDbl = ((CoordinateAxis1D)GridData.getDataVariable(lat_name)).getCoordValues();\n return latDbl[this.findBestIndexLon(latDbl, (Double.valueOf( this.latLonRequest.get(LAT).split(\",\")[0])))];\n\n }\n \n public double getClosestLon(int stNum){\n \t String lon_name = GridData.getGrids().get(0).getCoordinateSystem().getXHorizAxis().getOriginalVariable().getFullName();\n double[] lonDbl = ((CoordinateAxis1D)GridData.getDataVariable(lon_name)).getCoordValues();\n return lonDbl[this.findBestIndexLon(lonDbl, (Double.valueOf( this.latLonRequest.get(LON).split(\",\")[0])))];\n }\n \n \n @Override\n public double getLowerLon(int stNum) {\n// return Double.parseDouble(latLonRequest.get(LON));\n String[] lonStr = latLonRequest.get(LON).split((\"[,]\"));\n double retVal = Double.MAX_VALUE;\n for(int i=0; i<lonStr.length;i++) {\n try {\n double val;\n if(lonStr[i].contains(\"_\")) {\n String[] bounds = lonStr[i].split(\"_\");\n if(Double.parseDouble(bounds[0]) > Double.parseDouble(bounds[1])) {\n val = Double.parseDouble(bounds[1]);\n } else {\n val = Double.parseDouble(bounds[0]);\n }\n } else {\n val = Double.parseDouble(lonStr[i]);\n }\n if (val < retVal)\n retVal = val;\n } catch (Exception e) {\n System.out.println(\"Error getLowerLon: \" + e.getMessage());\n }\n }\n \n return retVal;\n }\n\n public double getUpperLat() {\n return upperLat;\n }\n public double getUpperLon() {\n return upperLon;\n }\n public double getLowerLat() {\n return lowerLat;\n }\n public double getLowerLon() {\n return lowerLon;\n }\n\n @Override\n public double getUpperLat(int stNum) {\n// return Double.parseDouble(latLonRequest.get(LAT));\n String[] latStr = latLonRequest.get(LAT).split((\"[,]\"));\n double retVal = -1 * Double.MAX_VALUE;\n for(int i=0; i<latStr.length;i++) {\n try {\n double val;\n if(latStr[i].contains(\"_\")) {\n String[] bounds = latStr[i].split(\"_\");\n if(Double.parseDouble(bounds[0]) < Double.parseDouble(bounds[1])) {\n val = Double.parseDouble(bounds[1]);\n } else {\n val = Double.parseDouble(bounds[0]);\n }\n } else {\n val = Double.parseDouble(latStr[i]);\n }\n if (val > retVal)\n retVal = val;\n } catch (Exception e) {\n System.out.println(\"Error getUpperLat: \" + e.getMessage());\n }\n }\n \n return retVal;\n }\n\n @Override\n public double getUpperLon(int stNum) {\n// return Double.parseDouble(latLonRequest.get(LON));\n String[] lonStr = latLonRequest.get(LON).split((\"[,]\"));\n double retVal = -1 * Double.MAX_VALUE;\n for(int i=0; i<lonStr.length;i++) {\n try {\n double val;\n if(lonStr[i].contains(\"_\")) {\n String[] bounds = lonStr[i].split(\"_\");\n if(Double.parseDouble(bounds[0]) < Double.parseDouble(bounds[1])) {\n val = Double.parseDouble(bounds[1]);\n } else {\n val = Double.parseDouble(bounds[0]);\n }\n } else {\n val = Double.parseDouble(lonStr[i]);\n }\n if (val > retVal)\n retVal = val;\n } catch (Exception e) {\n System.out.println(\"Error getUpperLon: \" + e.getMessage());\n }\n }\n \n return retVal;\n }\n \n @Override\n public String getDescription(int stNum) {\n return stationDescripList.get(stNum);\n }\n \n /**************************************************************************/\n\n /**\n * \n * @param nameToCheck\n * @return \n */\n private Boolean isInVariableNames(String nameToCheck) {\n for (String name : variableNames) {\n if (name.equalsIgnoreCase(nameToCheck)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * find lat lon index's in X|Y axis of requested locations\n * @param lonDbl array of longitude values\n * @param latDbl array of latitude values\n * @param latLonRequest map with the latitude and longitude request(s)\n * @return map with arrays of indices for latitude and longitude\n */\n private Map<String, Integer[]> findDataIndexs(double[] lonDbl, double[] latDbl, Map<String, String> latLonRequest) {\n Map<String, Integer[]> latLonIndex = new HashMap<String, Integer[]>();\n String lonVal = latLonRequest.get(LON);\n String latVal = latLonRequest.get(LAT);\n String[] lons, lats;\n \n // check to see if we are looking for multiple or range of lat/lons\n // multiple\n if(lonVal.contains(\",\")) {\n // multiple lons\n lons = lonVal.split(\",\");\n } else {\n lons = new String[] { lonVal };\n }\n \n if (latVal.contains(\",\")) {\n // multiple lats\n lats = latVal.split(\",\");\n } else {\n lats = new String[] { latVal }; \n }\n \n double[] requestedLons = new double[lons.length];\n double[] requestedLats = new double[lats.length];\n\n\n for (int j=0;j<lons.length;j++) {\n try {\n if (lons[j].contains(\"_\")) {\n String[] bounds = lons[j].split(\"_\");\n requestedLons = arrayFromValueRange(bounds, lonDbl, requestedLons);\n } else {\n requestedLons[j] = Double.parseDouble(lons[j]);\n }\n } catch (Exception e) {\n System.out.println(\"Error in parse: \" + e.getMessage());\n }\n }\n\n for (int k=0;k<lats.length;k++) {\n try {\n if (lats[k].contains(\"_\")) {\n String[] bounds = lats[k].split(\"_\");\n requestedLats = arrayFromValueRange(bounds, latDbl, requestedLats);\n } else {\n requestedLats[k] = Double.parseDouble(lats[k]);\n }\n } catch (Exception e) {\n System.out.println(\"Error in parse: \" + e.getMessage());\n }\n }\n\n // determine which array to use for loop count\n int requestedArrayLength = (requestedLons.length > requestedLats.length) ? requestedLons.length : requestedLats.length;\n\n Integer[] retLats = new Integer[requestedArrayLength];\n Integer[] retLons = new Integer[requestedArrayLength];\n\n // get our indices\n for(int i=0;i<requestedArrayLength;i++) {\n if(requestedLons.length > i) {\n retLons[i] = findBestIndexLon(lonDbl, requestedLons[i]);\n } else {\n retLons[i] = findBestIndexLon(lonDbl, requestedLons[requestedLons.length - 1]);\n }\n\n if(requestedLats.length > i) {\n retLats[i] = findBestIndex(latDbl, requestedLats[i]);\n } else {\n retLats[i] = findBestIndex(latDbl, requestedLats[requestedLats.length - 1]);\n }\n }\n\n // put into hash\n latLonIndex.put(LAT, retLats);\n latLonIndex.put(LON, retLons);\n \n return latLonIndex;\n\n }\n \n /**\n * iterate through the arrayToSearch array for values that lie in out boundaries\n * @param bounds the upper & lower bounds of the desired values\n * @param arrayToSearch array to search for values inside given bounds\n * @param arrayToExpand the array to add the desired values to\n * @return arrayToExpand with the new values added\n */\n private double[] arrayFromValueRange(String[] bounds, double[] arrayToSearch, double[] arrayToExpand) {\n double minVal, maxVal;\n try {\n minVal = Double.parseDouble(bounds[0]);\n } catch (Exception e) {\n minVal = 0;\n }\n try {\n maxVal = Double.parseDouble(bounds[1]);\n } catch (Exception e) {\n maxVal = minVal;\n }\n if (maxVal < minVal) {\n // swap values if the order is reversed\n double temp = minVal;\n minVal = maxVal;\n maxVal = temp;\n }\n // looking for a range of doubles, iterate through the arrayToSearch array for values that lie in out boundaries\n ArrayList<Double> builder = new ArrayList<Double>();\n for (int k=0;k<arrayToExpand.length;k++) {\n builder.add(arrayToExpand[k]);\n }\n for (int l=0;l<arrayToSearch.length;l++) {\n if (arrayToSearch[l] >= minVal && arrayToSearch[l] <= maxVal) {\n builder.add(arrayToSearch[l]);\n }\n }\n arrayToExpand = new double[builder.size()];\n for(int i=0;i<builder.size();i++) {\n arrayToExpand[i] = builder.get(i).doubleValue();\n }\n return arrayToExpand;\n }\n \n /**\n * iterate through valueArray to find the index with the value closest to 'valueToFind'\n * @param valueArray array to iterate through\n * @param valueToFind value to find\n * @return index of value closest to 'valueToFind'\n */\n private int findBestIndex(double[] valueArray, double valueToFind){\n // iterate through the array to find the index with the value closest to 'valueToFind'\n double bestDiffValue = Double.MAX_VALUE;\n int retIndex = -1;\n for(int i=0; i<valueArray.length; i++) {\n double curDiffValue = valueArray[i] - valueToFind;\n if(Math.abs(curDiffValue) < bestDiffValue) {\n bestDiffValue = Math.abs(curDiffValue);\n retIndex = i;\n }\n }\n return retIndex;\n }\n\n private int findBestIndexLon(double[] valueArray, double valueToFind){\n // iterate through the array to find the index with the value closest to 'valueToFind'\n double bestDiffValue = Double.MAX_VALUE;\n int retIndex = -1;\n double uValueToFind = valueToFind % 360; // make 0-360\n for(int i=0; i<valueArray.length; i++) {\n \tdouble cVal = valueArray[i] % 360;\n \tdouble curDiffValue;\n \t\tcurDiffValue = cVal - uValueToFind;\n \t\tdouble meth2;\n \t if(uValueToFind > cVal){\n \t\t meth2 = (360 - uValueToFind) + cVal;\n \t }\n \t else{\n \t\t meth2 = (360 - cVal) + uValueToFind;\n \t } \t \n \t curDiffValue = Math.min(curDiffValue, meth2);\n \n \tif(Math.abs(curDiffValue) < bestDiffValue) {\n bestDiffValue = Math.abs(curDiffValue);\n retIndex = i;\n }\n }\n return retIndex;\n }\n public List<String> getLocationsString(int stNum) {\n List<String> retval = new ArrayList<String>();\n retval.add(this.getLowerLat(stNum) + \" \" + this.getLowerLon(stNum));\n return retval;\n }\n\n \n}", "public class TimeSeriesProfile extends baseCDMClass implements iStationData {\n\n private StationProfileFeatureCollection tsProfileData;\n private List<Station> tsStationList;\n private final ArrayList<String> eventTimes;\n private final String[] variableNames;\n private ArrayList<Double> altMin, altMax;\n private Map<String, List<Double>> numberHeightsForStation;\n private boolean requestedFirst;\n private boolean requestedLast;\n private boolean multDimTimVar;\n CoordinateAxis heightAxis;\n /**\n * \n * @param stationName\n * @param eventTime\n * @param variableNames\n */\n public TimeSeriesProfile(String[] stationName, String[] eventTime, \n String[] variableNames, boolean requestedFirst,\n boolean requestedLast, boolean multDimTimeVar,\n CoordinateAxis heightAxis) {\n\n startDate = null;\n endDate = null;\n this.variableNames = variableNames;\n this.multDimTimVar = multDimTimeVar;\n this.reqStationNames = new ArrayList<String>();\n this.requestedFirst = requestedFirst;\n this.requestedLast = requestedLast;\n this.heightAxis = heightAxis;\n reqStationNames.addAll(Arrays.asList(stationName));\n if (eventTime != null) {\n this.eventTimes = new ArrayList<String>();\n this.eventTimes.addAll(Arrays.asList(eventTime));\n } else\n this.eventTimes = null;\n lowerAlt = Double.POSITIVE_INFINITY;\n upperAlt = Double.NEGATIVE_INFINITY;\n }\n\n /****************TIMESERIESPROFILE*******************/\n private String createStationProfileFeature(int stNum) throws IOException {\n StringBuilder builder = new StringBuilder();\n DateFormatter dateFormatter = new DateFormatter();\n List<String> valueList = new ArrayList<String>();\n\n StationProfileFeature stationProfileFeature = tsProfileData.getStationProfileFeature(tsStationList.get(stNum));\n List<Date> z = stationProfileFeature.getTimes();\n\n ProfileFeature pf = null;\n Set<Date> processedDates = new HashSet<Date>();\n \n //if not event time is specified get all the data\n if (eventTimes == null) {\n //test getting items by date(index(0))\n stationProfileFeature.resetIteration();\n// for (int i = 0; i < z.size(); i++) {\n while(stationProfileFeature.hasNext()){\n // pf = stationProfileFeature.getProfileByDate(z.get(i));\n pf = stationProfileFeature.next();\n System.out.println(pf.getTime().toGMTString());\n if(this.multDimTimVar || !processedDates.contains(pf.getTime()) ){\n createStationProfileData(pf, valueList, dateFormatter, builder, stNum);\n if (builder.toString().contains(\"ERROR\"))\n break;\n processedDates.add(pf.getTime());\n }\n \n }\n } else if (eventTimes.size() > 1) {\n Date startDate = null;\n Date endDate = null;\n if(this.requestedFirst){\n startDate = z.get(0);\n if(!requestedLast && eventTimes.get(0).equals(eventTimes.get(1))){\n endDate = startDate;\n }\n }\n \n if(this.requestedLast){\n endDate = z.get(z.size() - 1);\n if(!requestedFirst && eventTimes.get(0).equals(eventTimes.get(1))){\n startDate = endDate;\n }\n }\n if(endDate == null) {\n endDate = CalendarDateFormatter.isoStringToDate( eventTimes.get(1));\n }\n if(startDate == null) {\n startDate = CalendarDateFormatter.isoStringToDate( eventTimes.get(0));\n }\n for (int i = 0; i < z.size(); i++) {\n\n // check to make sure the data is within the start/stop\n if(z.get(i).compareTo(startDate) >= 0 && z.get(i).compareTo(endDate) <= 0){\n if(this.multDimTimVar || !processedDates.contains(z.get(i)) ){\n pf = stationProfileFeature.getProfileByDate(z.get(i));\n\n DateTime dtStart = new DateTime(startDate, chrono);\n DateTime dtEnd = new DateTime(endDate, chrono);\n DateTime tsDt = new DateTime(pf.getTime(), chrono);\n\n //find out if current time(searchtime) is one or after startTime\n //same as start\n if (tsDt.isEqual(dtStart)) {\n createStationProfileData(pf, valueList, dateFormatter, builder, stNum);\n } //equal end\n else if (tsDt.isEqual(dtEnd)) {\n createStationProfileData(pf, valueList, dateFormatter, builder, stNum);\n } //afterStart and before end \n else if (tsDt.isAfter(dtStart) && (tsDt.isBefore(dtEnd))) {\n createStationProfileData(pf, valueList, dateFormatter, builder, stNum);\n }\n if (builder.toString().contains(\"ERROR\"))\n break;\n processedDates.add(z.get(i));\n }\n }\n }\n } //if the event time is specified get the correct data \n else {\n for (int i = 0; i < z.size(); i++) {\n\n if (df.toDateTimeStringISO(z.get(i)).contentEquals(eventTimes.get(0).toString())) {\n pf = stationProfileFeature.getProfileByDate(z.get(i));\n createStationProfileData(pf, valueList, dateFormatter, builder, stNum);\n }\n \n if (builder.toString().contains(\"ERROR\"))\n break;\n }\n }\n return builder.toString();\n }\n\n\n \n // returns the number of unique depths ie alt(profile,z) will return profile*z\n public int getNumberProfilesForStation(String station){\n int numProfiles = 0;\n if(this.numberHeightsForStation.containsKey(station)){\n numProfiles = this.numberHeightsForStation.get(station).size();\n }\n return numProfiles;\n }\n \n public String getHeightAxisUnits(){\n \tString heightUnits = null;\n \tif(this.heightAxis != null){\n \t\theightUnits = this.heightAxis.getUnitsString();\n \t}\n \treturn heightUnits;\n }\n \n public List<Double> getProfileHeightsForStation(String station){\n List<Double> profHeights;\n \n if(station != null && this.numberHeightsForStation.containsKey(station)){\n profHeights = this.numberHeightsForStation.get(station);\n }\n else{\n profHeights = new ArrayList<Double>();\n }\n return profHeights;\n }\n \n \n public List<Double> getProfileHeightsForStation(int stationNum){\n \tStation stat = tsStationList.get(stationNum);\n \tString statStr = null;\n \tif (stat != null){\n \t\tstatStr = stat.getName();\n \t}\n return getProfileHeightsForStation(statStr);\n }\n \n \n private void createStationProfileData(ProfileFeature pf, List<String> valueList, \n DateFormatter dateFormatter, StringBuilder builder, int stNum) {\n\n try {\n PointFeatureIterator it = pf.getPointFeatureIterator(-1);\n List<Double> binAlts = this.getProfileHeightsForStation(tsStationList.get(stNum).getName());\n while (it.hasNext()) {\n PointFeature pointFeature = it.next();\n valueList.clear();\n valueList.add(TIME_STR + dateFormatter.toDateTimeStringISO(\n \t\tnew Date(pointFeature.getObservationTimeAsCalendarDate().getMillis())));\n valueList.add(STATION_STR + stNum);\n Object heightOb = null;\n if(this.heightAxis != null)\n heightOb = pointFeature.getData().getScalarObject(this.heightAxis.getShortName());\n \n double alt;\n if(heightOb != null)\n alt = Double.valueOf(heightOb.toString());\n else\n alt = pointFeature.getLocation().getAltitude();\n \n if(binAlts != null && binAlts.contains(alt)){\n valueList.add(BIN_STR + binAlts.indexOf(alt));\n }\n for (String variableName : variableNames) {\n valueList.add(variableName + \"=\" + pointFeature.getData().getScalarObject(variableName).toString());\n }\n\n for (int i = 0; i < valueList.size(); i++) {\n builder.append(valueList.get(i));\n if (i < valueList.size() - 1) {\n builder.append(\",\");\n }\n }\n\n //builder.append(tokenJoiner.join(valueList));\n // TODO: conditional inside loop...\n if (tsProfileData.getStationProfileFeature(tsStationList.get(stNum)).size() > 1) {\n // builder.append(\" \");\n // builder.append(\"\\n\");\n builder.append(\";\");\n }\n }\n } catch (Exception ex ) {\n // print error\n builder.delete(0, builder.length());\n builder.append(\"ERROR =reading data from dataset: \").append(ex.getLocalizedMessage()).append(\". Most likely this property does not exist or is improperly stored in the dataset.\");\n }\n }\n\n \n \n \n /**\n * sets the time series profile data\n * @param featureProfileCollection \n */\n @Override\n public void setData(Object featureProfileCollection) throws IOException {\n this.tsProfileData = (StationProfileFeatureCollection) featureProfileCollection;\n String genericName = this.tsProfileData.getCollectionFeatureType().name()+\"-\";\n\n tsStationList = tsProfileData.getStations(reqStationNames);\n\n // Try to get stations by name, both with URN procedure and without\n tsStationList = tsProfileData.getStations(reqStationNames);\n for (String s : reqStationNames) {\n String[] urns = s.split(\":\");\n String statUrn = urns[urns.length - 1];\n\n Station st = tsProfileData.getStation(urns[urns.length - 1]);\n if (st != null) {\n tsStationList.add(st);\n }\n else if (statUrn.startsWith(genericName)){\n \t// check to see if generic name (ie: STATION-0)\n \ttry {\n \t\tInteger sIndex = Integer.valueOf(statUrn.substring(genericName.length()));\n \t\tst = tsProfileData.getStations().get(sIndex);\n \t\tif(st != null){\n \t\t\ttsStationList.add(st);\n \t\t}\n \t}\n \tcatch(Exception n){\n \t\tn.printStackTrace();\n \t}\n }\n }\n\n setNumberOfStations(tsStationList.size());\n \n altMin = new ArrayList<Double>();\n altMax = new ArrayList<Double>();\n numberHeightsForStation = new HashMap<String, List<Double>>();\n\n DateTime curTime;\n DateTime dtStart = null;\n DateTime dtEnd = null;\n if (tsStationList.size() > 0) {\n\n\n for (int i = 0; i < tsStationList.size(); i++) {\n StationProfileFeature sPFeature = tsProfileData.getStationProfileFeature(tsStationList.get(i));\n List<Date> times = sPFeature.getTimes();\n\n if (i == 0) {\n setInitialLatLonBoundaries(tsStationList);\n dtStart = new DateTime(times.get(0), chrono);\n dtEnd = new DateTime(times.get(0), chrono);\n } else {\n checkLatLonAltBoundaries(tsStationList, i);\n }\n\n //check the dates\n for (int j = 0; j < times.size(); j++) {\n curTime = new DateTime(times.get(j), chrono);\n\n if (curTime.isBefore(dtStart)) {\n dtStart = curTime;\n } else if (curTime.isAfter(dtEnd)) {\n dtEnd = curTime;\n }\n }\n }\n setStartDate(df.toDateTimeStringISO(dtStart.toDate()));\n setEndDate(df.toDateTimeStringISO(dtEnd.toDate()));\n \n // iterate through the stations and check the altitudes by their profiles\n for (int j = 0; j < tsStationList.size(); j++) {\n StationProfileFeature profile = tsProfileData.getStationProfileFeature(tsStationList.get(j));\n double altmin = Double.POSITIVE_INFINITY;\n double altmax = Double.NEGATIVE_INFINITY;\n List<Double> altVals = new ArrayList<Double>();\n for (profile.resetIteration();profile.hasNext();) {\n ProfileFeature nProfile = profile.next();\n for (nProfile.resetIteration();nProfile.hasNext();) {\n PointFeature point = nProfile.next();\n Object heightOb = null;\n if(this.heightAxis != null)\n heightOb = point.getData().getScalarObject(this.heightAxis.getShortName());\n \n double alt;\n if(heightOb != null)\n alt = Double.valueOf(heightOb.toString());\n else\n alt = point.getLocation().getAltitude();\n if (!Double.toString(alt).equalsIgnoreCase(\"nan\")) {\n if (alt > altmax) \n altmax = alt;\n if (alt < altmin) \n altmin = alt;\n if (alt > upperAlt)\n upperAlt = alt;\n if (alt < lowerAlt)\n lowerAlt = alt;\n }\n if(!altVals.contains(alt))\n altVals.add(alt);\n }\n\n }\n this.numberHeightsForStation.put(tsStationList.get(j).getName(), altVals);\n altMin.add(altmin);\n altMax.add(altmax);\n }\n }\n }\n\n \n \n \n @Override\n public void setInitialLatLonBoundaries(List<Station> tsStationList) {\n upperLat = tsStationList.get(0).getLatitude();\n lowerLat = tsStationList.get(0).getLatitude();\n upperLon = tsStationList.get(0).getLongitude();\n lowerLon = tsStationList.get(0).getLongitude();\n }\n\n @Override\n public String getDataResponse(int stNum) {\n try {\n if (tsProfileData != null) {\n return createStationProfileFeature(stNum);\n }\n } catch (IOException ex) {\n Logger.getLogger(TimeSeriesProfile.class.getName()).log(Level.SEVERE, null, ex);\n return DATA_RESPONSE_ERROR + TimeSeries.class;\n }\n return DATA_RESPONSE_ERROR + TimeSeries.class;\n }\n\n @Override\n public String getStationName(int idNum) {\n if (tsProfileData != null && getNumberOfStations() > idNum) {\n \tString statName = tsStationList.get(idNum).getName();\n \tif (statName.isEmpty()){\n \t\t// return generic\n \t\tstatName = this.tsProfileData.getCollectionFeatureType().name()+\"-\"+idNum;\n \t}\n return statName;\n } \n else {\n return Invalid_Station;\n }\n }\n\n @Override\n public double getLowerLat(int stNum) {\n if (tsProfileData != null) {\n return (tsStationList.get(stNum).getLatitude());\n } else {\n return Invalid_Value;\n }\n }\n\n @Override\n public double getLowerLon(int stNum) {\n if (tsProfileData != null) {\n return (tsStationList.get(stNum).getLongitude());\n } else {\n return Invalid_Value;\n }\n }\n\n @Override\n public double getUpperLat(int stNum) {\n if (tsProfileData != null) {\n return (tsStationList.get(stNum).getLatitude());\n } else {\n return Invalid_Value;\n }\n }\n\n @Override\n public double getUpperLon(int stNum) {\n if (tsProfileData != null) {\n return (tsStationList.get(stNum).getLongitude());\n } else {\n return Invalid_Value;\n }\n }\n \n @Override\n public double getLowerAltitude(int stNum) {\n if (altMin != null && altMin.size() > stNum) {\n double retval = altMin.get(stNum);\n if (Double.toString(retval).equalsIgnoreCase(\"nan\"))\n retval = 0;\n return retval;\n } else {\n return Invalid_Value;\n }\n }\n \n @Override\n public double getUpperAltitude(int stNum) {\n if (altMax != null && altMax.size() > stNum) {\n double retval = altMax.get(stNum);\n if (Double.toString(retval).equalsIgnoreCase(\"nan\"))\n retval = 0;\n return retval;\n } else {\n return Invalid_Value;\n }\n }\n\n @Override\n public String getTimeEnd(int stNum) {\n try {\n if (tsProfileData != null) {\n DateTime curTime = null;\n DateTime dtEnd = null;\n StationProfileFeature sPFeature = tsProfileData.getStationProfileFeature(tsStationList.get(stNum));\n List<Date> times = sPFeature.getTimes();\n dtEnd = new DateTime(times.get(0), chrono);\n //check the dates\n for (int j = 0; j < times.size(); j++) {\n curTime = new DateTime(times.get(j), chrono);\n\n if (curTime.isAfter(dtEnd)) {\n dtEnd = curTime;\n }\n }\n return (df.toDateTimeStringISO(dtEnd.toDate()));\n }\n } catch (IOException ex) {\n Logger.getLogger(TimeSeriesProfile.class.getName()).log(Level.SEVERE, null, ex);\n }\n return ERROR_NULL_DATE;\n }\n\n @Override\n public String getTimeBegin(int stNum) {\n try {\n if (tsProfileData != null) {\n DateTime curTime = null;\n DateTime dtStart = null;\n StationProfileFeature sPFeature = tsProfileData.getStationProfileFeature(tsStationList.get(stNum));\n List<Date> times = sPFeature.getTimes();\n dtStart = new DateTime(times.get(0), chrono);\n //check the dates\n for (int j = 0; j < times.size(); j++) {\n curTime = new DateTime(times.get(j), chrono);\n if (curTime.isBefore(dtStart)) {\n dtStart = curTime;\n }\n }\n return (df.toDateTimeStringISO(dtStart.toDate()));\n }\n } catch (IOException ex) {\n Logger.getLogger(TimeSeriesProfile.class.getName()).log(Level.SEVERE, null, ex);\n }\n return ERROR_NULL_DATE;\n }\n\n @Override\n public String getDescription(int stNum) {\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n public List<String> getLocationsString(int stNum) {\n List<String> retval = new ArrayList<String>();\n retval.add(this.getLowerLat(stNum) + \" \" + this.getLowerLon(stNum));\n return retval;\n }\n}", "public abstract class baseCDMClass implements iStationData {\n\n protected double upperLon, lowerLon, lowerLat, upperLat, lowerAlt, upperAlt;\n protected String startDate;\n protected String endDate;\n protected List<String> reqStationNames;\n protected int numberOfStations;\n protected static final String DATA_RESPONSE_ERROR = \"Data Response IO Error: \";\n protected static final String ERROR_NULL_DATE = \"ERROR NULL Date!!!!\";\n protected static final int Invalid_Value = -9999999;\n public static final String STATION_STR = \"station=\";\n public static final String TIME_STR = \"time=\";\n public final static String BIN_STR = \"BIN=\";\n\n protected static final String Invalid_Station = \"INVALID_ST\";\n protected Chronology chrono = ISOChronology.getInstance();\n protected DateFormatter df = new DateFormatter();\n \n protected static org.slf4j.Logger _log = org.slf4j.LoggerFactory.getLogger(baseCDMClass.class);\n \n \n @Override\n public void checkLatLonAltBoundaries(List<Station> stationList, int i) {\n //LAT?LON PARSING\n //lat\n if (stationList.get(i).getLatitude() > upperLat) {\n upperLat = stationList.get(i).getLatitude();\n }\n if (stationList.get(i).getLatitude() < lowerLat) {\n lowerLat = stationList.get(i).getLatitude();\n }\n //lon\n if (stationList.get(i).getLongitude() > upperLon) {\n upperLon = stationList.get(i).getLongitude();\n }\n if (stationList.get(i).getLongitude() < lowerLon) {\n lowerLon = stationList.get(i).getLongitude();\n }\n // alt\n if (stationList.get(i).getAltitude() > upperAlt) {\n upperAlt = stationList.get(i).getAltitude();\n }\n if (stationList.get(i).getAltitude() < lowerAlt) {\n lowerAlt = stationList.get(i).getAltitude();\n }\n }\n\n protected Date getDateForTime(double timeVal, DateUnit dateUnit){\n \tif (Double.isNaN(timeVal)) return null;\n \tdouble secs = dateUnit.getTimeUnit().getValueInSeconds(timeVal); //\n \treturn new Date(Math.round( ((double) dateUnit.getDateOrigin().getTime()+ (1000.0*secs))));\n }\n \n \n @Override\n public List<String> getStationNames() {\n return reqStationNames;\n }\n\n @Override\n public double getBoundUpperLon() {\n return upperLon;\n }\n\n @Override\n public double getBoundUpperLat() {\n return upperLat;\n }\n\n @Override\n public double getBoundLowerLon() {\n return lowerLon;\n }\n\n @Override\n public double getBoundLowerLat() {\n return lowerLat;\n }\n\n @Override\n public String getBoundTimeBegin() {\n return startDate;\n }\n\n @Override\n public String getBoundTimeEnd() {\n return endDate;\n }\n\n @Override\n public void setStartDate(String startDateStr) {\n this.startDate = startDateStr;\n }\n\n @Override\n public void setEndDate(String endDateStr) {\n this.endDate = endDateStr;\n }\n\n @Override\n public void setNumberOfStations(int numOfStations) {\n this.numberOfStations = numOfStations;\n }\n\n @Override\n public int getNumberOfStations() {\n return numberOfStations;\n }\n \n @Override\n public boolean isStationInFinalList(int stNum) {\n return true;\n }\n \n @Override\n public double getLowerAltitude(int stNum) {\n return 0;\n }\n @Override\n public double getUpperAltitude(int stNum) {\n return 0;\n }\n \n @Override\n public double getBoundLowerAlt() {\n if (Double.toString(lowerAlt).contains(\"fin\") || Double.toString(lowerAlt).equalsIgnoreCase(\"nan\"))\n return 0;\n return lowerAlt;\n }\n \n @Override\n public double getBoundUpperAlt() {\n if (Double.toString(lowerAlt).contains(\"fin\") || Double.toString(upperAlt).equalsIgnoreCase(\"nan\"))\n return 0;\n return upperAlt;\n }\n}", "public class GetObservationRequestHandler extends BaseRequestHandler {\n public static final String DEPTH = \"depth\";\n private static final String LAT = \"latitude\";\n private static final String LON = \"longitude\";\n\n public static final String TEXTXML = \"text/xml\";\n\n private String[] obsProperties;\n private String[] procedures;\n private iStationData CDMDataSet;\n private org.slf4j.Logger _log = org.slf4j.LoggerFactory.getLogger(GetObservationRequestHandler.class);\n public static final String FILL_VALUE_NAME = \"_FillValue\";\n public static final String IOOS10_RESPONSE_FORMAT = \"text/xml;subtype=\\\"om/1.0.0/profiles/ioos_sos/1.0\\\"\";\n public static final String OOSTETHYS_RESPONSE_FORMAT = \"text/xml;subtype=\\\"om/1.0.0\\\"\";\n public static final String CSV_RESPONSE_FORMAT = \"text/csv\";\n public static final String JSON_RESPONSE_FORMAT = \"text/json\";\n private final List<String> eventTimes;\n private boolean requestFirstTime;\n private boolean requestLastTime;\n private static final String LATEST_TIME = \"latest\";\n private static final String FIRST_TIME = \"first\";\n private static final String ALL_OBS = \"all\";\n private String latAxisName;\n private String lonAxisName;\n private String depthAxisName;\n /**\n * SOS get obs request handler\n * @param netCDFDataset dataset for which the get observation request is being made\n * @param requestedStationNames collection of offerings from the request\n * @param variableNames collection of observed properties from the request\n * @param eventTime event time range from the request\n * @param responseFormat response format from the request\n * @param latLonRequest map of the latitudes and longitude (points or ranges) from the request\n * @throws Exception \n */\n public GetObservationRequestHandler(NetcdfDataset netCDFDataset,\n String[] requestedProcedures,\n String offering,\n String[] variableNames,\n String[] eventTime,\n String responseFormat,\n Map<String, String> latLonRequest) throws Exception {\n super(netCDFDataset);\n this.requestFirstTime = false;\n this.requestLastTime = false;\n latAxisName = null;\n lonAxisName = null;\n depthAxisName = null;\n eventTimes = setupGetObservation(netCDFDataset,\n requestedProcedures,\n offering,\n variableNames,\n eventTime,\n responseFormat,\n latLonRequest);\n \n }\n\n \n private List<String> setupGetObservation(NetcdfDataset netCDFDataset,\n String[] requestedProcedures,\n String offering,\n String[] variableNames,\n String[] eventTime,\n String responseFormat,\n Map<String, String> latLonRequest) throws Exception{\n List<String> localEventTime = new ArrayList<String>();\n // Translate back to an URN. (gml:id fields in XML can't have colons)\n offering = offering.replace(\"_-_\",\":\");\n offering = URLDecoder.decode(offering,\"UTF-8\");\n responseFormat = URLDecoder.decode(responseFormat,\"UTF-8\");\n\n //Remove any spaces between \";\" and subtype\n responseFormat = responseFormat.replaceAll(\";\\\\s+subtype\",\";subtype\");\n boolean setProcedureFromOffering = false;\n // set up our formatter\n if (responseFormat.equalsIgnoreCase(OOSTETHYS_RESPONSE_FORMAT)) {\n formatter = new OosTethysFormatter(this);\n } \n else if (responseFormat.equalsIgnoreCase(IOOS10_RESPONSE_FORMAT)) {\n formatter = new Ioos10Formatter(this);\n } \n else if (responseFormat.equalsIgnoreCase(CSV_RESPONSE_FORMAT)){\n \tformatter = new CsvFormatter(this);\n }\n else if (responseFormat.equalsIgnoreCase(JSON_RESPONSE_FORMAT)){\n \tformatter = new JsonFormatter(this);\n }\n else {\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"Could not recognize response format: \" + responseFormat, \n INVALID_PARAMETER, \"responseFormat\");\n\n return localEventTime;\n\n }\n\n // Since the obsevedProperties can be standard_name attributes, map everything to an actual variable name here.\n\n String[] actualVariableNames = variableNames.clone();\n\n \n if (variableNames.length == 1 && variableNames[0].equalsIgnoreCase(ALL_OBS)){\n \tSet<String> sensorVar = getSensorNames().keySet();\n \tactualVariableNames = sensorVar.toArray(new String[sensorVar.size()]); \t\n }\n else{\n \t// make sure that all of the requested variable names are in the dataset\n \tfor (int i = 0 ; i < variableNames.length ; i++) {\n \t\tString vars = variableNames[i];\n \t\tboolean isInDataset = false;\n \t\tfor (Variable dVar : netCDFDataset.getVariables()) {\n \t\t\tString dVarFullName = dVar.getFullName();\n \t\t\tString obsUrl = this.getObservedOfferingUrl(dVarFullName);\n \t\t\tAttribute standardAtt = dVar.findAttribute((STANDARD_NAME));\n \t\t\tif (obsUrl != null && obsUrl.equalsIgnoreCase(vars) ) {\n \t\t\t\tisInDataset = true;\n \t\t\t\t// Replace standard_name with the variable name\n \t\t\t\tactualVariableNames[i] = dVarFullName;\n \t\t\t\tbreak;\n \t\t\t}\n \t\t\telse if(standardAtt != null && standardAtt.getStringValue().equals(vars)){\n \t\t\t\tisInDataset = true;\n \t\t\t\t// Replace standard_name with the variable name\n \t\t\t\tactualVariableNames[i] = dVarFullName;\n \t\t\t\tbreak;\n \t\t\t}\n\n \t\t}\n \t\tif (!isInDataset) {\n \t\t\tformatter = new ErrorFormatter();\n \t\t\t((ErrorFormatter)formatter).setException(\"observed property - \" + vars + \n \t\t\t\t\t\" - was not found in the dataset\", INVALID_PARAMETER, \"observedProperty\");\n \t\t\tCDMDataSet = null;\n \t\t\treturn localEventTime;\n \t\t}\n \t}\n }\n CoordinateAxis heightAxis = netCDFDataset.findCoordinateAxis(AxisType.Height);\n\n this.obsProperties = checkNetcdfFileForAxis(heightAxis, actualVariableNames);\n\n // Figure out what procedures to use...\n try {\n if (requestedProcedures == null) {\n if (offering.equalsIgnoreCase(this.getUrnNetworkAll())) {\n // All procedures\n requestedProcedures = getStationNames().values().toArray(new String[getStationNames().values().size()]);\n } else {\n // Just the single procedure supplied by the offering\n requestedProcedures = new String[1];\n requestedProcedures[0] = offering;\n }\n setProcedureFromOffering = true;\n } else {\n if (requestedProcedures.length == 1 && requestedProcedures[0].equalsIgnoreCase(getUrnNetworkAll())) {\n requestedProcedures = getStationNames().values().toArray(new String[getStationNames().values().size()]);\n } else {\n for (int i = 0; i < requestedProcedures.length; i++) {\n requestedProcedures[i] = requestedProcedures[i].substring(requestedProcedures[i].lastIndexOf(\":\") + 1);\n }\n }\n }\n // Now map them all to the station URN\n List<String> naProcs = ListComprehension.map(Arrays.asList(requestedProcedures),\n new ListComprehension.Func<String, String>() {\n public String apply(String in) {\n return getUrnName(in);\n }\n }\n );\n this.procedures = naProcs.toArray(new String[naProcs.size()]);\n } catch (Exception ex) {\n _log.error(ex.toString());\n this.procedures = null;\n }\n\n // check that the procedures are valid\n boolean procedureError = checkProcedureValidity(setProcedureFromOffering);\n if(procedureError)\n return localEventTime;\n // and are a part of the offering\n if (offering != null) {\n checkProceduresAgainstOffering(offering);\n }\n\n if (eventTime != null && eventTime.length > 0) {\n Array timeVals = null;\n DateUnit dateUnit = null;\n for(int eventTimeI = 0; eventTimeI < eventTime.length; eventTimeI++){\n if(eventTime[eventTimeI].equals(LATEST_TIME) ||\n eventTime[eventTimeI].equals(FIRST_TIME)){\n int timeIndex = 0;\n if(timeVals == null)\n timeVals = this.timeVariable.read();\n if(dateUnit == null)\n dateUnit = new DateUnit(timeVariable.getUnitsString());\n if(eventTime[eventTimeI].equals(FIRST_TIME)){\n this.requestFirstTime = true;\n }\n \n if(eventTime[eventTimeI].equals(LATEST_TIME)) {\n timeIndex = (int)timeVals.getSize() - 1;\n this.requestLastTime = true;\n }\n double lastT = timeVals.getDouble(timeIndex);\n eventTime[eventTimeI] = dateUnit.makeStandardDateString(lastT);\n }\n\n }\n\n\n\n if(eventTime.length == 1){\n String currEntry = eventTime[0];\n eventTime = new String[2];\n eventTime[0] = currEntry;\n eventTime[1] = currEntry;\n }\n localEventTime = Arrays.asList(eventTime);\n\n } \n setCDMDatasetForStations(netCDFDataset, eventTime, latLonRequest, heightAxis);\n\n return localEventTime;\n\n }\n \n public boolean is3dGrid(String station){\n \tboolean is3dGrid = false;\n \tif(this.getCDMDataset() instanceof Grid){\n\t\t\tGrid gDs = (Grid) this.getCDMDataset();\n\t\t\tMap<String, String> llrequest = gDs.getLatLonRequest();\n\t\t\tif(!llrequest.containsKey(Grid.DEPTH) || llrequest.get(Grid.DEPTH).split(\",\").length > 1){\n\t\t\t\tis3dGrid = gDs.getGridZIndex(this.getCDMDataset().getStationName(0)) > -1 ? true : false;\n\t\t\t}\n\t\t}\n \treturn is3dGrid;\n }\n \n private void setCDMDatasetForStations(NetcdfDataset netCDFDataset, String[] eventTime, \n Map<String, String> latLonRequest, CoordinateAxis heightAxis) throws IOException {\n // strip out text if the station is defined by indices\n /*\n if (isStationDefinedByIndices()) {\n String[] editedStationNames = new String[requestedStationNames.length];\n for (int i = 0; i < requestedStationNames.length; i++) {\n if (requestedStationNames[i].contains(UNKNOWN)) {\n editedStationNames[i] = UNKNOWN;\n } else {\n editedStationNames[i] = requestedStationNames[i].replaceAll(\"[A-Za-z]+\", \"\");\n }\n }\n // copy array\n requestedStationNames = editedStationNames.clone();\n }\n */\n //grid operation\n if (getDatasetFeatureType() == FeatureType.GRID) {\n\n // Make sure latitude and longitude are specified\n if (!latLonRequest.containsKey(LON)) {\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"No longitude point specified\", MISSING_PARAMETER, \"longitude\");\n CDMDataSet = null;\n return;\n }\n if (!latLonRequest.containsKey(LAT)) {\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"No latitude point specified\", MISSING_PARAMETER, \"latitude\");\n CDMDataSet = null;\n return;\n }\n\n List<String> lats = Arrays.asList(latLonRequest.get(LAT).split(\",\"));\n for (String s : lats) {\n try {\n Double.parseDouble(s);\n } catch (NumberFormatException e) {\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"Invalid latitude specified\", INVALID_PARAMETER, \"latitude\");\n CDMDataSet = null;\n return;\n }\n }\n List<String> lons = Arrays.asList(latLonRequest.get(LON).split(\",\"));\n for (String s : lons) {\n try {\n Double.parseDouble(s);\n } catch (NumberFormatException e) {\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"Invalid longitude specified\", INVALID_PARAMETER, \"longitude\");\n CDMDataSet = null;\n return;\n }\n }\n\n\n Variable depthAxis;\n if (!latLonRequest.isEmpty()) {\n \tList<String> variableNamesNew = new ArrayList<String>();\n variableNamesNew.addAll(Arrays.asList(this.obsProperties));\n depthAxis = netCDFDataset.findCoordinateAxis(AxisType.Height);\n if (depthAxis != null) {\n \tthis.depthAxisName = depthAxis.getFullName();\n this.obsProperties = checkNetcdfFileForAxis((CoordinateAxis1D) depthAxis, this.obsProperties);\n }\n CoordinateAxis lonAxis = netCDFDataset.findCoordinateAxis(AxisType.Lon);\n this.lonAxisName = lonAxis.getFullName();\n this.obsProperties = checkNetcdfFileForAxis(lonAxis, this.obsProperties);\n\n CoordinateAxis latAxis = netCDFDataset.findCoordinateAxis(AxisType.Lat);\n this.latAxisName = latAxis.getFullName();\n this.obsProperties = checkNetcdfFileForAxis(latAxis, this.obsProperties);\n \n CDMDataSet = new Grid(this.procedures, eventTime, this.obsProperties, latLonRequest);\n CDMDataSet.setData(getGridDataset());\n }\n } //if the stations are not of cdm type grid then check to see and set cdm data type \n else {\n FeatureType currType = getDatasetFeatureType();\n String stationsNamesFromUrn[] = new String[this.procedures.length];\n Map<String,String> urnMap = this.getUrnToStationName();\n for(int statI = 0; statI < this.procedures.length; statI++){\n \t\tstationsNamesFromUrn[statI] = urnMap.get(procedures[statI]);\n }\n \n \n if (currType == FeatureType.TRAJECTORY) {\n CDMDataSet = new Trajectory(stationsNamesFromUrn, eventTime, this.obsProperties);\n } else if (currType == FeatureType.STATION) {\n CDMDataSet = new TimeSeries(stationsNamesFromUrn, eventTime, this.obsProperties);\n } else if (currType == FeatureType.STATION_PROFILE) {\n \n CDMDataSet = new TimeSeriesProfile(stationsNamesFromUrn, eventTime, \n this.obsProperties, this.requestFirstTime, this.requestLastTime,\n this.timeVariable.getRank() > 1,\n heightAxis);\n } else if (currType == FeatureType.PROFILE) {\n CDMDataSet = new Profile(stationsNamesFromUrn, eventTime, this.obsProperties);\n } else if (currType == FeatureType.SECTION) {\n CDMDataSet = new Section(stationsNamesFromUrn, eventTime, this.obsProperties);\n } else {\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"NetCDF-Java could not recognize the dataset's FeatureType\");\n CDMDataSet = null;\n return;\n }\n \n //only set the data is it is valid\n CDMDataSet.setData(getFeatureTypeDataSet());\n }\n CoordinateAxis depthAxis = netCDFDataset.findCoordinateAxis(AxisType.Height);\n if (depthAxis != null) \n \tthis.depthAxisName = depthAxis.getFullName();\n CoordinateAxis lonAxis = netCDFDataset.findCoordinateAxis(AxisType.Lon);\n if (lonAxis != null)\n \tthis.lonAxisName = lonAxis.getFullName();\n CoordinateAxis latAxis = netCDFDataset.findCoordinateAxis(AxisType.Lat);\n if(latAxis != null)\n \tthis.latAxisName = latAxis.getFullName();\n }\n\n \n public String getDepthUnits(){\n \tString depthUnits = null;\n \t\n CoordinateAxis depthAxis = netCDFDataset.findCoordinateAxis(AxisType.Height);\n if(depthAxis != null){\n \tdepthUnits = depthAxis.getUnitsString();\n }\n return depthUnits;\n }\n /**\n * checks for the presence of height in the netcdf dataset if it finds it but not in the variables selected it adds it\n * @param Axis the axis being checked\n * @param variableNames1 the observed properties from the request (split)\n * @return updated observed properties (with altitude added, if found)\n */\n private String[] checkNetcdfFileForAxis(CoordinateAxis Axis, String[] variableNames1) {\n if (Axis != null) {\n List<String> variableNamesNew = new ArrayList<String>();\n //check to see if Z present\n boolean foundZ = false;\n for (int i = 0; i < variableNames1.length; i++) {\n String zAvail = variableNames1[i];\n\n if (zAvail.equalsIgnoreCase(Axis.getFullName())) {\n foundZ = true;\n break;\n }\n }\n\n //if it not found add it!\n if (!foundZ && !Axis.getDimensions().isEmpty()) {\n variableNamesNew = new ArrayList<String>();\n variableNamesNew.add(Axis.getFullName());\n\n variableNamesNew.addAll(Arrays.asList(variableNames1));\n variableNames1 = new String[variableNames1.length + 1];\n variableNames1 = (String[]) variableNamesNew.toArray(variableNames1);\n //*******************************\n }\n }\n return variableNames1;\n }\n\n \n\n\n public List<String> getRequestedEventTimes() {\n return this.eventTimes;\n }\n\n /**\n * Gets the dataset wrapped by the cdm feature type giving multiple easy to \n * access functions\n * @return dataset wrapped by iStationData\n */\n public iStationData getCDMDataset() {\n return CDMDataSet;\n }\n\n //<editor-fold defaultstate=\"collapsed\" desc=\"Helper functions for building GetObs XML\">\n /**\n * Looks up a stations index by a string name\n * @param stName the name of the station to look for\n * @return the index of the station (-1 if it does not exist)\n */\n public int getIndexFromStationName(String stName) {\n return getStationIndex(stName);\n }\n\n public String getStationLowerCorner(int relIndex) {\n return formatDegree(CDMDataSet.getLowerLat(relIndex)) + \" \" + formatDegree(CDMDataSet.getLowerLon(relIndex));\n }\n\n public String getStationUpperCorner(int relIndex) {\n return formatDegree(CDMDataSet.getUpperLat(relIndex)) + \" \" + formatDegree(CDMDataSet.getUpperLon(relIndex));\n }\n\n public String getBoundedLowerCorner() {\n return formatDegree(CDMDataSet.getBoundLowerLat()) + \" \" + formatDegree(CDMDataSet.getBoundLowerLon());\n }\n\n public String getBoundedUpperCorner() {\n return formatDegree(CDMDataSet.getBoundUpperLat()) + \" \" + formatDegree(CDMDataSet.getBoundUpperLon());\n }\n\n public String getStartTime(int relIndex) {\n return CDMDataSet.getTimeBegin(relIndex);\n }\n\n public String getEndTime(int relIndex) {\n return CDMDataSet.getTimeEnd(relIndex);\n }\n\n public List<String> getRequestedObservedProperties() {\n CoordinateAxis heightAxis = netCDFDataset.findCoordinateAxis(AxisType.Height);\n CoordinateAxis latAxis = netCDFDataset.findCoordinateAxis(AxisType.Lat);\n CoordinateAxis lonAxis = netCDFDataset.findCoordinateAxis(AxisType.Lon);\n\n List<String> retval = Arrays.asList(obsProperties);\n\n if (heightAxis != null) {\n retval = ListComprehension.filterOut(retval, heightAxis.getShortName());\n }\n if (latAxis != null){\n \tretval = ListComprehension.filterOut(retval, latAxis.getShortName());\n }\n if (lonAxis != null){\n \tretval = ListComprehension.filterOut(retval, lonAxis.getShortName());\n }\n return retval;\n }\n\n public String[] getObservedProperties() {\n return obsProperties;\n }\n\n public String[] getProcedures() {\n return procedures;\n }\n\n public String getUnitsString(String dataVarName) {\n return getUnitsOfVariable(dataVarName);\n }\n\n public String getValueBlockForAllObs(String block, String decimal, String token, int relIndex) {\n _log.info(\"Getting data for index: \" + relIndex);\n String retval = CDMDataSet.getDataResponse(relIndex);\n return retval.replaceAll(\"\\\\.\", decimal).replaceAll(\",\", token).replaceAll(\";\", block);\n }\n //</editor-fold>\n\n public String getFillValue(String obsProp) {\n Attribute[] attrs = getAttributesOfVariable(obsProp);\n for (Attribute attr : attrs) {\n if (attr.getFullNameEscaped().equalsIgnoreCase(FILL_VALUE_NAME)) {\n return attr.getValue(0).toString();\n }\n }\n return \"\";\n }\n\n public boolean hasFillValue(String obsProp) {\n Attribute[] attrs = getAttributesOfVariable(obsProp);\n if (attrs == null) {\n return false;\n }\n for (Attribute attr : attrs) {\n if (attr.getFullNameEscaped().equalsIgnoreCase(FILL_VALUE_NAME)) {\n return true;\n }\n }\n return false;\n\n }\n\n private boolean checkProcedureValidity(boolean procedureSetFromOffering) throws IOException {\n List<String> stProc = new ArrayList<String>();\n boolean errorFound = false;\n stProc.add(this.getUrnNetworkAll());\n for (String stname : this.getStationNames().values()) {\n \tString stationUrn = this.getUrnName(stname);\n for (VariableSimpleIF senVar : this.getSensorNames().values()) {\n stProc.add(this.getSensorUrnName(stationUrn, senVar));\n }\n stProc.add(stationUrn);\n }\n\n for (String proc : this.procedures) {\n if (ListComprehension.filter(stProc, proc).size() < 1) {\n if(procedureSetFromOffering)\n setOfferingException(proc);\n else \n setProcedureException(proc);\n errorFound = true;\n }\n }\n return errorFound;\n }\n\n private void setProcedureException(String proc){\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"Invalid procedure \" + proc + \n \". Check GetCapabilities document for valid procedures.\", INVALID_PARAMETER, \"procedure\");\n }\n \n private void setOfferingException(String offering){\n formatter = new ErrorFormatter();\n ((ErrorFormatter)formatter).setException(\"Offering: \" + offering +\n \" does not exist in the dataset. Check GetCapabilities document for valid offerings.\", \n INVALID_PARAMETER, \"offering\"); \n }\n \n private void checkProceduresAgainstOffering(String offering) throws IOException {\n // if the offering is 'network-all' no error (network-all should have all procedures)\n if (offering.equalsIgnoreCase(this.getUrnNetworkAll())) {\n return;\n }\n // currently in ncSOS the only offerings that exist are network-all and each of the stations\n // in the dataset. So basically we need to check that the offering exists\n // in each of the procedures requested.\n for (String proc : this.procedures) {\n if (!proc.toLowerCase().contains(offering.toLowerCase())) {\n setOfferingException(offering);\n }\n }\n\n }\n\n\n\tpublic String getLatAxisName() {\n\t\treturn latAxisName;\n\t}\n\n\n\tpublic String getLonAxisName() {\n\t\treturn lonAxisName;\n\t}\n\n\n\tpublic String getDepthAxisName() {\n\t\treturn depthAxisName;\n\t}\n}", "public abstract class OutputFormatter {\n protected static final String BLOCK_SEPERATOR = \"\\n\";\n protected static final String TOKEN_SEPERATOR = \",\";\n protected static final String DECIMAL_SEPERATOR = \".\";\n protected Boolean hasError = false;\n /**\n * Writes prepared output to the writer (usually will be a response stream from a http request\n *\n * @param writer the stream where the output will be written to.\n */\n public abstract void writeOutput(Writer writer) throws IOException;\n \n /**\n * The Content-type of this response\n */\n public abstract String getContentType();\n\n \n\n}", "public abstract class BaseRequestHandler {\n public static final String CF_ROLE = \"cf_role\";\n public static final String GRID = \"grid\";\n public static final String GRID_MAPPING = \"grid_mapping\";\n public static final String NAME = \"name\";\n public static final String PROFILE = \"profile\";\n public static final String TRAJECTORY = \"trajectory\";\n public static final String PROFILE_ID = \"profile_id\";\n public static final String TRAJECTORY_ID = \"trajectory_id\";\n public static final String UNKNOWN = \"unknown\";\n public static final String STANDARD_NAME = \"standard_name\";\n public static final String HREF_NO_STANDARD_NAME_URL = \"http://mmisw.org/ont/fake/parameter/\";\n public static final String STATION_URN_BASE = \"urn:ioos:station:\";\n public static final String SENSOR_URN_BASE = \"urn:ioos:sensor:\";\n public static final String NETWORK_URN_BASE = \"urn:ioos:network:\";\n public static final String DEFAULT_NAMING_AUTHORITY = \"ncsos\";\n public static final String STANDARD_NAME_VOCAB =\"standard_name_vocabulary\";\n public static final String PLATFORM_VOCAB = \"platform_vocabulary\";\n public static final String TYPE = \"type\";\n public static final String NETWORK_ALL = \"network-all\";\n public static final String NAMING_AUTHORITY= \"naming_authority\";\n public static final String DISCRIMINANT = \"discriminant\";\n public static final String CELL_METHOD = \"cell_methods\";\n public static final String INTERVAL = \"interval\";\n public static final String VERTICAL_DATUM = \"vertical_datum\";\n public static final String PLATFORM = \"platform\";\n public static final String SHORT_NAME = \"short_name\";\n public static final String IOOS_CODE = \"ioos_code\";\n public static final String INSTRUMENT = \"instrument\";\n public static final String LONG_NAME = \"long_name\";\n private static final NumberFormat FORMAT_DEGREE;\n // list of keywords to filter variables on to remove non-data variables from the list\n private static final String[] NON_DATAVAR_NAMES = { \"rowsize\", \"row_size\", PROFILE, \"info\", \"time\", \"z\", \"alt\", \"height\", \"station_info\" };\n private FeatureDataset featureDataset;\n private FeatureCollection CDMPointFeatureCollection;\n private GridDataset gridDataSet = null;\n \n // Global Attributes\n protected HashMap<String, Object> global_attributes = new HashMap<String, Object>();\n \n // Variables and other information commonly needed\n protected final NetcdfDataset netCDFDataset;\n protected Variable latVariable, lonVariable, timeVariable, depthVariable;\n protected Variable stationVariable;\n private HashMap<Integer, String> stationNames;\n private HashMap<String, String> urnToStationName;\n private HashMap<String, VariableSimpleIF> sensorNames;\n private HashMap<String, Variable> platformVariableMap;\n private HashMap<String, String> gridVariableMap;\n protected boolean isInitialized;\n protected String crsName;\n private boolean crsInitialized;\n // Exception codes - Table 25 of OGC 06-121r3 (OWS Common)\n protected static String INVALID_PARAMETER = \"InvalidParameterValue\";\n protected static String MISSING_PARAMETER = \"MissingParameterValue\";\n protected static String OPTION_NOT_SUPPORTED = \"OptionNotSupported\";\n protected static String OPERATION_NOT_SUPPORTED = \"OperationNotSupported\";\n protected static String VERSION_NEGOTIATION = \"VersionNegotiationFailed\";\n\n\n private org.slf4j.Logger _log = org.slf4j.LoggerFactory.getLogger(BaseRequestHandler.class);\n\n static {\n FORMAT_DEGREE = NumberFormat.getNumberInstance();\n FORMAT_DEGREE.setMinimumFractionDigits(1);\n FORMAT_DEGREE.setMaximumFractionDigits(14);\n }\n private FeatureType dataFeatureType;\n protected OutputFormatter formatter;\n\n /**\n * Takes in a dataset and wraps it based on its feature type.\n * @param netCDFDataset the dataset being acted on\n * @throws IOException\n */\n public BaseRequestHandler(NetcdfDataset netCDFDataset) throws IOException {\n \tthis(netCDFDataset, true);\n }\n \n public BaseRequestHandler(NetcdfDataset netCDFDataset, boolean initialize) throws IOException{\n // check for non-null dataset\n if(netCDFDataset == null) {\n// _log.error(\"received null dataset -- probably exception output\");\n this.netCDFDataset = null;\n return;\n }\n this.crsInitialized = false;\n this.crsName = null;\n this.netCDFDataset = netCDFDataset;\n isInitialized = false;\n if(initialize){\n \tinitializeDataset();\n }\n }\n \n \n /**\n * Returns the 'standard_name' attribute of a variable, if it exists\n * @param varName the name of the variable\n * @return the 'standard_name' if it exists, otherwise \"\"\n */\n public String getVariableStandardName(String varName) {\n return getVariableAttribute(varName, STANDARD_NAME);\n }\n \n \n \n \n /**\n * Returns the 'standard_name' attribute of a variable, if it exists\n * @param varName the name of the variable\n * @return the 'standard_name' if it exists, otherwise \"\"\n */\n public String getVariableAttribute(String varName, String attributeName) {\n String retval = UNKNOWN;\n\n for (Variable var : netCDFDataset.getVariables()) {\n if (varName.equalsIgnoreCase(var.getFullName())) {\n Attribute attr = var.findAttribute(attributeName);\n if (attr != null) {\n retval = attr.getStringValue();\n }\n }\n }\n\n return retval;\n }\n \n public String getObservedOfferingUrl(String variable){\n String sensorDef = getVariableStandardName(variable); \n String hrefUrl = null;\n\n if(sensorDef.equals(UNKNOWN)){\n hrefUrl = HREF_NO_STANDARD_NAME_URL + variable;\n }\n else {\n hrefUrl = getHrefForParameter(sensorDef);\n }\n return hrefUrl;\n }\n \n \n public String getHrefForParameter(String standardName) {\n\n \t String globalStandVocab = this.getGlobalAttributeStr(STANDARD_NAME_VOCAB);\n \t Boolean cfConventions = null;\n \t if(globalStandVocab != null){\n \t\t String cfConv = this.getGlobalAttributeStr(\"Convention\");\n \t\t if(cfConv != null && cfConv.toUpperCase().contains(\"CF\")){\n \t\t\t cfConventions = true;\n \t\t }\n \t }\n \t \n \t return VocabDefinitions.GetDefinitionForParameter(standardName, globalStandVocab, cfConventions);\n\n }\n \n \n \n protected void initializeDataset() throws IOException{\n // get the feature dataset (wraps the dataset in variety of accessor methods)\n findFeatureDataset(FeatureDatasetFactoryManager.findFeatureType(netCDFDataset));\n // verify we could get a dataset (make sure the dataset is CF 1.6 compliant or whatever)\n if (gridDataSet == null && featureDataset == null) {\n _log.error(\"Unknown feature type! \" + FeatureDatasetFactoryManager.findFeatureType(netCDFDataset));\n return;\n }\n // if dataFeatureType is none/null (not GRID) get the point feature collection\n if (dataFeatureType == null || dataFeatureType == FeatureType.NONE) {\n CDMPointFeatureCollection = DiscreteSamplingGeometryUtil.extractFeatureDatasetCollection(featureDataset);\n dataFeatureType = CDMPointFeatureCollection.getCollectionFeatureType();\n\n }\n // find the global attributes\n parseGlobalAttributes();\n // get the station variable and several other bits needed\n findAndParseStationVariable();\n // get sensor Variable names\n parseSensorNames();\n // get Axis vars (location, time, depth)\n latVariable = netCDFDataset.findCoordinateAxis(AxisType.Lat);\n lonVariable = netCDFDataset.findCoordinateAxis(AxisType.Lon);\n timeVariable = netCDFDataset.findCoordinateAxis(AxisType.Time);\n depthVariable = netCDFDataset.findCoordinateAxis(AxisType.Height);\n isInitialized = true;\n }\n /**\n * Attempts to set the feature dataset based on the dataset's FeatureType\n * @param datasetFT The FeatureType of the netcdf dataset, found with the factory manager\n * @throws IOException \n */\n private void findFeatureDataset(FeatureType datasetFT) throws IOException {\n if (datasetFT != null) {\n switch (datasetFT) {\n case STATION_PROFILE:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.STATION_PROFILE, netCDFDataset, null, new Formatter(System.err));\n break;\n case PROFILE:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.PROFILE, netCDFDataset, null, new Formatter(System.err));\n break;\n case STATION:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.STATION, netCDFDataset, null, new Formatter(System.err));\n break;\n case TRAJECTORY:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.TRAJECTORY, netCDFDataset, null, new Formatter(System.err));\n break;\n case SECTION:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.SECTION, netCDFDataset, null, new Formatter(System.err));\n break;\n case POINT:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.POINT, netCDFDataset, null, new Formatter(System.err));\n break;\n case GRID:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.GRID, netCDFDataset, null, new Formatter(System.err));\n gridDataSet = DiscreteSamplingGeometryUtil.extractGridDatasetCollection(featureDataset);\n dataFeatureType = FeatureType.GRID;\n break;\n default:\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.ANY_POINT, netCDFDataset, null, new Formatter(System.err));\n break;\n }\n }\n \n if (featureDataset == null) {\n // attempt to get the dataset from an any_point\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.ANY_POINT, netCDFDataset, null, new Formatter(System.err));\n \n if (featureDataset == null) {\n // null, which means the dataset should be grid...\n featureDataset = FeatureDatasetFactoryManager.wrap(FeatureType.GRID, netCDFDataset, null, new Formatter(System.err));\n gridDataSet = DiscreteSamplingGeometryUtil.extractGridDatasetCollection(featureDataset);\n dataFeatureType = FeatureType.GRID;\n }\n }\n }\n \n /**\n * Finds commonly used global attributes in the netcdf file.\n */\n protected void parseGlobalAttributes() {\n String name = null;\n Object value = null;\n for (Attribute a : this.netCDFDataset.getGlobalAttributes()) {\n name = a.getFullName();\n try {\n value = a.getStringValue().trim();\n } catch(NullPointerException e) {\n try {\n value = a.getNumericValue();\n } catch(Exception ex) {\n continue;\n }\n }\n this.global_attributes.put(name, value);\n }\n // Fill in required naming authority attribute\n if (!this.global_attributes.containsKey(\"naming_authority\") ) {\n this.global_attributes.put(\"naming_authority\", DEFAULT_NAMING_AUTHORITY);\n }\n\n if (this.global_attributes.get(\"naming_authority\").equals(\"\")) {\n this.global_attributes.put(\"naming_authority\", DEFAULT_NAMING_AUTHORITY);\n }\n // Fill in required naming authority attribute\n if (!this.global_attributes.containsKey(\"featureType\")) {\n this.global_attributes.put(\"featureType\", \"UNKNOWN\");\n }\n }\n\n /**\n * Finds the station variable with several approaches\n * 1) Attempts to find a variable with the attribute \"cf_role\"; only the\n * station defining variable should have this attribute\n * 2) Looks for a variable with 'grid' and 'name' in its name; GRID datasets\n * do not have a \"cf_role\" attribute\n * 3) Failing above, will \n * @throws IOException \n */\n private void findAndParseStationVariable() throws IOException {\n // get station var\n // check for station, trajectory, profile and grid station info\n \tVariable cfRole = null;\n \tList<String> platformVars = new ArrayList<String>();\n this.urnToStationName = new HashMap<String, String>();\n this.platformVariableMap = new HashMap<String, Variable>();\n this.gridVariableMap = new HashMap<String, String>();\n\n this.stationNames = new HashMap<Integer, String>();\n for (Variable var : netCDFDataset.getVariables()) {\n // look for cf_role attr\n if (this.stationVariable == null) {\n \t\n for (Attribute attr : var.getAttributes()) {\n \tif(attr.getFullName().equalsIgnoreCase(PLATFORM)) {\n \t\tString platName = attr.getStringValue();\n \t\tif(platName != null){\n \t\t\tfor (String platVarName : platName.split(\",\")){\n \t\t\t\tif(!platformVars.contains(platVarName))\n \t\t\t\t\tplatformVars.add(platVarName);\n \t\t\t}\n \t\t}\n \t\t\n \t}\n if(attr.getFullName().equalsIgnoreCase(CF_ROLE)) {\n cfRole = var;\n }\n }\n }\n // check name for grid data (does not have cf_role)\n String varName = var.getFullName().toLowerCase();\n \n if (dataFeatureType == FeatureType.GRID || (varName.contains(GRID) && varName.contains(NAME))) {\n this.stationVariable = var;\n parseGridIdsToName();\n }\n \n if (this.stationVariable != null)\n break;\n }\n boolean addedStat = false;\n if(platformVars.isEmpty()){\n \tObject plat = this.getGlobalAttribute(PLATFORM);\n \t\tif(plat != null){\n \t\t\tfor (String platVarName : String.valueOf(plat).split(\",\")){\n \t\t\t\tif(!platformVars.contains(platVarName))\n \t\t\t\t\tplatformVars.add(platVarName);\n \t\t\t}\n \t\t}\n }\n if(!platformVars.isEmpty()){\n \t//\n \tint stationIndex = 0;\n\n \tMap<Integer, String> stationNamesForURNMap = new HashMap<Integer, String>();\n \tparsePlatformNames(stationNamesForURNMap);\n\n \tfor (String platformVariableName : platformVars){\n \t\tVariable var = getVariableByName(platformVariableName);\n \t\tString station = null;\n \t\tif(var != null){\n \t\t\tfor(Attribute sname : var.getAttributes()){\n \t\t\t\tif(sname.getFullName().equalsIgnoreCase(SHORT_NAME)){\n \t\t\t\t\tstation = sname.getStringValue();\n \t\t\t\t\tbreak;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n\n \t\tif (var != null && station == null) {\n \t\t\tstation = var.getShortName();\n\n\n \t\t\tstationNames.put(stationIndex, station);\n\n \t\t\tplatformVariableMap.put(station, var);\n \t\t\taddedStat = true;\n\n \t\t\tthis.urnToStationName.put( this.getUrnName(station), stationNamesForURNMap.get(stationIndex));\n \t\t\tstationIndex++;\n \t\t}\n \t}\n }\n \t\n \t\n \n if(!addedStat){\n if(this.stationVariable == null){\n \tif(cfRole != null){\n \t\tthis.stationVariable = cfRole;\n \t\tparsePlatformNames(stationNames);\n \t}\n \telse if (getGridDataset() == null) {\n \t\t// there is no station variable ... add a single station with index 0?\n \t\tparsePlatformNames(stationNames);\n \t}\n \telse {\n \t\tparseGridIdsToName();\n \t}\n }\n \t\tfor(String sName : this.stationNames.values()){\n \t\tthis.urnToStationName.put(this.getUrnName(sName), sName);\n \t\t}\n }\n }\n \n /**\n * Finds all variables that are sensor (data) variables and compiles a list of their names.\n */\n private void parseSensorNames() {\n // find all variables who's not a coordinate axis and does not have 'station' in the name\n this.sensorNames = new HashMap<String, VariableSimpleIF>();\n// getFeatureDataset().getDataVariables();\n for (Iterator<VariableSimpleIF> it = getFeatureDataset().getDataVariables().iterator(); it.hasNext();) {\n VariableSimpleIF var = it.next();\n String name = var.getShortName();\n if (name.equalsIgnoreCase(PROFILE) || name.toLowerCase().contains(\"info\") || name.toLowerCase().contains(\"time\") ||\n name.toLowerCase().contains(\"row\") || name.equalsIgnoreCase(\"z\") || name.equalsIgnoreCase(\"alt\") ||\n name.equalsIgnoreCase(\"height\") ||\n name.equalsIgnoreCase(\"depth\") || name.equalsIgnoreCase(\"lat\") || name.equalsIgnoreCase(\"lon\"))\n \tcontinue;\n else\n this.sensorNames.put(name, var);\n }\n if (this.sensorNames.size() < 1) {\n System.err.println(\"Do not have any sensor names!\");\n }\n }\n\n\n private String getPlatformName(FeatureCollection fc, int index) {\n // If NCJ can't pull out the FC name, we need to populate it with something\n // like TRAJECTORY-0, STATION-0, PROFILE-0\n \tString fcName = fc.getName();\n if (fcName != null && !fcName.equalsIgnoreCase(\"unknown\") && !fcName.isEmpty()) {\n return fc.getName();\n } else {\n return fc.getCollectionFeatureType().name() + \"-\" + index;\n }\n }\n\n /**\n * Add station names to hashmap, indexed.\n * @param npfc The nested point feature collection we're iterating through\n * @param stationIndex Current index of the station\n * @return Next station index\n * @throws IOException \n */\n private int parseNestedCollection(NestedPointFeatureCollection npfc, int stationIndex,\n \t\tMap<Integer,String> stationMap) throws IOException { \n if (npfc.isMultipleNested()) {\n NestedPointFeatureCollectionIterator npfci = npfc.getNestedPointFeatureCollectionIterator(-1);\n while (npfci.hasNext()) {\n NestedPointFeatureCollection n = npfci.next();\n \n stationMap.put(stationIndex, this.getPlatformName(n, stationIndex));\n stationIndex += 1;\n }\n } else {\n PointFeatureCollectionIterator pfci = npfc.getPointFeatureCollectionIterator(-1);\n while (pfci.hasNext()) {\n PointFeatureCollection n = pfci.next();\n stationMap.put(stationIndex, this.getPlatformName(n, stationIndex));\n stationIndex += 1;\n }\n }\n \n return stationIndex;\n }\n \n /**\n * Reads a point feature collection and adds the station name, indexed\n * @param pfc feature collection to read\n * @param stationIndex current station index\n * @return next station index\n * @throws IOException \n */\n private int parsePointFeatureCollectionNames(PointFeatureCollection pfc, \n \t\tint stationIndex, Map<Integer,String> stationMap) throws IOException {\n String name = pfc.getName();\n stationMap.put(stationIndex, name);\n return stationIndex+1;\n }\n \n /**\n * Go through the point feature collection to get the station names.\n * @throws IOException \n */\n private void parsePlatformNames(Map<Integer,String> stationMap) throws IOException {\n int stationIndex = 0;\n if (CDMPointFeatureCollection instanceof PointFeatureCollection) {\n PointFeatureCollection pfc = (PointFeatureCollection) CDMPointFeatureCollection;\n parsePointFeatureCollectionNames(pfc, stationIndex,stationMap);\n } else if (CDMPointFeatureCollection instanceof NestedPointFeatureCollection) {\n NestedPointFeatureCollection npfc = (NestedPointFeatureCollection) CDMPointFeatureCollection;\n parseNestedCollection(npfc, stationIndex,stationMap);\n }\n }\n \n /**\n * Gets a number of stations based on the size of the grid sets.\n */\n private void parseGridIdsToName() {\n \tthis.stationNames = new HashMap<Integer, String>();\n \tGridDataset gd = getGridDataset();\n \tif(gd != null){\n \t\tList<Gridset> gridSets = gd.getGridsets();\n \t\tint i = 0;\n \t\tfor (Gridset gs : gridSets) {\n \t\t\tfor(GridDatatype gridV : gs.getGrids()){\n \t\t\t\tthis.gridVariableMap.put(gridV.getFullName(), \"Grid\"+i);\n \t\t\t}\n \t\t\tthis.stationNames.put(i, \"Grid\"+i);\n \t\t\ti++;\n \t\t}\n \t}\n }\n \n /**\n * Attempts to find the coordinate reference authority\n * @param varName var name to check for crs authority\n * @return the authority name, if there is one\n */\n private String getAuthorityFromVariable(String varName) {\n String retval = null;\n\n Variable crsVar = null;\n for (Variable var : netCDFDataset.getVariables()) {\n if (var.getFullName().equalsIgnoreCase(varName)) {\n crsVar = var;\n break;\n }\n }\n \n if (crsVar != null) {\n for (Attribute attr : crsVar.getAttributes()) {\n if (attr.getName().toLowerCase().contains(\"code\")) {\n retval = attr.getValue(0).toString();\n break;\n }\n }\n }\n \n return retval;\n }\n \n /**\n * Returns the index of the station name\n * @param stationToLookFor the name of the station to find\n * @return the index of the station; -1 if no station with the name exists\n */\n protected int getStationIndex(String stationToLookFor) {\n try {\n if (stationToLookFor == null)\n throw new Exception(\"Looking for null station\");\n // look for the station in the hashmap and return its index\n int retval = -1;\n if (stationNames != null && stationNames.containsValue(stationToLookFor)) {\n int index = 0;\n for (String stationName : stationNames.values()) {\n if (stationToLookFor.equalsIgnoreCase(stationName)) {\n retval = index;\n break;\n }\n index++;\n }\n }\n\n return retval;\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n \n return -1;\n }\n \n /**\n * Get the station names, parsed from a Variable containing \"station\" and \"name\"\n * @return list of station names\n */\n protected HashMap<Integer,String> getStationNames() {\n return this.stationNames;\n }\n \n protected HashMap<String, Variable> getPlatformMap(){\n \treturn this.platformVariableMap;\n }\n public NetcdfDataset getNetCDFDataset() {\n\t\treturn netCDFDataset;\n\t}\n\n\t/**\n * Return the list of sensor names\n * @return string list of sensor names\n */\n protected HashMap<String, VariableSimpleIF> getSensorNames() {\n return this.sensorNames;\n }\n\n public VariableSimpleIF getSensorVariable(String sensorName) {\n return this.sensorNames.get(sensorName);\n }\n\n \n protected HashMap<String, Variable> getPlatformVariableMap() {\n\t\treturn platformVariableMap;\n\t}\n\n\t/**\n * Return the list of sensor names\n * @return string list of sensor names\n */\n protected List<String> getSensorUrns(String stationName) {\n List<String> urnNames = new ArrayList<String>(this.sensorNames.size());\n for (VariableSimpleIF sensorVar : this.sensorNames.values()) {\n urnNames.add(this.getSensorUrnName(stationName, sensorVar));\n }\n return urnNames;\n\n }\n \n \n \n /**\n * \n * @param stationIndex\n * @return \n */\n protected final double[] getStationCoords(int stationIndex) {\n try {\n // get the lat/lon of the station\n if (stationIndex >= 0) {\n double[] coords = new double[] { Double.NaN, Double.NaN };\n \n // find lat/lon values for the station\n coords[0] = latVariable.read().getDouble(stationIndex);\n coords[1] = lonVariable.read().getDouble(stationIndex);\n\n return coords;\n } else {\n return null;\n }\n } catch (Exception e) {\n _log.error(\"exception in getStationCoords \" + e.getMessage());\n return null;\n }\n }\n\n /**\n * Gets the units string of a variable\n * @param varName the name of the variable to look for\n * @return the units string or \"none\" if the variable could not be found\n */\n protected String getUnitsOfVariable(String varName) {\n String units = \"none\";\n if (featureDataset != null) {\n VariableSimpleIF ivar = featureDataset.getDataVariable(varName);\n if(ivar != null){\n \t units = ivar.getUnitsString();\n }\n } else {\n Variable var = netCDFDataset.findVariable(varName);\n if (var != null) {\n \tunits = var.getUnitsString();\n }\n }\n \n return units;\n }\n \n public HashMap<String, String> getUrnToStationName() {\n\t\treturn urnToStationName;\n\t}\n\n\tprotected Attribute[] getAttributesOfVariable(String varName) {\n\t\tVariableSimpleIF var;\n if (featureDataset != null) {\n var = featureDataset.getDataVariable(varName);\n } else {\n var = netCDFDataset.findVariable(varName);\n }\n if (var != null) {\n return var.getAttributes().toArray(new Attribute[var.getAttributes().size()]);\n }\n return null;\n }\n \n /**\n * Attempts to find a variable in the dataset.\n * @param variableName name of the variable\n * @return either the variable if found or null\n */\n public Variable getVariableByName(String variableName) {\n return this.netCDFDataset.findVariable(variableName);\n }\n\n /**\n * Returns the dataset, wrapped according to its feature type\n * @return wrapped dataset\n */\n public FeatureDataset getFeatureDataset() {\n return featureDataset;\n }\n\n /**\n * If the dataset has feature type of Grid, this will return the wrapped dataset\n * @return wrapped dataset\n */\n public GridDataset getGridDataset() {\n return gridDataSet;\n }\n \n /**\n * Returns the OutputFormatter being used by the request.\n * @return OutputFormatter\n */\n public OutputFormatter getOutputFormatter() {\n return formatter;\n }\n\n /**\n * Gets the dataset currently in use\n * @return feature collection dataset\n */\n public FeatureCollection getFeatureTypeDataSet() {\n return CDMPointFeatureCollection;\n }\n\n /**\n * gets the feature type of the dataset in question\n * @return feature type of dataset\n */\n public FeatureType getDatasetFeatureType() {\n return dataFeatureType;\n }\n \n /**\n * Are the station defined by indices rather than names\n * @return T/F\n */\n public boolean isStationDefinedByIndices() {\n return stationVariable != null && stationVariable.getDataType() != DataType.CHAR && stationVariable.getDataType() != DataType.STRING;\n }\n \n /**\n * Get a list of the station variable attributes\n * @return a list of attributes; empty if there is no station var\n */\n public List<Attribute> getStationAttributes() {\n if (stationVariable != null) \n return stationVariable.getAttributes();\n else\n return new ArrayList<Attribute>();\n }\n\n /**\n * Returns the urn of a station\n * @param stationName the station name to add to the name base\n * @return\n */\n public String getUrnName(String stationName) {\n \n \t\n \tif(stationName != null) {\n \t\t// mapping from station to platform.\n \tMap<String,String> urnMap = getUrnToStationName();\n \tfor(String cName : urnMap.keySet()){\n \t\tString val = urnMap.get(cName);\n \t\tif(val != null && val.equals(stationName)){\n \t\t\tstationName = cName;\n \t\t}\n \t}\n \t\tString[] feature_name = stationName.split(\":\");\n \t\tif(this.platformVariableMap != null && this.platformVariableMap.containsKey(stationName) ){\n \t\t\tVariable platformVar = this.platformVariableMap.get(stationName);\n \t\t\tif(platformVar != null){\n \t\t\t\tfor(Attribute att : platformVar.getAttributes()){\n \t\t\t\t\tif(att.getFullName().equalsIgnoreCase(IOOS_CODE)){\n \t\t\t\t\t\treturn att.getStringValue();\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t\telse if(this.gridVariableMap.containsKey(stationName)){\n \t\t\tstationName = this.gridVariableMap.get(stationName);\n \t\t}\n \t\tif (feature_name.length > 1 && feature_name[0].equalsIgnoreCase(\"urn\")) {\n \t\t\t// We already have a URN, so just return it.\n \t\t\treturn stationName;\n \t\t} \n \t}\n \treturn STATION_URN_BASE + this.global_attributes.get(NAMING_AUTHORITY) + \":\" + stationName;\n }\n \n \n\n /**\n * Go from urn to readable name (as in swe2:field name)\n * @param stName\n * @return \n */\n public String stationToFieldName(String stName) {\n // get the gml urn\n String urn = this.getUrnName(stName);\n // split on station/sensor\n String[] urnSplit = urn.split(\"(sensor|station):\");\n // get the last index of split\n urn = urnSplit[urnSplit.length - 1];\n // convert to underscore\n String underScorePattern = \"[\\\\+\\\\-\\\\s:]+\";\n urn = urn.replaceAll(underScorePattern, \"_\");\n return urn.toLowerCase();\n }\n protected Variable getPlatformVariableFromURN(String stationURN){\n \tVariable platformVar = null;\n \tMap<String, Variable> platformMap = this.getPlatformVariableMap();\n\t\tString foundStationName = null;\n\t\t for (String stationName : this.getStationNames().values()) {\n\t if (getUrnName(stationName).equalsIgnoreCase(stationURN) || getUrnNetworkAll().equalsIgnoreCase(stationURN)){\n\t \tfoundStationName = stationName;\n\t \tbreak;\n\t }\n\t\t }\n\t\t if (foundStationName != null)\n\t\t\t platformVar = platformMap.get(foundStationName);\n \treturn platformVar;\n }\n public String getUrnNetworkAll() {\n // returns the network-all urn of the authority\n return NETWORK_URN_BASE + this.global_attributes.get(NAMING_AUTHORITY) + \":all\";\n }\n \n /**\n * Returns a composite string of the sensor urn\n * @param stationName name of the station holding the sensor\n * @param sensorName name of the sensor\n * @return urn of the station/sensor combo\n */\n public String getSensorUrnName(String stationName, VariableSimpleIF sensorVar) {\n \t// mapping from station to platform.\n \tMap<String,String> urnMap = getUrnToStationName();\n \tfor(String cName : urnMap.keySet()){\n \t\tString val = urnMap.get(cName);\n \t\tif(val != null && val.equals(stationName)){\n \t\t\tstationName = cName;\n \t\t}\n \t}\n \tif(this.gridVariableMap != null && this.gridVariableMap.containsKey(stationName)){\n \t\tstationName = this.gridVariableMap.get(stationName);\n \t}\n String[] feature_name = stationName.split(\":\");\n String authority = (String) this.global_attributes.get(NAMING_AUTHORITY);\n if (feature_name.length > 2 && feature_name[0].equalsIgnoreCase(\"urn\")) {\n // We have a station URN, so strip out the name\n stationName = feature_name[feature_name.length - 1];\n authority = feature_name[feature_name.length - 2];\n }\n\n List<Attribute> sensorAtts= sensorVar.getAttributes();\n String stadName = sensorVar.getShortName();\n String discriminant = \"\";\n String optionalArgs = \"\";\n for(Attribute att : sensorAtts){\n \tString attName = att.getShortName();\n \tString attVal = att.getStringValue();\n \tif(attName.equalsIgnoreCase(STANDARD_NAME)){\n \t\tstadName = att.getStringValue();\n \t}\n \telse if(attName.equalsIgnoreCase(DISCRIMINANT)){\n \t\tdiscriminant = \":\" + attVal;\n \t}\n \telse if(attName.equalsIgnoreCase(VERTICAL_DATUM)){\n \t\toptionalArgs += optionalArgs.equals(\"\") ? \"#\" : \";\";\n \t\toptionalArgs += VERTICAL_DATUM + \"=\" + attVal;\n \t}\n \telse if(attName.equalsIgnoreCase(CELL_METHOD)){\n \t\toptionalArgs += optionalArgs.equals(\"\") ? \"#\" : \";\";\n \t\toptionalArgs += CELL_METHOD + \"=\" + attVal;\n \t} \n }\n return SENSOR_URN_BASE + authority + \":\" + stationName + \":\" + stadName + discriminant + optionalArgs;\n }\n\n /**\n * Finds the CRS/SRS authorities used for the data vars. This method reads\n * through variables in a highly inefficient manner, therefore if a method\n * provided by the netcdf-java api is found that provides the same output it\n * should be favored over this.\n * @return an array of crs/srs authorities if there are any; else null\n */\n public String[] getCRSSRSAuthorities() {\n ArrayList<String> returnList = new ArrayList<String>();\n for (VariableSimpleIF var : featureDataset.getDataVariables()) {\n for (Attribute attr : var.getAttributes()) {\n if (attr.getFullName().equalsIgnoreCase(GRID_MAPPING)) {\n String stName = attr.getValue(0).toString();\n String auth = getAuthorityFromVariable(stName);\n if (auth != null && !returnList.contains(auth)) {\n returnList.add(auth);\n }\n }\n }\n }\n if (returnList.size() > 0)\n return returnList.toArray(new String[returnList.size()]);\n else\n return null;\n }\n \n public String getCrsName() {\n if(!this.crsInitialized) {\n String[] crsArray = getCRSSRSAuthorities();\n if (crsArray != null && crsArray[0] != null) {\n crsName = crsArray[0].replace(\"EPSG:\", \"http://www.opengis.net/def/crs/EPSG/0/\");\n } else {\n crsName = \"http://www.opengis.net/def/crs/EPSG/0/4326\";\n }\n this.crsInitialized = true;\n }\n return crsName;\n }\n\n \n /**\n * \n * @return \n */\n public ArrayList<String> getCoordinateNames() {\n ArrayList<String> retval = new ArrayList<String>();\n for (CoordinateTransform ct : netCDFDataset.getCoordinateTransforms()) {\n retval.add(ct.getName());\n }\n return retval;\n }\n\n /**\n * Formats degree, using a number formatter\n * @param degree a number to format to a degree\n * @return the number as a degree\n */\n public static String formatDegree(double degree) {\n return FORMAT_DEGREE.format(degree);\n }\n\n\n public Object getGlobalAttribute(String key, Object fillvalue) {\n if (this.global_attributes.containsKey(key)) {\n return this.global_attributes.get(key);\n } else {\n return fillvalue;\n }\n }\n\n public Object getGlobalAttribute(String key) {\n if (this.global_attributes.containsKey(key)) {\n return this.global_attributes.get(key);\n } else {\n return null;\n }\n }\n \n public String getGlobalAttributeStr(String key) {\n \tObject ob = getGlobalAttribute(key);\n \tString retVal = null;\n \tif (ob != null){\n \t\tretVal = String.valueOf(ob);\n \t}\n \treturn retVal;\n }\n /**\n * Attempts to find an attribute from a given variable\n * @param variable variable to look in for the attribute\n * @param attributeName attribute with value desired\n * @param defaultValue default value if attribute does not exist\n * @return the string value of the attribute if exists otherwise defaultValue\n */\n public static String getValueFromVariableAttribute(VariableSimpleIF variable, String attributeName, String defaultValue) {\n Attribute attr = variable.findAttributeIgnoreCase(attributeName);\n if (attr != null) {\n return attr.getStringValue();\n }\n return defaultValue;\n }\n \n /**\n * Get all of the data variables from the dataset. Removes any axis variables or\n * variables that are not strictly measurements.\n * @return list of variable interfaces\n */\n public List<VariableSimpleIF> getDataVariables() {\n List<VariableSimpleIF> retval = ListComprehension.map(this.featureDataset.getDataVariables(), new ListComprehension.Func<VariableSimpleIF, VariableSimpleIF>() {\n public VariableSimpleIF apply(VariableSimpleIF in) {\n // check for direct name comparisons\n for (String name : NON_DATAVAR_NAMES) {\n String sname = in.getShortName().toLowerCase();\n if (sname.equalsIgnoreCase(name))\n return null;\n }\n return in;\n }\n });\n retval = ListComprehension.filterOut(retval, null);\n // get any ancillary variables from the current data variables\n List<String> ancillaryVariables = ListComprehension.map(retval, new ListComprehension.Func<VariableSimpleIF, String>() {\n public String apply(VariableSimpleIF in) {\n Attribute av = in.findAttributeIgnoreCase(\"ancillary_variables\");\n if (av != null)\n return av.getStringValue();\n return null;\n } \n });\n final List<String> ancillaryVariablesF = ListComprehension.filterOut(ancillaryVariables, null);\n // remove any ancillary variables from the current retval list\n retval = ListComprehension.map(retval, new ListComprehension.Func<VariableSimpleIF, VariableSimpleIF>() {\n public VariableSimpleIF apply(VariableSimpleIF in) {\n List<Boolean> add = ListComprehension.map(ancillaryVariablesF, in, new ListComprehension.Func2P<String, VariableSimpleIF, Boolean>() {\n public Boolean apply(String sin, VariableSimpleIF vin) {\n if (sin.equals(vin.getShortName()))\n return false;\n return true;\n }\n });\n // filter out all of the 'trues' in the list, if there are any 'falses' left, then the\n // variable should not be in the final list\n add = ListComprehension.filterOut(add, true);\n if (add.size() > 0)\n return null;\n \n return in;\n } \n });\n return ListComprehension.filterOut(retval, null);\n }\n\n \n\n}" ]
import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import ucar.nc2.constants.AxisType; import ucar.nc2.dataset.CoordinateAxis; import com.asascience.ncsos.cdmclasses.Grid; import com.asascience.ncsos.cdmclasses.TimeSeriesProfile; import com.asascience.ncsos.cdmclasses.baseCDMClass; import com.asascience.ncsos.go.GetObservationRequestHandler; import com.asascience.ncsos.outputformatter.OutputFormatter; import com.asascience.ncsos.service.BaseRequestHandler; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper;
package com.asascience.ncsos.outputformatter.go; public class JsonFormatter extends OutputFormatter { private GetObservationRequestHandler handler; public JsonFormatter( GetObservationRequestHandler getObservationRequestHandler) { this.handler = getObservationRequestHandler; } public void createDataStructs(Map<String, Map<String, JsonFormatterData>> stationData, Map<String, Integer> stationToNum){ List<String> obsProps = handler.getRequestedObservedProperties();
String time_keyname = baseCDMClass.TIME_STR.replace("=","");
2
olgamiller/SSTVEncoder2
app/src/main/java/om/sstvencoder/Encoder.java
[ "public interface IMode {\n void init();\n\n int getProcessCount();\n\n boolean process();\n\n void finish(boolean cancel);\n}", "public interface IModeInfo {\n int getModeName();\n\n String getModeClassName();\n\n ModeSize getModeSize();\n}", "public final class ModeFactory {\n public static Class<?> getDefaultMode() {\n return Robot36.class;\n }\n\n public static String getDefaultModeClassName() {\n return (new ModeInfo(getDefaultMode())).getModeClassName();\n }\n\n public static IModeInfo[] getModeInfoList() {\n return new IModeInfo[]{\n new ModeInfo(Martin1.class), new ModeInfo(Martin2.class),\n new ModeInfo(PD50.class), new ModeInfo(PD90.class), new ModeInfo(PD120.class),\n new ModeInfo(PD160.class), new ModeInfo(PD180.class),\n new ModeInfo(PD240.class), new ModeInfo(PD290.class),\n new ModeInfo(Scottie1.class), new ModeInfo(Scottie2.class), new ModeInfo(ScottieDX.class),\n new ModeInfo(Robot36.class), new ModeInfo(Robot72.class),\n new ModeInfo(Wraase.class)\n };\n }\n\n public static IModeInfo getModeInfo(Class<?> modeClass) {\n if (!isModeClassValid(modeClass))\n return null;\n\n return new ModeInfo(modeClass);\n }\n\n public static IMode CreateMode(Class<?> modeClass, Bitmap bitmap, IOutput output) {\n Mode mode = null;\n\n if (bitmap != null && output != null && isModeClassValid(modeClass)) {\n ModeSize size = modeClass.getAnnotation(ModeSize.class);\n\n if (bitmap.getWidth() == size.width() && bitmap.getHeight() == size.height()) {\n try {\n Constructor constructor = modeClass.getDeclaredConstructor(Bitmap.class, IOutput.class);\n mode = (Mode) constructor.newInstance(bitmap, output);\n } catch (Exception ignore) {\n }\n }\n }\n\n return mode;\n }\n\n private static boolean isModeClassValid(Class<?> modeClass) {\n return Mode.class.isAssignableFrom(modeClass) &&\n modeClass.isAnnotationPresent(ModeSize.class) &&\n modeClass.isAnnotationPresent(ModeDescription.class);\n }\n}", "public interface IOutput {\n double getSampleRate();\n\n void init(int samples);\n\n void write(double value);\n\n void finish(boolean cancel);\n}", "public final class OutputFactory {\n\n public static IOutput createOutputForSending() {\n double sampleRate = 44100.0;\n return new AudioOutput(sampleRate);\n }\n\n public static IOutput createOutputForSavingAsWave(WaveFileOutputContext context) {\n double sampleRate = 44100.0;\n return new WaveFileOutput(context, sampleRate);\n }\n}", "public class WaveFileOutputContext {\n private ContentResolver mContentResolver;\n private String mFileName;\n private File mFile;\n private Uri mUri;\n private ContentValues mValues;\n\n public WaveFileOutputContext(ContentResolver contentResolver, String fileName) {\n mContentResolver = contentResolver;\n mFileName = fileName;\n mValues = getContentValues(fileName);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)\n mUri = mContentResolver.insert(MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY), mValues);\n else\n mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), mFileName);\n }\n \n private ContentValues getContentValues(String fileName) {\n ContentValues values = new ContentValues();\n values.put(MediaStore.Audio.Media.MIME_TYPE, \"audio/wav\");\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n values.put(MediaStore.Audio.Media.DISPLAY_NAME, fileName);\n values.put(MediaStore.Audio.Media.RELATIVE_PATH, (new File(Environment.DIRECTORY_MUSIC, \"SSTV Encoder\")).getPath());\n values.put(MediaStore.Audio.Media.IS_PENDING, 1);\n } else {\n values.put(MediaStore.Audio.Media.ALBUM, \"SSTV Encoder\");\n values.put(MediaStore.Audio.Media.TITLE, fileName);\n values.put(MediaStore.Audio.Media.IS_MUSIC, true);\n }\n return values;\n }\n\n public String getFileName() {\n return mFileName;\n }\n\n public OutputStream getOutputStream() {\n try {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n return mContentResolver.openOutputStream(mUri);\n } else\n return new FileOutputStream(mFile);\n } catch (Exception ignore) {\n }\n return null;\n }\n\n public void update() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n if (mUri != null && mValues != null) {\n mValues.clear();\n mValues.put(MediaStore.Audio.Media.IS_PENDING, 0);\n mContentResolver.update(mUri, mValues, null, null);\n }\n } else {\n if (mFile != null && mValues != null) {\n mValues.put(MediaStore.Audio.Media.DATA, mFile.toString());\n mUri = mContentResolver.insert(MediaStore.Audio.Media.getContentUriForPath(mFile.getAbsolutePath()), mValues);\n }\n }\n }\n\n public void deleteFile() {\n try {\n if (mFile == null)\n mFile = new File(mUri.getPath());\n mFile.delete();\n } catch (Exception ignore) {\n }\n }\n}" ]
import android.graphics.Bitmap; import java.util.LinkedList; import java.util.List; import om.sstvencoder.ModeInterfaces.IMode; import om.sstvencoder.ModeInterfaces.IModeInfo; import om.sstvencoder.Modes.ModeFactory; import om.sstvencoder.Output.IOutput; import om.sstvencoder.Output.OutputFactory; import om.sstvencoder.Output.WaveFileOutputContext;
/* Copyright 2017 Olga Miller <olga.rgb@gmail.com> 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 om.sstvencoder; // Creates IMode instance class Encoder { private final MainActivityMessenger mMessenger; private final Thread mThread; private Thread mSaveWaveThread; private final List<IMode> mQueue; private final ProgressBarWrapper mProgressBar, mProgressBar2; private boolean mQuit, mStop; private Class<?> mModeClass; Encoder(MainActivityMessenger messenger, ProgressBarWrapper progressBar, ProgressBarWrapper progressBar2) { mMessenger = messenger; mProgressBar = progressBar; mProgressBar2 = progressBar2; mQueue = new LinkedList<>(); mQuit = false; mStop = false; mModeClass = ModeFactory.getDefaultMode(); mThread = new Thread() { @Override public void run() { while (true) { IMode mode; synchronized (this) { while (mQueue.isEmpty() && !mQuit) { try { wait(); } catch (Exception ignore) { } } if (mQuit) return; mStop = false; mode = mQueue.remove(0); } mode.init(); mProgressBar.begin(mode.getProcessCount(), "Sending..."); while (mode.process()) { mProgressBar.step(); synchronized (this) { if (mQuit || mStop) break; } } mode.finish(mStop); mProgressBar.end(); } } }; mThread.start(); } boolean setMode(String className) { try { mModeClass = Class.forName(className); } catch (Exception ignore) { return false; } return true; } IModeInfo getModeInfo() { return ModeFactory.getModeInfo(mModeClass); } IModeInfo[] getModeInfoList() { return ModeFactory.getModeInfoList(); } void play(Bitmap bitmap) {
IOutput output = OutputFactory.createOutputForSending();
3
ofelbaum/spb-transport-app
src/main/java/com/emal/android/transport/spb/activity/SettingsFragment.java
[ "public enum VehicleType {\n BUS(\"vehicle_bus\", \"0\", \"A\", false, Color.BLUE),\n TROLLEY(\"vehicle_trolley\", \"1\", \"Ш\", true, Color.GREEN),\n TRAM(\"vehicle_tram\", \"2\", \"T\", false, Color.RED),\n SHIP(\"vehicle_ship\", \"46\", \"S\", false, Color.YELLOW);\n\n private String code;\n private String id;\n private String letter;\n private boolean upsideDown;\n private int color;\n\n private VehicleType(String code, String id, String letter, boolean upsideDown, int color) {\n this.code = code;\n this.id = id;\n this.letter = letter;\n this.color = color;\n this.upsideDown = upsideDown;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getId() {\n return id;\n }\n\n public String getLetter() {\n return letter;\n }\n\n public int getColor() {\n return color;\n }\n\n public boolean isUpsideDown() {\n return upsideDown;\n }\n\n public static VehicleType getType(String value) {\n if (\"bus\".equals(value)) {\n return BUS;\n }\n if (\"tram\".equals(value)) {\n return TRAM;\n }\n if (\"trolley\".equals(value)) {\n return TROLLEY;\n }\n if (\"ship\".equals(value)) {\n return SHIP;\n }\n throw new IllegalStateException(\"Wrong vehicle type\");\n }\n}", "public class ApplicationParams {\n public static final int SPB_CENTER_LAT_DEF_VALUE = (int) (59.95f * 1E6);\n public static final int SPB_CENTER_LONG_DEF_VALUE = (int) (30.316667f * 1E6);\n\n private static final String TAG = \"ApplicationParams\";\n private SharedPreferences sharedPreferences;\n private boolean showBus = false;\n private boolean showTrolley = false;\n private boolean showTram = false;\n private boolean showShip = false;\n private boolean satView = true;\n private boolean showTraffic = false;\n private MapProviderType mapProviderType;\n private int syncTime = Constants.DEFAULT_SYNC_MS;\n private int zoomSize;\n private GeoPoint homeLocation;\n private GeoPoint lastLocation;\n private Set<String> routesToTrack;\n private Theme theme;\n private int iconSize;\n\n public ApplicationParams(SharedPreferences sharedPreferences) {\n this.sharedPreferences = sharedPreferences;\n this.showBus = sharedPreferences.getBoolean(Constants.SHOW_BUS_FLAG, true);\n this.showTrolley = sharedPreferences.getBoolean(Constants.SHOW_TROLLEY_FLAG, true);\n this.showTram = sharedPreferences.getBoolean(Constants.SHOW_TRAM_FLAG, true);\n this.showShip = sharedPreferences.getBoolean(Constants.SHOW_SHIP_FLAG, true);\n this.showTraffic = sharedPreferences.getBoolean(Constants.SHOW_TRAFFIC_FLAG, false);\n this.syncTime = sharedPreferences.getInt(Constants.SYNC_TIME_FLAG, Constants.DEFAULT_SYNC_MS);\n this.iconSize = sharedPreferences.getInt(Constants.ICON_SIZE_FLAG, Constants.DEFAULT_ICON_SIZE);\n\n Integer homeLat = sharedPreferences.getInt(Constants.HOME_LOC_LAT_FLAG, -1);\n Integer homeLong = sharedPreferences.getInt(Constants.HOME_LOC_LONG_FLAG, -1);\n if (homeLat != -1 && homeLong != -1) {\n this.homeLocation = new GeoPoint(homeLat, homeLong);\n }\n\n Integer currLat = sharedPreferences.getInt(Constants.LAST_LOC_LAT_FLAG, SPB_CENTER_LAT_DEF_VALUE);\n Integer currLong = sharedPreferences.getInt(Constants.LAST_LOC_LONG_FLAG, SPB_CENTER_LONG_DEF_VALUE);\n this.lastLocation = new GeoPoint(currLat, currLong);\n\n this.satView = sharedPreferences.getBoolean(Constants.SAT_VIEW_FLAG, false);\n this.mapProviderType = MapProviderType.getByValue(sharedPreferences.getString(Constants.MAP_PROVIDER_TYPE_FLAG, MapProviderType.GMAPSV2.name()));\n this.zoomSize = sharedPreferences.getInt(Constants.ZOOM_FLAG, Constants.DEFAULT_ZOOM_LEVEL);\n Set<String> stringSet = sharedPreferences.getStringSet(Constants.ROUTES_TO_TRACK, Collections.<String>emptySet());\n this.routesToTrack = new ConcurrentSkipListSet<String>(stringSet);\n this.theme = Theme.valueOf(sharedPreferences.getString(Constants.THEME_FLAG, Theme.HOLO_LIGHT.name()));\n }\n\n public boolean isShowBus() {\n return showBus;\n }\n\n public boolean isShowTrolley() {\n return showTrolley;\n }\n\n public boolean isShowTram() {\n return showTram;\n }\n\n public boolean isShowShip() {\n return showShip;\n }\n\n public boolean isSatView() {\n return satView;\n }\n\n public boolean isShowTraffic() {\n return showTraffic;\n }\n\n public int getSyncTime() {\n return syncTime;\n }\n\n public int getZoomSize() {\n return zoomSize;\n }\n\n public GeoPoint getHomeLocation() {\n return homeLocation;\n }\n\n public GeoPoint getLastLocation() {\n return lastLocation;\n }\n\n public MapProviderType getMapProviderType() {\n return mapProviderType;\n }\n\n public void setShowBus(boolean showBus) {\n this.showBus = showBus;\n }\n\n public void setShowTrolley(boolean showTrolley) {\n this.showTrolley = showTrolley;\n }\n\n public void setShowTram(boolean showTram) {\n this.showTram = showTram;\n }\n\n public void setShowShip(boolean showShip) {\n this.showShip = showShip;\n }\n\n public void setSatView(boolean satView) {\n this.satView = satView;\n }\n\n public void setShowTraffic(boolean showTraffic) {\n this.showTraffic = showTraffic;\n }\n\n public void setMapProviderType(MapProviderType mapProviderType) {\n this.mapProviderType = mapProviderType;\n }\n\n public void setSyncTime(int syncTime) {\n this.syncTime = syncTime;\n }\n\n public void setZoomSize(int zoomSize) {\n this.zoomSize = zoomSize;\n }\n\n public void setHomeLocation(GeoPoint homeLocation) {\n this.homeLocation = homeLocation;\n }\n\n public void setLastLocation(GeoPoint lastLocation) {\n this.lastLocation = lastLocation;\n }\n\n public Set<String> getRoutesToTrack() {\n Log.d(TAG, \"getRoutesToTrack: \" + routesToTrack.getClass().getCanonicalName());\n for (String s : routesToTrack) {\n Log.d(TAG, s);\n }\n return routesToTrack;\n }\n\n public List<VehicleType> getSelectedVehicleTypes() {\n List<VehicleType> list = new ArrayList<VehicleType>();\n if (isShowBus()) {\n list.add(VehicleType.BUS);\n }\n if (isShowTram()) {\n list.add(VehicleType.TRAM);\n }\n if (isShowTrolley()) {\n list.add(VehicleType.TROLLEY);\n }\n if (isShowShip()) {\n list.add(VehicleType.SHIP);\n }\n\n return list;\n }\n\n public Theme getTheme() {\n return theme;\n }\n\n public void setTheme(Theme theme) {\n this.theme = theme;\n }\n\n public int getIconSize() {\n return iconSize;\n }\n\n public void setIconSize(int iconSize) {\n this.iconSize = iconSize;\n }\n\n public void saveAll() {\n SharedPreferences.Editor editor = sharedPreferences.edit();\n editor.putInt(Constants.SYNC_TIME_FLAG, syncTime);\n editor.putString(Constants.MAP_PROVIDER_TYPE_FLAG, mapProviderType.name());\n editor.putBoolean(Constants.SHOW_BUS_FLAG, Boolean.TRUE.equals(showBus));\n editor.putBoolean(Constants.SHOW_TRAM_FLAG, Boolean.TRUE.equals(showTram));\n editor.putBoolean(Constants.SHOW_TROLLEY_FLAG, Boolean.TRUE.equals(showTrolley));\n editor.putBoolean(Constants.SHOW_SHIP_FLAG, Boolean.TRUE.equals(showShip));\n editor.putBoolean(Constants.SHOW_TRAFFIC_FLAG, Boolean.TRUE.equals(showTraffic));\n editor.putBoolean(Constants.SAT_VIEW_FLAG, Boolean.TRUE.equals(satView));\n editor.putInt(Constants.LAST_LOC_LAT_FLAG, lastLocation.getLatitudeE6());\n editor.putInt(Constants.LAST_LOC_LONG_FLAG, lastLocation.getLongitudeE6());\n if (homeLocation != null) {\n editor.putInt(Constants.HOME_LOC_LAT_FLAG, homeLocation.getLatitudeE6());\n editor.putInt(Constants.HOME_LOC_LONG_FLAG, homeLocation.getLongitudeE6());\n } else {\n editor.remove(Constants.HOME_LOC_LAT_FLAG);\n editor.remove(Constants.HOME_LOC_LONG_FLAG);\n }\n editor.putInt(Constants.ZOOM_FLAG, zoomSize);\n editor.putInt(Constants.ICON_SIZE_FLAG, iconSize);\n editor.putStringSet(Constants.ROUTES_TO_TRACK, routesToTrack);\n editor.putString(Constants.THEME_FLAG, theme.name());\n\n Log.d(TAG, \"Saving app prefs: \" + this);\n\n editor.commit();\n\n }\n\n public void resetVehicles() {\n showBus = false;\n showShip = false;\n showTram = false;\n showTrolley = false;\n }\n\n public void setLastLocation(LatLng location) {\n GeoPoint geoPoint = new GeoPoint((int)(location.latitude * 1E6), (int)(location.longitude * 1E6));\n setLastLocation(geoPoint);\n }\n\n @Override\n public String toString() {\n return \"ApplicationParams{\" +\n \"showBus=\" + showBus +\n \", showTrolley=\" + showTrolley +\n \", showTram=\" + showTram +\n \", showShip=\" + showShip +\n \", satView=\" + satView +\n \", mapProviderType=\" + mapProviderType +\n \", syncTime=\" + syncTime +\n \", zoomSize=\" + zoomSize +\n \", homeLocation=\" + homeLocation +\n \", lastLocation=\" + lastLocation +\n '}';\n }\n}", "public enum Theme {\n HOLO_BLACK(android.R.style.Theme_Holo),\n HOLO_LIGHT(android.R.style.Theme_Holo_Light);\n private int code;\n\n Theme(int code) {\n this.code = code;\n }\n\n public int getCode() {\n return code;\n }\n}", "public final class Constants {\n public static final String URL_TEMPLATE = \"http://transport.orgp.spb.ru/cgi-bin/mapserv?TRANSPARENT=TRUE&FORMAT=image%2Fpng&MAP=vehicle_typed.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&SRS=EPSG%3A900913&_OLSALT=0.1508798657450825\";\n public static final String URL_PARAMS = \"&LAYERS=%s&BBOX=%s&WIDTH=%d&HEIGHT=%d\";\n public static final String SHOW_BUS_FLAG = \"SHOW_BUS_FLAG\";\n public static final String SHOW_TROLLEY_FLAG = \"SHOW_TROLLEY_FLAG\";\n public static final String SHOW_TRAM_FLAG = \"SHOW_TRAM_FLAG\";\n public static final String SHOW_SHIP_FLAG = \"SHOW_SHIP_FLAG\";\n public static final String SAT_VIEW_FLAG = \"SAT_VIEW_FLAG\";\n public static final String SHOW_TRAFFIC_FLAG = \"SHOW_TRAFFIC_FLAG\";\n public static final String MAP_PROVIDER_TYPE_FLAG = \"MAP_PROVIDER_TYPE_FLAG\";\n public static final String SYNC_TIME_FLAG = \"SYNC_TIME_FLAG\";\n public static final String ZOOM_FLAG = \"ZOOM_FLAG\";\n public static final String HOME_LOC_LONG_FLAG = \"HOME_LOCATION_LONG_FLAG\";\n public static final String HOME_LOC_LAT_FLAG = \"HOME_LOCATION_LAT_FLAG\";\n public static final String LAST_LOC_LONG_FLAG = \"LAST_LOC_LONG_FLAG\";\n public static final String LAST_LOC_LAT_FLAG = \"LAST_LOC_LAT_FLAG\";\n public static final String APP_SHARED_SOURCE = \"SPB_TRANSPORT_APP\";\n public static final int DEFAULT_ZOOM_LEVEL = 15;\n public static final int MS_IN_SEC = 1000;\n public static final int DEFAULT_SYNC_MS = 10000;\n public static final String ROUTES_TO_TRACK = \"ROUTES_TO_TRACK\";\n public static final String THEME_FLAG = \"THEME_FLAG\";\n public static final String ICON_SIZE_FLAG = \"ICON_SIZE_FLAG\";\n public static final int DEFAULT_ICON_SIZE = 5;\n}", "public abstract class LoadAddressTask extends AsyncTask<Object, Void, String> {\n private static final String TAG = LoadAddressTask.class.getName();\n private Context context;\n private GeoPoint geoPoint;\n\n public abstract void setValue(String s);\n\n protected LoadAddressTask(Context context, GeoPoint geoPoint) {\n this.context = context;\n this.geoPoint = geoPoint;\n }\n\n @Override\n protected String doInBackground(Object... params) {\n String myPlaceString = context.getResources().getString(R.string.notfound);\n Geocoder geo = new Geocoder(context);\n try {\n List<Address> myAddrs = geo.getFromLocation(geoPoint.getLatitudeE6() / 1E6, geoPoint.getLongitudeE6() / 1E6, 1);\n if (myAddrs.size() > 0) {\n Address myPlace = myAddrs.get(0);\n Log.d(TAG, \"My Place selected: \" + GeoConverter.convert(myPlace));\n myPlaceString = GeoConverter.convert(myPlace);\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n return myPlaceString;\n }\n }\n\n @Override\n protected void onPostExecute(String s) {\n setValue(s);\n }\n}", "public class SeekBarDialogPreference extends DialogPreference {\n private static final int DEFAULT_MIN_PROGRESS = 0;\n private static final int DEFAULT_MAX_PROGRESS = 100;\n private static final int DEFAULT_PROGRESS = 0;\n\n private int mMinProgress;\n private int mMaxProgress;\n private int mProgress;\n private CharSequence mProgressTextSuffix;\n private TextView mProgressText;\n private SeekBar mSeekBar;\n\n public SeekBarDialogPreference(Context context) {\n this(context, null);\n }\n\n public SeekBarDialogPreference(Context context, AttributeSet attrs) {\n super(context, attrs);\n\n // get attributes specified in XML\n TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SeekBarDialogPreference, 0, 0);\n try {\n setMinProgress(a.getInteger(R.styleable.SeekBarDialogPreference_min, DEFAULT_MIN_PROGRESS));\n setMaxProgress(a.getInteger(R.styleable.SeekBarDialogPreference_android_max, DEFAULT_MAX_PROGRESS));\n setProgressTextSuffix(a.getString(R.styleable.SeekBarDialogPreference_progressTextSuffix));\n } finally {\n a.recycle();\n }\n\n // set layout\n setDialogLayoutResource(R.layout.preference_seek_bar_dialog);\n setPositiveButtonText(android.R.string.ok);\n setNegativeButtonText(android.R.string.cancel);\n setDialogIcon(null);\n }\n\n @Override\n protected void onSetInitialValue(boolean restore, Object defaultValue) {\n setProgress(restore ? getPersistedInt(DEFAULT_PROGRESS) : (Integer) defaultValue);\n }\n\n @Override\n protected Object onGetDefaultValue(TypedArray a, int index) {\n return a.getInt(index, DEFAULT_PROGRESS);\n }\n\n @Override\n protected void onBindDialogView(View view) {\n super.onBindDialogView(view);\n\n TextView dialogMessageText = (TextView) view.findViewById(R.id.text_dialog_message);\n dialogMessageText.setText(getDialogMessage());\n\n mProgressText = (TextView) view.findViewById(R.id.text_progress);\n\n mSeekBar = (SeekBar) view.findViewById(R.id.seek_bar);\n mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {\n @Override\n public void onStopTrackingTouch(SeekBar seekBar) {\n }\n\n @Override\n public void onStartTrackingTouch(SeekBar seekBar) {\n }\n\n @Override\n public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {\n // update text that displays the current SeekBar progress value\n // note: this does not persist the progress value. that is only ever done in setProgress()\n String progressStr = String.valueOf(progress + mMinProgress);\n mProgressText.setText(mProgressTextSuffix == null ? progressStr : progressStr.concat(mProgressTextSuffix.toString()));\n }\n });\n mSeekBar.setMax(mMaxProgress - mMinProgress);\n mSeekBar.setProgress(mProgress - mMinProgress);\n }\n\n public int getMinProgress() {\n return mMinProgress;\n }\n\n public void setMinProgress(int minProgress) {\n mMinProgress = minProgress;\n setProgress(Math.max(mProgress, mMinProgress));\n }\n\n public int getMaxProgress() {\n return mMaxProgress;\n }\n\n public void setMaxProgress(int maxProgress) {\n mMaxProgress = maxProgress;\n setProgress(Math.min(mProgress, mMaxProgress));\n }\n\n public int getProgress() {\n return mProgress;\n }\n\n public void setProgress(int progress) {\n progress = Math.max(Math.min(progress, mMaxProgress), mMinProgress);\n\n if (progress != mProgress) {\n mProgress = progress;\n persistInt(progress);\n notifyChanged();\n }\n }\n\n public CharSequence getProgressTextSuffix() {\n return mProgressTextSuffix;\n }\n\n public void setProgressTextSuffix(CharSequence progressTextSuffix) {\n mProgressTextSuffix = progressTextSuffix;\n }\n\n @Override\n protected void onDialogClosed(boolean positiveResult) {\n super.onDialogClosed(positiveResult);\n\n // when the user selects \"OK\", persist the new value\n if (positiveResult) {\n int seekBarProgress = mSeekBar.getProgress() + mMinProgress;\n if (callChangeListener(seekBarProgress)) {\n setProgress(seekBarProgress);\n }\n }\n }\n\n @Override\n protected Parcelable onSaveInstanceState() {\n // save the instance state so that it will survive screen orientation changes and other events that may temporarily destroy it\n final Parcelable superState = super.onSaveInstanceState();\n\n // set the state's value with the class member that holds current setting value\n final SavedState myState = new SavedState(superState);\n myState.minProgress = getMinProgress();\n myState.maxProgress = getMaxProgress();\n myState.progress = getProgress();\n\n return myState;\n }\n\n @Override\n protected void onRestoreInstanceState(Parcelable state) {\n // check whether we saved the state in onSaveInstanceState()\n if (state == null || !state.getClass().equals(SavedState.class)) {\n // didn't save the state, so call superclass\n super.onRestoreInstanceState(state);\n return;\n }\n\n // restore the state\n SavedState myState = (SavedState) state;\n setMinProgress(myState.minProgress);\n setMaxProgress(myState.maxProgress);\n setProgress(myState.progress);\n\n super.onRestoreInstanceState(myState.getSuperState());\n }\n\n private static class SavedState extends BaseSavedState {\n int minProgress;\n int maxProgress;\n int progress;\n\n public SavedState(Parcelable superState) {\n super(superState);\n }\n\n public SavedState(Parcel source) {\n super(source);\n\n minProgress = source.readInt();\n maxProgress = source.readInt();\n progress = source.readInt();\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n super.writeToParcel(dest, flags);\n\n dest.writeInt(minProgress);\n dest.writeInt(maxProgress);\n dest.writeInt(progress);\n }\n\n @SuppressWarnings(\"unused\")\n public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {\n @Override\n public SavedState createFromParcel(Parcel in) {\n return new SavedState(in);\n }\n\n @Override\n public SavedState[] newArray(int size) {\n return new SavedState[size];\n }\n };\n }\n}" ]
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.preference.*; import android.util.Log; import com.emal.android.transport.spb.R; import android.os.Bundle; import com.emal.android.transport.spb.VehicleType; import com.emal.android.transport.spb.model.ApplicationParams; import com.emal.android.transport.spb.model.Theme; import com.emal.android.transport.spb.utils.Constants; import com.emal.android.transport.spb.task.LoadAddressTask; import com.emal.android.transport.spb.component.SeekBarDialogPreference; import com.google.android.maps.GeoPoint; import java.util.*;
package com.emal.android.transport.spb.activity; /** * User: alexey.emelyanenko@gmail.com * Date: 5/21/13 12:40 AM */ public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = SettingsFragment.class.getName(); private static final String MAP_SYNC_TIME = "map_sync_time"; private static final String MAP_TYPE = "map_type"; private static final String VEHICLE_TYPES = "vehicle_types"; private static final String MY_PLACE = "my_place"; private static final String MAP_SHOW_TRAFFIC = "map_show_traffic"; private static final String APP_THEME = "app_theme"; private static final String ICON_SIZE = "icon_size"; private ListPreference syncTimePref; private MultiSelectListPreference vehicleTypes; private ListPreference mapTypePref; private ListPreference appTheme;
private ApplicationParams appParams;
1
jbossas/jboss-vfs
src/test/java/org/jboss/test/vfs/util/automount/AutomounterTestCase.java
[ "public abstract class AbstractVFSTest extends BaseTestCase {\n protected TempFileProvider provider;\n\n public AbstractVFSTest(String name) {\n super(name);\n }\n\n protected void setUp() throws Exception {\n super.setUp();\n\n provider = TempFileProvider.create(\"test\", new ScheduledThreadPoolExecutor(2));\n }\n\n protected void tearDown() throws Exception {\n provider.close();\n }\n\n public URL getResource(String name) {\n URL url = super.getResource(name);\n assertNotNull(\"Resource not found: \" + name, url);\n return url;\n }\n\n public VirtualFile getVirtualFile(String name) {\n VirtualFile virtualFile = VFS.getChild(getResource(name).getPath());\n assertTrue(\"VirtualFile does not exist: \" + name, virtualFile.exists());\n return virtualFile;\n }\n\n public List<Closeable> recursiveMount(VirtualFile file) throws IOException {\n ArrayList<Closeable> mounts = new ArrayList<Closeable>();\n\n if (!file.isDirectory() && file.getName().matches(\"^.*\\\\.([EeWwJj][Aa][Rr]|[Zz][Ii][Pp])$\")) { mounts.add(VFS.mountZip(file, file, provider)); }\n\n if (file.isDirectory()) { for (VirtualFile child : file.getChildren()) { mounts.addAll(recursiveMount(child)); } }\n\n return mounts;\n }\n\n protected void assertContentEqual(VirtualFile expected, VirtualFile actual) throws ArrayComparisonFailure, IOException {\n assertArrayEquals(\"Expected content must mach actual content\", getContent(expected), getContent(actual));\n }\n\n protected byte[] getContent(VirtualFile virtualFile) throws IOException {\n InputStream is = virtualFile.openStream();\n return getContent(is);\n }\n\n protected byte[] getContent(InputStream is) throws IOException {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n VFSUtils.copyStreamAndClose(is, bos);\n return bos.toByteArray();\n }\n}", "public final class VirtualFile implements Serializable {\n\n private static final long serialVersionUID = 1L;\n private final String name;\n private final String lcname;\n private final VirtualFile parent;\n private final int hashCode;\n private String pathName;\n\n VirtualFile(String name, VirtualFile parent) {\n this.name = name;\n lcname = name.toLowerCase();\n this.parent = parent;\n int result = parent == null ? 1 : parent.hashCode();\n result = 31 * result + name.hashCode();\n hashCode = result;\n }\n\n /**\n * Get the simple VF name (X.java)\n *\n * @return the simple file name\n */\n public String getName() {\n return name;\n }\n\n /**\n * Get the simple VF name mapped to lowercase (x.java) (used by case-insensitive filesystems like ZIP).\n *\n * @return the lowercase simple file name\n * @deprecated should not be used anymore, as the code is case-sensitive from JBVFS-170\n */\n public String getLowerCaseName() {\n return lcname;\n }\n\n /**\n * Get the absolute VFS full path name (/xxx/yyy/foo.ear/baz.jar/org/jboss/X.java)\n *\n * @return the VFS full path name\n */\n public String getPathName() {\n return getPathName(false);\n }\n\n /**\n * Get the path name relative to a parent virtual file. If the given virtual file is not a parent of\n * this virtual file, then an {@code IllegalArgumentException} is thrown.\n *\n * @param parent the parent virtual file\n * @return the relative path name as a string\n * @throws IllegalArgumentException if the given virtual file is not a parent of this virtual file\n */\n public String getPathNameRelativeTo(VirtualFile parent) throws IllegalArgumentException {\n final StringBuilder builder = new StringBuilder(160);\n getPathNameRelativeTo(parent, builder);\n return builder.toString();\n }\n\n private void getPathNameRelativeTo(VirtualFile parent, StringBuilder builder) {\n if (this.parent == null) {\n throw VFSMessages.MESSAGES.parentIsNotAncestor(parent);\n }\n if (this.equals(parent)) {\n return;\n }\n if (!this.parent.equals(parent)) {\n this.parent.getPathNameRelativeTo(parent, builder);\n builder.append('/');\n }\n builder.append(name);\n }\n\n /**\n * Get the absolute VFS full path name. If this is a URL then directory entries will have a trailing slash.\n *\n * @param url whether or not this path is being used for a URL\n * @return the VFS full path name\n */\n String getPathName(boolean url) {\n if (pathName == null || pathName.isEmpty()) {\n VirtualFile[] path = getParentFiles();\n final StringBuilder builder = new StringBuilder(path.length * 30 + 50);\n for (int i = path.length - 1; i > -1; i--) {\n final VirtualFile parent = path[i].parent;\n if (parent == null) {\n builder.append(path[i].name);\n } else {\n if (parent.parent != null) {\n builder.append('/');\n }\n builder.append(path[i].name);\n }\n }\n pathName = builder.toString();\n }\n // Perhaps this should be cached to avoid the fs stat call?\n return (url && isDirectory()) ? pathName.concat(\"/\") : pathName;\n }\n\n /**\n * When the file was last modified\n *\n * @return the last modified time\n */\n public long getLastModified() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"read\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return AccessController.doPrivileged(\n (PrivilegedAction<Long>) () -> mount.getFileSystem().getLastModified(mount.getMountPoint(), this)\n );\n }\n return mount.getFileSystem().getLastModified(mount.getMountPoint(), this);\n }\n\n /**\n * Get the size\n *\n * @return the size\n */\n public long getSize() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"read\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return AccessController.doPrivileged(\n (PrivilegedAction<Long>) () -> mount.getFileSystem().getSize(mount.getMountPoint(), this)\n );\n }\n return mount.getFileSystem().getSize(mount.getMountPoint(), this);\n }\n\n /**\n * Tests whether the underlying implementation file still exists.\n *\n * @return true if the file exists, false otherwise.\n */\n public boolean exists() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"read\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return AccessController.doPrivileged(\n (PrivilegedAction<Boolean>) () -> mount.getFileSystem().exists(mount.getMountPoint(), this)\n );\n }\n return mount.getFileSystem().exists(mount.getMountPoint(), this);\n }\n\n /**\n * Determines whether this virtual file represents a true root of a file system.\n * On UNIX, there is only one root \"/\". Howevever, on Windows there are an infinite\n * number of roots that correspond to drives, or UNC paths.\n *\n * @return {@code true} if this represents a root.\n */\n public boolean isRoot() {\n return parent == null;\n }\n\n /**\n * Whether it is a simple leaf of the VFS, i.e. whether it can contain other files\n *\n * @return {@code true} if a simple file\n * @deprecated use {@link #isDirectory()} or {@link #isFile()} instead\n */\n @Deprecated\n public boolean isLeaf() {\n return isFile();\n }\n\n /**\n * Determine whether the named virtual file is a plain file.\n *\n * @return {@code true} if it is a plain file, {@code false} otherwise\n */\n public boolean isFile() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"read\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return AccessController.doPrivileged(\n (PrivilegedAction<Boolean>) () -> mount.getFileSystem().isFile(mount.getMountPoint(), this)\n );\n }\n return mount.getFileSystem().isFile(mount.getMountPoint(), this);\n }\n\n /**\n * Determine whether the named virtual file is a directory.\n *\n * @return {@code true} if it is a directory, {@code false} otherwise\n */\n public boolean isDirectory() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"read\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return AccessController.doPrivileged(\n (PrivilegedAction<Boolean>) () -> mount.getFileSystem().isDirectory(mount.getMountPoint(), this)\n );\n }\n return mount.getFileSystem().isDirectory(mount.getMountPoint(), this);\n }\n\n /**\n * Access the file contents.\n *\n * @return an InputStream for the file contents.\n * @throws IOException for any error accessing the file system\n */\n public InputStream openStream() throws IOException {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"read\"));\n }\n if (isDirectory()) {\n return new VirtualJarInputStream(this);\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return doIoPrivileged(() -> mount.getFileSystem().openInputStream(mount.getMountPoint(), this));\n }\n return mount.getFileSystem().openInputStream(mount.getMountPoint(), this);\n }\n\n /**\n * Delete this virtual file\n *\n * @return {@code true} if file was deleted\n */\n public boolean delete() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"delete\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return AccessController.doPrivileged(\n (PrivilegedAction<Boolean>) () -> mount.getFileSystem().delete(mount.getMountPoint(), this)\n );\n }\n return mount.getFileSystem().delete(mount.getMountPoint(), this);\n }\n\n /**\n * Get a physical file for this virtual file. Depending on the underlying file system type, this may simply return\n * an already-existing file; it may create a copy of a file; or it may reuse a preexisting copy of the file.\n * Furthermore, the returned file may or may not have any relationship to other files from the same or any other\n * virtual directory.\n *\n * @return the physical file\n * @throws IOException if an I/O error occurs while producing the physical file\n */\n public File getPhysicalFile() throws IOException {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"getfile\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n if (sm != null) {\n return doIoPrivileged(() -> mount.getFileSystem().getFile(mount.getMountPoint(), this));\n }\n return mount.getFileSystem().getFile(mount.getMountPoint(), this);\n }\n\n private static <T> T doIoPrivileged(PrivilegedExceptionAction<T> action) throws IOException {\n try {\n return AccessController.doPrivileged(action);\n } catch (PrivilegedActionException pe) {\n try {\n throw pe.getException();\n } catch (IOException | RuntimeException e) {\n throw e;\n } catch (Exception e) {\n throw new UndeclaredThrowableException(e);\n }\n }\n }\n\n /**\n * Get a {@code VirtualFile} which represents the parent of this instance.\n *\n * @return the parent or {@code null} if there is no parent\n */\n public VirtualFile getParent() {\n return parent;\n }\n\n /**\n * Get the all the parent files of this virtual file from this file to the root. The leafmost file will be at the\n * start of the array, and the rootmost will be at the end.\n *\n * @return the array of parent files\n */\n public VirtualFile[] getParentFiles() {\n return getParentFiles(0);\n }\n\n /**\n * Get the all the parent files of this virtual file from this file to the root as a list. The leafmost file will be\n * at the start of the list, and the rootmost will be at the end.\n *\n * @return the list of parent files\n */\n public List<VirtualFile> getParentFileList() {\n return Arrays.asList(getParentFiles());\n }\n\n private VirtualFile[] getParentFiles(int idx) {\n final VirtualFile[] array;\n if (parent == null) {\n array = new VirtualFile[idx + 1];\n } else {\n array = parent.getParentFiles(idx + 1);\n }\n array[idx] = this;\n return array;\n }\n\n /**\n * Get the children. This is the combined list of real children within this directory, as well as virtual children\n * created by submounts.\n *\n * @return the children\n */\n public List<VirtualFile> getChildren() {\n // isDirectory does the read security check\n if (!isDirectory()) { return Collections.emptyList(); }\n final VFS.Mount mount = VFS.getMount(this);\n final Set<String> submounts = VFS.getSubmounts(this);\n final List<String> names = mount.getFileSystem().getDirectoryEntries(mount.getMountPoint(), this);\n final List<VirtualFile> virtualFiles = new ArrayList<VirtualFile>(names.size() + submounts.size());\n for (String name : names) {\n final VirtualFile child = new VirtualFile(name, this);\n virtualFiles.add(child);\n submounts.remove(name);\n }\n for (String name : submounts) {\n final VirtualFile child = new VirtualFile(name, this);\n virtualFiles.add(child);\n }\n return virtualFiles;\n }\n\n /**\n * Get the children\n *\n * @param filter to filter the children\n * @return the children\n * @throws IOException for any problem accessing the virtual file system\n * @throws IllegalStateException if the file is closed or it is a leaf node\n */\n public List<VirtualFile> getChildren(VirtualFileFilter filter) throws IOException {\n // isDirectory does the read security check\n if (!isDirectory()) { return Collections.emptyList(); }\n if (filter == null) { filter = MatchAllVirtualFileFilter.INSTANCE; }\n FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor(filter, null);\n visit(visitor);\n return visitor.getMatched();\n }\n\n /**\n * Get all the children recursively<p>\n * <p/>\n * This always uses {@link VisitorAttributes#RECURSE}\n *\n * @return the children\n * @throws IOException for any problem accessing the virtual file system\n * @throws IllegalStateException if the file is closed\n */\n public List<VirtualFile> getChildrenRecursively() throws IOException {\n return getChildrenRecursively(null);\n }\n\n /**\n * Get all the children recursively<p>\n * <p/>\n * This always uses {@link VisitorAttributes#RECURSE}\n *\n * @param filter to filter the children\n * @return the children\n * @throws IOException for any problem accessing the virtual file system\n * @throws IllegalStateException if the file is closed or it is a leaf node\n */\n public List<VirtualFile> getChildrenRecursively(VirtualFileFilter filter) throws IOException {\n // isDirectory does the read security check\n if (!isDirectory()) { return Collections.emptyList(); }\n if (filter == null) { filter = MatchAllVirtualFileFilter.INSTANCE; }\n FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor(filter, VisitorAttributes.RECURSE);\n visit(visitor);\n return visitor.getMatched();\n }\n\n /**\n * Visit the virtual file system\n *\n * @param visitor the visitor\n * @throws IOException for any problem accessing the virtual file system\n * @throws IllegalArgumentException if the visitor is null\n * @throws IllegalStateException if the file is closed\n */\n public void visit(VirtualFileVisitor visitor) throws IOException {\n visit(visitor, true);\n }\n\n private void visit(VirtualFileVisitor visitor, boolean root) throws IOException {\n final VisitorAttributes visitorAttributes = visitor.getAttributes();\n if (root && visitorAttributes.isIncludeRoot()) { visitor.visit(this); }\n // isDirectory does the read security check\n if (!isDirectory()) { return; }\n for (VirtualFile child : getChildren()) {\n // Always visit a leaf, and visit directories when leaves only is false\n if (!child.isDirectory() || !visitorAttributes.isLeavesOnly()) { visitor.visit(child); }\n if (child.isDirectory() && visitorAttributes.isRecurse(child)) { child.visit(visitor, false); }\n }\n }\n\n /**\n * Get a child virtual file. The child may or may not exist in the virtual filesystem.\n *\n * @param path the path\n * @return the child\n * @throws IllegalArgumentException if the path is null\n */\n public VirtualFile getChild(String path) {\n if (path == null) {\n throw VFSMessages.MESSAGES.nullArgument(\"path\");\n }\n final List<String> pathParts = PathTokenizer.getTokens(path);\n VirtualFile current = this;\n for (String part : pathParts) {\n if (PathTokenizer.isReverseToken(part)) {\n final VirtualFile parent = current.parent;\n current = parent == null ? current : parent;\n } else if (PathTokenizer.isCurrentToken(part) == false) {\n current = new VirtualFile(part, current);\n }\n }\n return current;\n }\n\n /**\n * Get file's current URL. <b>Note:</b> if this VirtualFile refers to a directory <b>at the time of this\n * method invocation</b>, a trailing slash will be appended to the URL; this means that invoking\n * this method may require a filesystem access, and in addition, may not produce consistent results\n * over time.\n *\n * @return the current url\n * @throws MalformedURLException if the URL is somehow malformed\n * @see VirtualFile#asDirectoryURL()\n * @see VirtualFile#asFileURL()\n */\n public URL toURL() throws MalformedURLException {\n return VFSUtils.getVirtualURL(this);\n }\n\n /**\n * Get file's current URI. <b>Note:</b> if this VirtualFile refers to a directory <b>at the time of this\n * method invocation</b>, a trailing slash will be appended to the URI; this means that invoking\n * this method may require a filesystem access, and in addition, may not produce consistent results\n * over time.\n *\n * @return the current uri\n * @throws URISyntaxException if the URI is somehow malformed\n * @see VirtualFile#asDirectoryURI()\n * @see VirtualFile#asFileURI()\n */\n public URI toURI() throws URISyntaxException {\n return VFSUtils.getVirtualURI(this);\n }\n\n /**\n * Get file's URL as a directory. There will always be a trailing {@code \"/\"} character.\n *\n * @return the url\n * @throws MalformedURLException if the URL is somehow malformed\n */\n public URL asDirectoryURL() throws MalformedURLException {\n final String pathName = getPathName(false);\n return new URL(VFSUtils.VFS_PROTOCOL, \"\", -1, parent == null ? pathName : pathName + \"/\", VFSUtils.VFS_URL_HANDLER);\n }\n\n /**\n * Get file's URI as a directory. There will always be a trailing {@code \"/\"} character.\n *\n * @return the uri\n * @throws URISyntaxException if the URI is somehow malformed\n */\n public URI asDirectoryURI() throws URISyntaxException {\n final String pathName = getPathName(false);\n return new URI(VFSUtils.VFS_PROTOCOL, \"\", parent == null ? pathName : pathName + \"/\", null);\n }\n\n /**\n * Get file's URL as a file. There will be no trailing {@code \"/\"} character unless this {@code VirtualFile}\n * represents a root.\n *\n * @return the url\n * @throws MalformedURLException if the URL is somehow malformed\n */\n public URL asFileURL() throws MalformedURLException {\n return new URL(VFSUtils.VFS_PROTOCOL, \"\", -1, getPathName(false), VFSUtils.VFS_URL_HANDLER);\n }\n\n /**\n * Get file's URI as a file. There will be no trailing {@code \"/\"} character unless this {@code VirtualFile}\n * represents a root.\n *\n * @return the url\n * @throws URISyntaxException if the URI is somehow malformed\n */\n public URI asFileURI() throws URISyntaxException {\n return new URI(VFSUtils.VFS_PROTOCOL, \"\", getPathName(false), null);\n }\n\n /**\n * Get the {@link CodeSigner}s for a the virtual file.\n *\n * @return the {@link CodeSigner}s for the virtual file, or {@code null} if not signed\n */\n public CodeSigner[] getCodeSigners() {\n final SecurityManager sm = System.getSecurityManager();\n if (sm != null) {\n sm.checkPermission(new VirtualFilePermission(getPathName(), \"read\"));\n }\n final VFS.Mount mount = VFS.getMount(this);\n return mount.getFileSystem().getCodeSigners(mount.getMountPoint(), this);\n }\n\n /**\n * Get the {@link Certificate}s for the virtual file. Simply extracts the certificate entries from\n * the code signers array.\n *\n * @return the certificates for the virtual file, or {@code null} if not signed\n */\n public Certificate[] getCertificates() {\n // getCodeSigners() does the sec check\n final CodeSigner[] codeSigners = getCodeSigners();\n if (codeSigners == null) {\n return null;\n }\n final List<Certificate> certList = new ArrayList<Certificate>(codeSigners.length * 3);\n for (CodeSigner signer : codeSigners) {\n certList.addAll(signer.getSignerCertPath().getCertificates());\n }\n return certList.toArray(new Certificate[certList.size()]);\n }\n\n /**\n * Get a human-readable (but non-canonical) representation of this virtual file.\n *\n * @return the string\n */\n public String toString() {\n return '\"' + getPathName() + '\"';\n }\n\n /**\n * Determine whether the given object is equal to this one. Returns true if the argument is a {@code VirtualFile}\n * from the same {@code VFS} instance with the same name.\n *\n * @param o the other object\n * @return {@code true} if they are equal\n */\n public boolean equals(Object o) {\n return o instanceof VirtualFile && equals((VirtualFile) o);\n }\n\n /**\n * Determine whether the given object is equal to this one. Returns true if the argument is a {@code VirtualFile}\n * from the same {@code VFS} instance with the same name.\n *\n * @param o the other virtual file\n * @return {@code true} if they are equal\n */\n public boolean equals(VirtualFile o) {\n if (o == this) {\n return true;\n }\n if (o == null || hashCode != o.hashCode || !name.equals(o.name)) {\n return false;\n }\n final VirtualFile parent = this.parent;\n final VirtualFile oparent = o.parent;\n return parent != null && parent.equals(oparent) || oparent == null;\n }\n\n /**\n * Get a hashcode for this virtual file.\n *\n * @return the hash code\n */\n public int hashCode() {\n return hashCode;\n }\n}", "public class Automounter {\n /* Root entry in the tree. */\n private static final RegistryEntry rootEntry = new RegistryEntry();\n\n /* Map of owners and their references */\n private static final ConcurrentMap<MountOwner, Set<RegistryEntry>> ownerReferences = new ConcurrentHashMap<MountOwner, Set<RegistryEntry>>();\n\n /* Provider of temp files/directories*/\n private static TempFileProvider tempFileProvider;\n\n /**\n * Private constructor\n */\n private Automounter() {\n }\n\n /**\n * Mount provided {@link VirtualFile} (if not mounted) and set the owner to be the provided target. (Self owned mount)\n *\n * @param target VirtualFile to mount\n * @param mountOptions optional configuration to use for mounting\n * @throws IOException when the target can not be mounted.\n */\n public static void mount(VirtualFile target, MountOption... mountOptions) throws IOException {\n mount(new VirtualFileOwner(target), target, mountOptions);\n }\n\n /**\n * Mount provided {@link VirtualFile} (if not mounted) and add an owner entry. Also creates a back-reference to from the owner to the target.\n *\n * @param owner Object that owns the reference to the mount\n * @param target VirtualFile to mount\n * @param mountOptions optional configuration to use for mounting\n * @throws IOException when the target can not be mounted.\n */\n public static void mount(Object owner, VirtualFile target, MountOption... mountOptions) throws IOException {\n mount(new SimpleMountOwner(owner), target, mountOptions);\n }\n\n /**\n * Mount provided {@link VirtualFile} (if not mounted) and add an owner entry. Also creates a back-reference to from the owner to the target.\n *\n * @param owner VirtualFile that owns the reference to the mount\n * @param target VirtualFile to mount\n * @param mountOptions optional configuration to use for mounting\n * @throws IOException when the target can not be mounted.\n */\n public static void mount(VirtualFile owner, VirtualFile target, MountOption... mountOptions) throws IOException {\n mount(new VirtualFileOwner(owner), target, mountOptions);\n }\n\n /**\n * Mount provided {@link VirtualFile} (if not mounted) and add an owner entry. Also creates a back-reference to from the owner to the target.\n *\n * @param owner MountOwner that owns the reference to the mount\n * @param target VirtualFile to mount\n * @param mountOptions optional configuration to use for mounting\n * @throws IOException when the target can not be mounted\n */\n public static void mount(MountOwner owner, VirtualFile target, MountOption... mountOptions) throws IOException {\n final RegistryEntry targetEntry = getEntry(target);\n targetEntry.mount(target, getMountConfig(mountOptions));\n targetEntry.inboundReferences.add(owner);\n ownerReferences.putIfAbsent(owner, new HashSet<RegistryEntry>());\n ownerReferences.get(owner).add(targetEntry);\n }\n\n /**\n * Creates a MountConfig and applies the provided mount options\n *\n * @param mountOptions options to use for mounting\n * @return a MountConfig\n */\n private static MountConfig getMountConfig(MountOption[] mountOptions) {\n final MountConfig config = new MountConfig();\n for (MountOption option : mountOptions) {\n option.applyTo(config);\n }\n return config;\n }\n\n /**\n * Add handle to owner, to be auto closed.\n *\n * @param owner the handle owner\n * @param handle the handle\n * @return add result\n */\n public static boolean addHandle(VirtualFile owner, Closeable handle) {\n RegistryEntry entry = getEntry(owner);\n return entry.handles.add(handle);\n }\n\n /**\n * Remove handle from owner.\n *\n * @param owner the handle owner\n * @param handle the handle\n * @return remove result\n */\n public static boolean removeHandle(VirtualFile owner, Closeable handle) {\n RegistryEntry entry = getEntry(owner);\n return entry.handles.remove(handle);\n }\n\n /**\n * Cleanup all references from the owner. Cleanup any mounted entries that become un-referenced in the process.\n *\n * @param owner {@link Object} to cleanup references for\n */\n public static void cleanup(Object owner) {\n cleanup(new SimpleMountOwner(owner));\n }\n\n /**\n * Cleanup all references from the owner. Cleanup any mounted entries that become un-referenced in the process.\n *\n * @param owner {@link Object} to cleanup references for\n */\n public static void cleanup(VirtualFile owner) {\n cleanup(new VirtualFileOwner(owner));\n }\n\n /**\n * Cleanup all references from the {@link MountOwner}. Cleanup any mounted entries that become un-referenced in the process.\n *\n * @param owner {@link MountOwner} to cleanup references for\n */\n public static void cleanup(MountOwner owner) {\n final Set<RegistryEntry> references = ownerReferences.remove(owner);\n if (references != null) {\n for (RegistryEntry entry : references) {\n entry.removeInboundReference(owner);\n }\n }\n owner.onCleanup();\n }\n\n /**\n * Determines whether a target {@link VirtualFile} is mounted.\n *\n * @param target target to check\n * @return true if mounted, false otherwise\n */\n public static boolean isMounted(VirtualFile target) {\n return getEntry(target).isMounted();\n }\n\n /**\n * Get the entry from the tree creating the entry if not present.\n *\n * @param virtualFile entry's owner file\n * @return registry entry\n */\n static RegistryEntry getEntry(VirtualFile virtualFile) {\n if (virtualFile == null) {\n throw MESSAGES.nullArgument(\"VirutalFile\");\n }\n return rootEntry.find(virtualFile);\n }\n\n private static TempFileProvider getTempFileProvider() throws IOException {\n if (tempFileProvider == null) { tempFileProvider = TempFileProvider.create(\"automount\", Executors.newScheduledThreadPool(2)); }\n return tempFileProvider;\n }\n\n static class RegistryEntry {\n private final ConcurrentMap<String, RegistryEntry> children = new ConcurrentHashMap<String, RegistryEntry>();\n\n private final Set<MountOwner> inboundReferences = new HashSet<MountOwner>();\n\n private final List<Closeable> handles = new LinkedList<Closeable>();\n\n private final AtomicBoolean mounted = new AtomicBoolean();\n\n private void mount(VirtualFile target, MountConfig mountConfig) throws IOException {\n if (mounted.compareAndSet(false, true)) {\n if (target.isFile()) {\n VFSLogger.ROOT_LOGGER.debugf(\"Automounting: %s with options %s\", target, mountConfig);\n\n final TempFileProvider provider = getTempFileProvider();\n if (mountConfig.mountExpanded()) {\n if (mountConfig.copyTarget()) { handles.add(VFS.mountZipExpanded(target, target, provider)); } else {\n handles.add(VFS.mountZipExpanded(target.getPhysicalFile(), target, provider));\n }\n } else {\n if (mountConfig.copyTarget()) { handles.add(VFS.mountZip(target, target, provider)); } else {\n handles.add(VFS.mountZip(target.getPhysicalFile(), target, provider));\n }\n }\n }\n }\n }\n\n private void removeInboundReference(MountOwner owner) {\n inboundReferences.remove(owner);\n if (inboundReferences.isEmpty()) {\n cleanup();\n }\n }\n\n void cleanup() {\n if (mounted.compareAndSet(true, false)) {\n VFSUtils.safeClose(handles);\n handles.clear();\n\n final Collection<RegistryEntry> entries = getEntriesRecursive();\n for (RegistryEntry entry : entries) {\n entry.cleanup();\n }\n }\n }\n\n private boolean isMounted() {\n return mounted.get();\n }\n\n private RegistryEntry find(VirtualFile file) {\n return find(PathTokenizer.getTokens(file.getPathName()));\n }\n\n private RegistryEntry find(List<String> path) {\n if (path.isEmpty()) {\n return this;\n }\n final String current = path.remove(0);\n children.putIfAbsent(current, new RegistryEntry());\n final RegistryEntry childEntry = children.get(current);\n return childEntry.find(path);\n }\n\n private Collection<RegistryEntry> getEntriesRecursive() {\n final List<RegistryEntry> allHandles = new LinkedList<RegistryEntry>();\n collectEntries(this, allHandles);\n return allHandles;\n }\n\n private void collectEntries(RegistryEntry registryEntry, List<RegistryEntry> entries) {\n for (RegistryEntry childEntry : registryEntry.children.values()) {\n collectEntries(childEntry, entries);\n entries.add(childEntry);\n }\n }\n }\n}", "public enum MountOption {\n\n EXPANDED {\n void applyTo(MountConfig config) {\n config.setMountExpanded(true);\n }\n },\n COPY {\n void applyTo(MountConfig config) {\n config.setCopyTarget(true);\n }\n };\n\n /**\n * Each option must apply its custom settings to teh {@link MountConfig}.\n *\n * @param config MountConfig to apply settings to\n */\n abstract void applyTo(MountConfig config);\n}", "public interface MountOwner {\n /**\n * A callback method allowing the mount owner to perform any addition cleanup\n * specific to the owner type.\n */\n void onCleanup();\n}", "public class SimpleMountOwner extends AbstractMountOwner<Object> {\n /**\n * Construct with a new object as the owner\n */\n public SimpleMountOwner() {\n this(new Object());\n }\n\n /**\n * Construct with the provided object as the owner\n *\n * @param object the actual owner\n */\n public SimpleMountOwner(Object owner) {\n super(owner);\n }\n\n /**\n * No-op cleanup method\n */\n @Override\n public void onCleanup() {\n }\n}", "public class VirtualFileOwner extends AbstractMountOwner<VirtualFile> {\n /**\n * Constructed with a {@link VirtualFile} owner\n *\n * @param file the {@link VirtualFile} owning mount references\n */\n public VirtualFileOwner(VirtualFile file) {\n super(file);\n }\n\n /**\n * {@inheritDoc}\n * <p/>\n * Execute a forced recursive deep clean on the {@link VirtualFile} owner.\n */\n @Override\n public void onCleanup() {\n Automounter.getEntry(getOwner()).cleanup();\n }\n}" ]
import java.io.File; import org.jboss.test.vfs.AbstractVFSTest; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.util.automount.Automounter; import org.jboss.vfs.util.automount.MountOption; import org.jboss.vfs.util.automount.MountOwner; import org.jboss.vfs.util.automount.SimpleMountOwner; import org.jboss.vfs.util.automount.VirtualFileOwner;
/* * JBoss, Home of Professional Open Source * Copyright 2009, JBoss Inc., and individual contributors as indicated * by the @authors tag. * * 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 org.jboss.test.vfs.util.automount; /** * Test for {@link Automounter} * * @author <a href="jbailey@redhat.com">John Bailey</a> */ public class AutomounterTestCase extends AbstractVFSTest { public AutomounterTestCase(String name) { super(name); } public void testMountAndCleanup() throws Exception { VirtualFile virtualFile = getVirtualFile("/vfs/test/simple.ear"); MountOwner owner = new VirtualFileOwner(virtualFile); Automounter.mount(owner, virtualFile); assertTrue(Automounter.isMounted(virtualFile)); Automounter.cleanup(owner); assertFalse(Automounter.isMounted(virtualFile)); } public void testCleanupWithOwner() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFileOwner owner = new VirtualFileOwner(earVirtualFile); VirtualFile jarVirtualFile = earVirtualFile.getChild("archive.jar"); Automounter.mount(owner, jarVirtualFile); VirtualFile warVirtualFile = earVirtualFile.getChild("simple.war"); Automounter.mount(owner, warVirtualFile); assertTrue(Automounter.isMounted(earVirtualFile)); assertTrue(Automounter.isMounted(warVirtualFile)); assertTrue(Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(owner); assertFalse(Automounter.isMounted(earVirtualFile)); assertFalse(Automounter.isMounted(warVirtualFile)); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupRecursive() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFile jarVirtualFile = earVirtualFile.getChild("archive.jar"); Automounter.mount(jarVirtualFile); VirtualFile warVirtualFile = earVirtualFile.getChild("simple.war"); Automounter.mount(warVirtualFile); assertTrue(Automounter.isMounted(earVirtualFile)); assertTrue(Automounter.isMounted(warVirtualFile)); assertTrue(Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(new VirtualFileOwner(earVirtualFile)); assertFalse(Automounter.isMounted(earVirtualFile)); assertFalse(Automounter.isMounted(warVirtualFile)); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupRefereces() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFileOwner owner = new VirtualFileOwner(earVirtualFile); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(owner, jarVirtualFile); VirtualFile warVirtualFile = getVirtualFile("/vfs/test/filesonly.war"); Automounter.mount(owner, warVirtualFile); assertTrue(Automounter.isMounted(earVirtualFile)); assertTrue(Automounter.isMounted(warVirtualFile)); assertTrue(Automounter.isMounted(jarVirtualFile)); VirtualFile otherEarVirtualFile = getVirtualFile("/vfs/test/spring-ear.ear"); Automounter.mount(otherEarVirtualFile, jarVirtualFile); Automounter.cleanup(owner); assertFalse(Automounter.isMounted(earVirtualFile)); assertFalse(Automounter.isMounted(warVirtualFile)); assertTrue("Should not have unmounted the reference from two locations", Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(otherEarVirtualFile); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupReferecesSameVF() throws Exception { VirtualFile earVirtualFile = getVirtualFile("/vfs/test/simple.ear"); Automounter.mount(earVirtualFile); VirtualFileOwner owner = new VirtualFileOwner(earVirtualFile); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(owner, jarVirtualFile); VirtualFileOwner otherOwner = new VirtualFileOwner(earVirtualFile); Automounter.mount(otherOwner, jarVirtualFile); Automounter.cleanup(owner); assertFalse("Should have been unmounted since the VirtualFile is the same", Automounter.isMounted(jarVirtualFile)); } public void testCleanupReferecesSimpleOwner() throws Exception { MountOwner owner = new SimpleMountOwner(new Object()); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(owner, jarVirtualFile); MountOwner otherOwner = new SimpleMountOwner(new Object()); Automounter.mount(otherOwner, jarVirtualFile); Automounter.cleanup(owner); assertTrue("Should not have unmounted the reference from two locations", Automounter.isMounted(jarVirtualFile)); Automounter.cleanup(otherOwner); assertFalse(Automounter.isMounted(jarVirtualFile)); } public void testCleanupReferecesSimpleOwnerSameObj() throws Exception { Object ownerObject = new Object(); VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); Automounter.mount(ownerObject, jarVirtualFile); Automounter.mount(ownerObject, jarVirtualFile); Automounter.cleanup(ownerObject); assertFalse("Should have been unmounted since the owner object is the same", Automounter.isMounted(jarVirtualFile)); } public void testMountWithCopy() throws Exception { VirtualFile jarVirtualFile = getVirtualFile("/vfs/test/jar1.jar"); File originalFile = jarVirtualFile.getPhysicalFile();
Automounter.mount(jarVirtualFile, MountOption.COPY);
3
JEEventStore/JEEventStore
persistence-jpa/src/test/java/org/jeeventstore/persistence/jpa/EventStorePersistenceJPATest.java
[ "@Singleton\n@LocalBean\n@Startup\npublic class PersistenceTestHelper {\n\n @EJB(lookup = \"java:global/test/ejb/EventStorePersistence\")\n private EventStorePersistence persistence;\n\n private static final int COUNT_TEST = 150;\n\n private List<ChangeSet> data_default = new ArrayList<ChangeSet>();\n private List<ChangeSet> data_test = new ArrayList<ChangeSet>();\n\n @PostConstruct\n public void init() {\n System.out.println(\"Loading data @ \" + this.getClass().getName());\n try {\n List<Integer> ids = new ArrayList<>();\n for (int i = 0; i < 103; i++)\n ids.add(i);\n for (int j = 0; j < 50; j++) { // increasing stream version\n // shuffle order of writes to mimic real-world behaviour (at least a bit)\n Collections.shuffle(ids);\n for (Integer i: ids) {\n if (j > i % 37)\n continue;\n ChangeSet cs = new DefaultChangeSet(\n \"DEFAULT\",\n \"TEST_\" + i,\n j,\n UUID.randomUUID().toString(),\n new ArrayList<Serializable>());\n data_default.add(cs);\n persistence.persistChanges(cs);\n }\n }\n for (int i = 0; i < 150; i++) {\n ChangeSet cs = new DefaultChangeSet(\n \"TEST\",\n \"SINGLE_STREAM\" + i,\n i,\n UUID.randomUUID().toString(),\n new ArrayList<Serializable>());\n data_test.add(cs);\n persistence.persistChanges(cs);\n }\n } catch (ConcurrencyException | DuplicateCommitException e) {\n // ignore\n }\n System.out.println((data_default.size() + data_test.size()) + \" entities loaded.\");\n }\n\n public void test_allChanges_testBucket() {\n List<? extends Serializable> list = new ArrayList<Serializable>();\n Iterator<ChangeSet> it = persistence.allChanges(\"TEST\");\n compare(it, data_test, false);\n }\n\n public void test_allChanges_inorder() {\n Iterator<ChangeSet> it = persistence.allChanges(\"DEFAULT\");\n Map<String, Long> versions = new HashMap<>();\n int count = 0;\n while (it.hasNext()) {\n ChangeSet cs = it.next();\n assertEquals(cs.bucketId(), \"DEFAULT\");\n Long lastVersion = versions.get(cs.streamId());\n if (lastVersion == null)\n lastVersion = 0l;\n assertTrue(lastVersion <= cs.streamVersion());\n versions.put(cs.streamId(), cs.streamVersion());\n count++;\n }\n assertEquals(count, data_default.size());\n }\n\n public void test_getFrom_regular() throws StreamNotFoundException {\n List<ChangeSet> expected = filter(\"DEFAULT\", \"TEST_45\", 0, Long.MAX_VALUE);\n Iterator<ChangeSet> have = persistence.getFrom(\"DEFAULT\", \"TEST_45\", 0, Long.MAX_VALUE);\n compare(have, expected, true);\n }\n\n public void test_getFrom_substream() throws StreamNotFoundException {\n List<ChangeSet> expected = filter(\"DEFAULT\", \"TEST_65\", 4, 10);\n Iterator<ChangeSet> have = persistence.getFrom(\"DEFAULT\", \"TEST_65\", 4, 10);\n compare(have, expected, true);\n }\n\n public void test_allChanges_nullarg() {\n try {\n persistence.allChanges(null);\n fail(\"Should have failed by now\");\n } catch (EJBException e) {\n // expected\n }\n }\n\n public void test_getFrom_nullarg() throws StreamNotFoundException {\n try {\n persistence.getFrom(null, \"TEST\", 0, Long.MAX_VALUE);\n fail(\"Should have failed by now\");\n } catch (EJBException e) {\n // expected\n }\n try {\n persistence.getFrom(\"DEFAULT\", null, 0, Long.MAX_VALUE);\n fail(\"Should have failed by now\");\n } catch (EJBException e) {\n // expected\n }\n }\n\n public void test_large_event() {\n String streamId = UUID.randomUUID().toString();\n\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < 15000 / 32; i++)\n builder.append(UUID.randomUUID().toString());\n String body = builder.toString();\n\n store(streamId, streamId, body);\n String result = (String) load(streamId, streamId);\n assertEquals(body, result);\n }\n\n /**\n * Test against broken UTF8 encodings in the PostgreSQL/Hibernate combination,\n * when the @Lob annotation is used.\n * When database field is NOT of type TEXT \n * see https://hibernate.atlassian.net/browse/HHH-6127\n */\n public void test_utf8_chars() {\n String streamId = UUID.randomUUID().toString();\n\n String body = \"ÜÄÖüäöß / \" \n + TestUTF8Utils.unicodeString() + \" / \"\n + TestUTF8Utils.utf8String();\n store(streamId, streamId, body);\n String result = (String) load(streamId, streamId);\n TestUTF8Utils.println(\"####### Result as loaded from DB: \" + result);\n assertEquals(body, result);\n }\n\n private List<ChangeSet> getFrom(String bucketId, String streamId) throws StreamNotFoundException {\n assertTrue(persistence.existsStream(bucketId, streamId));\n Iterator<ChangeSet> it = persistence.getFrom(bucketId, streamId, 0, Long.MAX_VALUE);\n return IteratorUtils.toList(it);\n }\n\n private List<ChangeSet> filter(String bucketId, String streamId, long minVersion, long maxVersion) {\n List<ChangeSet> res = new ArrayList<>();\n for (ChangeSet cs: data_default) {\n if (!cs.bucketId().equals(bucketId))\n continue;\n if (!cs.streamId().equals(streamId))\n continue;\n res.add(cs);\n }\n if (maxVersion == Long.MAX_VALUE)\n maxVersion = Integer.MAX_VALUE - 1;\n int min = Math.min(res.size(), (int) minVersion + 1);\n int max = Math.min(res.size(), (int) maxVersion + 1);\n return res.subList(min, max);\n }\n\n private void store(String bucketId, String streamId, Serializable data) {\n List<Serializable> events = new ArrayList<>();\n events.add(data);\n try {\n ChangeSet cs = new DefaultChangeSet(\n bucketId, streamId, 1, \n UUID.randomUUID().toString(),\n events);\n persistence.persistChanges(cs);\n } catch (ConcurrencyException | DuplicateCommitException e) {\n throw new RuntimeException(e);\n }\n }\n\n private Serializable load(String bucketId, String streamId) {\n try {\n List<ChangeSet> sets = getFrom(streamId, streamId);\n assertEquals(1, sets.size());\n ChangeSet cs = sets.get(0);\n List<Serializable> result = IteratorUtils.toList(cs.events());\n assertEquals(1, result.size());\n return result.get(0);\n } catch (StreamNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n\n private void compare(Iterator<ChangeSet> it, List<ChangeSet> data, boolean deepverify) {\n int count = 0;\n long lastVersion = 0;\n while (it.hasNext()) {\n assertTrue(count < data.size());\n ChangeSet found = it.next();\n ChangeSet wanted = data.get(count);\n assertTrue(lastVersion <= found.streamVersion());\n assertEquals(found.bucketId(), wanted.bucketId());\n if (deepverify) {\n assertEquals(found.streamId(), wanted.streamId());\n assertEquals(found.streamVersion(), wanted.streamVersion());\n assertEquals(found.changeSetId(), wanted.changeSetId());\n assertEquals(IteratorUtils.toList(found.events()),\n IteratorUtils.toList(wanted.events()));\n }\n lastVersion = Math.max(lastVersion, found.streamVersion());\n count++;\n }\n assertEquals(count, data.size());\n }\n \n}", "public class StreamNotFoundException extends Exception {\n\n public StreamNotFoundException() {\n }\n\n public StreamNotFoundException(String message) {\n super(message);\n }\n\n public StreamNotFoundException(Throwable cause) {\n super(cause);\n }\n\n public StreamNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n \n}", "public class TestUTF8Utils {\n\n public static String unicodeString() {\n return \"A\" + \"\\u00ea\" + \"\\u00f1\" + \"\\u00fc\" + \"C\";\n }\n\n public static String utf8String() {\n try {\n return new String(unicodeString().getBytes(\"UTF8\"), \"UTF8\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void println(String output) {\n try {\n PrintStream out = new PrintStream(System.out, true, \"UTF8\");\n out.println(output);\n out.flush();\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n }\n \n}", "public class AbstractPersistenceTest extends Arquillian {\n\n @EJB(lookup = \"java:global/test/ejb/PersistenceTestHelper\")\n private PersistenceTestHelper testHelper;\n\n @EJB(lookup = \"java:global/test/ejb/EventStorePersistence\")\n private EventStorePersistence persistence;\n\n protected EventStorePersistence getPersistence() {\n return this.persistence;\n }\n\n @Test\n public void test_allChanges_testBucket() {\n testHelper.test_allChanges_testBucket();\n }\n\n @Test\n public void test_allChanges_inorder() {\n testHelper.test_allChanges_inorder();\n }\n\n @Test\n public void test_getFrom_regular() throws StreamNotFoundException {\n testHelper.test_getFrom_regular();\n }\n\n @Test\n public void test_getFrom_substream() throws StreamNotFoundException {\n testHelper.test_getFrom_substream();\n }\n\n @Test\n public void test_optimistic_lock() throws DuplicateCommitException {\n ChangeSet cs = new DefaultChangeSet(\n \"DEFAULT\",\n \"TEST_49\",\n 5, // exists\n UUID.randomUUID().toString(),\n new ArrayList<Serializable>());\n try {\n persistence.persistChanges(cs);\n fail(\"Should have failed by now\");\n } catch (EJBException | ConcurrencyException e) {\n // expected\n }\n }\n\n @Test\n public void test_duplicate_commit() throws ConcurrencyException {\n String id = UUID.randomUUID().toString();\n try {\n for (int i = 0; i < 2; i++)\n persistence.persistChanges(new DefaultChangeSet(\n \"DEFAULT\",\n \"TEST_DUPLICATE\",\n i + 1,\n id,\n new ArrayList<Serializable>()));\n fail(\"Should have failed by now\");\n } catch (EJBException | DuplicateCommitException e) {\n // expected\n }\n\n }\n \n @Test\n public void test_allChanges_nullarg() {\n testHelper.test_allChanges_nullarg();\n }\n\n @Test\n public void test_getFrom_nullarg() throws StreamNotFoundException {\n testHelper.test_getFrom_nullarg();\n }\n\n @Test\n public void test_existsStream_nullarg() {\n try {\n persistence.existsStream(null, \"TEST\");\n fail(\"Should have failed by now\");\n } catch (EJBException e) {\n // expected\n }\n try {\n persistence.existsStream(\"DEFAULT\", null);\n fail(\"Should have failed by now\");\n } catch (EJBException e) {\n // expected\n }\n }\n\n @Test\n public void test_persistChanges_nullarg() throws ConcurrencyException, DuplicateCommitException {\n try {\n persistence.persistChanges(null);\n fail(\"Should have failed by now\");\n } catch (EJBException e) {\n // expected\n }\n }\n\n @Test\n public void test_large_event() {\n testHelper.test_large_event();\n }\n\n @Test\n public void test_utf8_chars() {\n testHelper.test_utf8_chars();\n }\n\n}", "public class XMLSerializer implements EventSerializer {\n\n @Override\n public String serialize(List<? extends Serializable> events) {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n XMLEncoder encoder = new XMLEncoder(baos);\n encoder.writeObject(events);\n encoder.close();\n String res = baos.toString(\"UTF-8\");\n baos.close();\n return res;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public List<? extends Serializable> deserialize(String body) {\n try {\n ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes(\"UTF-8\"));\n XMLDecoder decoder = new XMLDecoder(bais);\n List<? extends Serializable> res = (List<? extends Serializable>) decoder.readObject();\n decoder.close();\n bais.close();\n return res;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n \n}", "public class DefaultDeployment {\n\n /**\n * Resolve the dependencies for the given maven artifact.\n * @param artifact\n * @return A list of files pointing to the dependencies.\n */\n static File[] resolve(String artifact) {\n\treturn Maven.resolver().loadPomFromFile(\"pom.xml\")\n\t\t.resolve(artifact)\n\t\t.withTransitivity()\n .as(File.class); \n }\n\n public static EnterpriseArchive ear(String artifact) {\n\tSystem.out.println(\"Generating standard EAR deployment\");\n\tEnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class);\n addDependencies(ear, artifact, true);\n return ear;\n }\n\n public static void addDependencies(EnterpriseArchive ear, String artifact, boolean includeArtifact) {\n String lib = artifact.split(\":\")[1];\n try {\n File[] libs = resolve(artifact);\n for (int i = 0; i < libs.length; i++) {\n if (i == 0 && !includeArtifact)\n continue;\n File f = libs[i];\n String filename = (i > 0 ? f.getName() : lib + \".jar\");\n System.out.println(\"Adding dependency #\" + i \n + \": \" + f.getAbsolutePath() \n + \" as \" + filename);\n ear.addAsLibrary(f, filename);\n }\n } catch (RuntimeException e) {\n // printing the error helps with testing\n System.err.println(\">>>>>> ERROR: \" + e + \" / \" + e.getCause());\n throw e;\n }\n }\n\n}" ]
import org.jeeventstore.persistence.AbstractPersistenceTest; import org.jeeventstore.serialization.XMLSerializer; import org.jeeventstore.tests.DefaultDeployment; import static org.testng.Assert.*; import org.testng.annotations.Test; import org.jeeventstore.persistence.PersistenceTestHelper; import java.io.File; import javax.ejb.EJBTransactionRequiredException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jeeventstore.StreamNotFoundException; import org.jeeventstore.TestUTF8Utils;
/* * Copyright (c) 2013-2014 Red Rainbow IT Solutions GmbH, Germany * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.jeeventstore.persistence.jpa; public class EventStorePersistenceJPATest extends AbstractPersistenceTest { @Deployment public static EnterpriseArchive deployment() { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "test.ear"); DefaultDeployment.addDependencies(ear, "org.jeeventstore:jeeventstore-persistence-jpa", false); ear.addAsModule(ShrinkWrap.create(JavaArchive.class, "ejb.jar") .addAsManifestResource(new File("src/test/resources/META-INF/beans.xml")) .addAsManifestResource(new File("src/test/resources/META-INF/persistence.xml")) .addAsManifestResource(new File( "src/test/resources/META-INF/ejb-jar-EventStorePersistenceJPATest.xml"), "ejb-jar.xml") .addClass(XMLSerializer.class)
.addClass(TestUTF8Utils.class)
2
NicolaasWeideman/RegexStaticAnalysis
src/main/java/analysis/ExploitStringBuilder.java
[ "public static class IdaSpecialTransitionLabel implements TransitionLabel {\n\n\t@Override\n\tpublic boolean matches(String word) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean matches(TransitionLabel tl) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic TransitionLabel intersection(TransitionLabel tl) {\n\t\tthrow new UnsupportedOperationException(\"The intersection operation is invalid for special transitions.\");\n\t}\n\t\t\n\t@Override\n\tpublic TransitionLabel union(TransitionLabel tl) {\n\t\tthrow new UnsupportedOperationException(\"The union operation is invalid for special transitions.\");\n\t}\n\n\t@Override\n\tpublic TransitionLabel complement() {\n\t\tthrow new UnsupportedOperationException(\"The complement operation is invalid for special transitions.\");\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn false;\n\t}\n\n\t\t\n\t@Override\n\tpublic String getSymbol() {\n\t\tthrow new UnsupportedOperationException(\"Special transitions contain multiple symbols\");\n\t}\n\t\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"#(\" + transitionLabels + \")\";\n\t}\n\n\t@Override\n\tpublic TransitionLabel copy() {\n\t\treturn new IdaSpecialTransitionLabel(transitionLabels);\n\t}\n\n\t@Override\n\tpublic TransitionType getTransitionType() {\n\t\treturn TransitionType.OTHER;\n\t}\n\t\t\n\t/* Represents a transition label in this scc, for when calculating the degree */\n\tprivate final LinkedList<TransitionLabel> transitionLabels;\n\tpublic LinkedList<TransitionLabel> getTransitionLabels() {\n\t\treturn transitionLabels;\n\t}\n\t\t\n\tpublic IdaSpecialTransitionLabel(LinkedList<TransitionLabel> transitionLabels) {\n\t\tthis.transitionLabels = transitionLabels;\n\t}\n\t\t\n}", "static final class EdaAnalysisResultsESCC extends EdaAnalysisResults {\n\n\n\tprivate final NFAGraph originalScc;\n\tpublic NFAGraph getOriginalScc() {\n\t\treturn originalScc;\n\t}\n\n\tprivate final NFAEdge entranceEdge;\n\tpublic NFAEdge getEntranceEdge() {\n\t\treturn entranceEdge;\n\t}\n\t\t\n\tprivate final NFAEdge exitEdge;\n\tpublic NFAEdge getExitEdge() {\n\t\treturn exitEdge;\n\t}\n\t\t\n\tEdaAnalysisResultsESCC(NFAGraph originalGraph, NFAGraph originalScc, NFAEdge startEdge, NFAEdge endEdge) {\n\t\tsuper(originalGraph, EdaCases.ESCC);\n\t\tthis.originalScc = originalScc;\n\t\tthis.entranceEdge = startEdge;\n\t\tthis.exitEdge = endEdge;\n\t}\n}", "static final class EdaAnalysisResultsFilter extends EdaAnalysisResults {\t\t\n\tprivate final NFAGraph pcScc;\n\tpublic NFAGraph getPcScc() {\n\t\treturn pcScc;\n\t}\n\n\tprivate final NFAVertexND startState;\n\tpublic NFAVertexND getStartState() {\n\t\treturn startState;\n\t}\n\tprivate final NFAVertexND endState;\n\tpublic NFAVertexND getEndState() {\n\t\treturn endState;\n\t}\n\n\tEdaAnalysisResultsFilter(NFAGraph originalGraph, NFAGraph pcScc, NFAVertexND startState, NFAVertexND endState) {\n\t\tsuper(originalGraph, EdaCases.FILTER);\n\t\tthis.pcScc = pcScc;\n\t\tthis.startState = startState;\n\t\tthis.endState = endState;\n\t}\n}", "static final class EdaAnalysisResultsParallel extends EdaAnalysisResults {\n\n\tprivate final NFAGraph mergedScc;\n\tpublic NFAGraph getMergedScc() {\n\t\treturn mergedScc;\n\t}\n\n\tprivate final NFAVertexND sourceVertex;\n\tpublic NFAVertexND getSourceVertex() {\n\t\treturn sourceVertex;\n\t}\n\t\t\n\tprivate final NFAEdge parallelEdge;\n\tpublic NFAEdge getParallelEdge() {\n\t\treturn parallelEdge;\n\t}\n\n\tEdaAnalysisResultsParallel(NFAGraph originalGraph, NFAGraph mergedScc, NFAVertexND sourceVertex, NFAEdge parallelEdge) {\n\t\tsuper(originalGraph, EdaCases.PARALLEL);\n\t\tthis.mergedScc = mergedScc;\n\t\tthis.sourceVertex = sourceVertex;\n\t\tthis.parallelEdge = parallelEdge;\n\t}\n\n}", "static final class IdaAnalysisResultsIda extends IdaAnalysisResults {\n\tprivate final int degree;\n\tpublic int getDegree() {\n\t\treturn degree;\n\t}\n\t\t\n\tprivate final LinkedList<NFAEdge> maxPath;\n\tpublic LinkedList<NFAEdge> getMaxPath() {\n\t\treturn maxPath;\n\t}\n\t\t\n\t\t\n\tIdaAnalysisResultsIda(NFAGraph originalGraph, int degree, LinkedList<NFAEdge> maxPath) {\n\t\tsuper(originalGraph, IdaCases.IDA);\n\t\tthis.degree = degree;\n\t\tthis.maxPath = maxPath;\n\t}\n}", "public class NFAGraph extends DirectedPseudograph<NFAVertexND, NFAEdge> {\n\tprivate static final long serialVersionUID = 1L;\n\n\t/* The vertex representing the initial state of the NFA */\n\tprivate NFAVertexND initialState;\n\n\tpublic NFAVertexND getInitialState() {\n\t\treturn initialState;\n\t}\n\n\tpublic void setInitialState(NFAVertexND initialState) {\n\t\tif (!super.containsVertex(initialState)) {\n\t\t\tthrow new IllegalArgumentException(\"Graph does not contain vertex: \" + initialState);\n\t\t}\n\t\tthis.initialState = initialState;\n\t}\n\n\t/* The accepting states of the NFA */\n\tprivate HashSet<NFAVertexND> acceptingStates;\n\n\tpublic void addAcceptingState(NFAVertexND acceptingState) {\n\t\tif (!super.containsVertex(acceptingState)) {\n\t\t\tthrow new IllegalArgumentException(\"Graph does not contain vertex: \" + acceptingState);\n\t\t}\n\t\tacceptingStates.add(acceptingState);\n\t}\n\n\tpublic boolean isAcceptingState(String stateNumber) {\n\t\treturn acceptingStates.contains(new NFAVertexND(stateNumber));\n\t}\n\n\tpublic boolean isAcceptingState(NFAVertexND state) {\n\t\treturn acceptingStates.contains(state);\n\t}\n\n\tpublic void removeAcceptingState(NFAVertexND acceptingState) {\n\t\tif (!super.containsVertex(acceptingState)) {\n\t\t\tthrow new IllegalArgumentException(\"Graph does not contains accepting state: \" + acceptingState);\n\t\t}\n\t\tacceptingStates.remove(acceptingState);\n\t}\n\n\tpublic Set<NFAVertexND> getAcceptingStates() {\n\t\treturn acceptingStates;\n\t}\n\n\tpublic NFAGraph() {\n\t\tsuper(NFAEdge.class);\n\t\tacceptingStates = new HashSet<NFAVertexND>();\n\t}\n\n\t/**\n\t * @return A new instance of a NFAGraph equal to this instance\n\t */\n\tpublic NFAGraph copy() {\n\t\tNFAGraph c = new NFAGraph();\n\t\tfor (NFAVertexND v : super.vertexSet()) {\n\t\t\tc.addVertex(v.copy());\n\t\t}\n\t\tfor (NFAEdge e : super.edgeSet()) {\n\t\t\tc.addEdge(e.copy());\n\t\t}\n\n\t\tif (initialState != null) {\n\t\t\tc.initialState = initialState.copy();\n\t\t}\n\t\t\n\t\tfor (NFAVertexND v : acceptingStates) {\n\t\t\tc.addAcceptingState(v.copy());\n\t\t}\n\t\treturn c;\n\t}\n\n\t/**\n\t * Adds a new edge to the NFA graph\n\t * \n\t * @param newEdge\n\t * The new edge to add\n\t * @return true if this graph did not already contain the specified edge\n\t */\n\tpublic boolean addEdge(NFAEdge newEdge) {\n\t\tif (newEdge == null) {\n\t\t\tthrow new NullPointerException(\"New edge cannot be null\");\n\t\t}\n\t\tif (newEdge.getTransitionLabel().isEmpty()) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tNFAVertexND s = newEdge.getSourceVertex();\n\t\tNFAVertexND t = newEdge.getTargetVertex();\n\t\tif (super.containsEdge(newEdge)) {\n\t\t\t/* if the edge exists increase the number of its parallel edges */\n\t\t\tNFAEdge e = getEdge(newEdge);\n\t\t\te.incNumParallel();\n\t\t} else if (newEdge.getIsEpsilonTransition()) {\n\t\t\t/* check if the NFA already has an epsilon transition between these states */\n\t\t\tSet<NFAEdge> es = super.getAllEdges(s, t);\n\t\t\tfor (NFAEdge currentEdge : es) {\n\t\t\t\tif (currentEdge.equals(newEdge)) {\n\t\t\t\t\t/* if it does, add the new edge as a parallel edge (priorities don't matter between the same states) */\n\t\t\t\t\tcurrentEdge.incNumParallel();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t/* check if the new edge overlaps the current edges */\n\t\t\tSet<NFAEdge> es = super.getAllEdges(s, t);\n\t\t\t// TODO lightly tested\n\t\t\tfor (NFAEdge currentEdge : es) {\n\t\t\t\t/* epsilon edges cannot overlap */\n\t\t\t\tif (currentEdge.getTransitionType() == TransitionType.SYMBOL) {\n\t\t\t\t\tTransitionLabel tlCurrentEdge = currentEdge.getTransitionLabel();\n\t\t\t\t\tTransitionLabel tlNewEdge = newEdge.getTransitionLabel();\n\t\t\t\t\tTransitionLabel intersection = tlNewEdge.intersection(tlCurrentEdge);\n\t\t\t\t\tif (!intersection.isEmpty()) {\n\t\t\t\t\t\t/* overlapping edge */\n\t\t\t\t\t\tTransitionLabel currentEdgeRelabel = tlCurrentEdge.intersection(tlNewEdge.complement());\n\t\t\t\t\t\tint currentEdgeWeight = 0;\n\t\t\t\t\t\tif (!currentEdgeRelabel.isEmpty()) {\n\t\t\t\t\t\t\tcurrentEdgeWeight = currentEdge.getNumParallel();\n\t\t\t\t\t\t\tremoveEdge(currentEdge);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tNFAEdge currentEdgeRelabeled = new NFAEdge(s, t, currentEdgeRelabel);\n\t\t\t\t\t\t\tcurrentEdgeRelabeled.setNumParallel(currentEdgeWeight);\n\t\t\t\t\t\t\taddEdge(currentEdgeRelabeled);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tNFAEdge overlappingEdge = new NFAEdge(s, t, intersection);\n\t\t\t\t\t\toverlappingEdge.setNumParallel(currentEdgeWeight + newEdge.getNumParallel());\n\t\t\t\t\t\taddEdge(overlappingEdge);\n\t\t\t\t\t\t\n\t\t\t\t\t\tTransitionLabel newEdgeRelabel = tlNewEdge.intersection(tlCurrentEdge.complement());\n\t\t\t\t\t\tif (!newEdgeRelabel.isEmpty()) {\n\t\t\t\t\t\t\tint newEdgeWeight = newEdge.getNumParallel();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tNFAEdge newEdgeRelabeled = new NFAEdge(s, t, newEdgeRelabel);\n\t\t\t\t\t\t\tnewEdgeRelabeled.setNumParallel(newEdgeWeight);\n\t\t\t\t\t\t\taddEdge(newEdgeRelabeled);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tif (!super.containsVertex(newEdge.getSourceVertex())) {\n\t\t\tthrow new IllegalArgumentException(\"Graph doesn't contain vertex: \" + newEdge.getSourceVertex());\n\t\t}\n\t\tif (!super.containsVertex(newEdge.getTargetVertex())) {\n\t\t\tthrow new IllegalArgumentException(\"Graph doesn't contain vertex: \" + newEdge.getTargetVertex());\n\t\t}\n\t\treturn super.addEdge(newEdge.getSourceVertex(), newEdge.getTargetVertex(), newEdge);\n\t}\n\n\t/**\n\t * All the edges representing an epsilon transition from a vertex\n\t * \n\t * @param v\n\t * The vertex to find the epsilon transitions from.\n\t * @return A set of NFA edges representing the epsilon transitions.\n\t */\n\tpublic Set<NFAEdge> outgoingEpsilonEdgesOf(NFAVertexND v) {\n\t\tSet<NFAEdge> allEdges = super.outgoingEdgesOf(v);\n\n\t\tSet<NFAEdge> toReturn = new HashSet<NFAEdge>();\n\n\t\tfor (NFAEdge e : allEdges) {\n\t\t\tif (e.getIsEpsilonTransition()) {\n\t\t\t\ttoReturn.add(e);\n\t\t\t}\n\t\t}\n\n\t\treturn toReturn;\n\t}\n\n\t@Override\n\tpublic boolean addVertex(NFAVertexND v) {\n\t\tif (containsVertex(v)) {\n\t\t\tthrow new IllegalArgumentException(\"Graph already contains vertex: \" + v);\n\t\t}\n\t\treturn super.addVertex(v);\n\t}\n\t\n\tpublic NFAEdge getEdge(NFAEdge e) {\n\t\tif (!super.containsEdge(e)) {\n\t\t\tthrow new IllegalArgumentException(\"Graph does not contain edge: \" + e.getSourceVertex() + \"->\" + e.getTargetVertex() + \":\" + e.getTransitionLabel());\n\t\t}\n\t\tSet<NFAEdge> edges = super.getAllEdges(e.getSourceVertex(), e.getTargetVertex());\n\t\tfor (NFAEdge currentE : edges) {\n\t\t\tif (currentE.equals(e)) {\n\t\t\t\treturn currentE;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!super.equals(o)) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t/* testing that the amount of parallel edges are equal */\n\t\tNFAGraph n = (NFAGraph) o;\n\t\tfor (NFAEdge e : n.edgeSet()) {\n\t\t\tSet<NFAEdge> nEdges = super.getAllEdges(e.getSourceVertex(), e.getTargetVertex());\n\t\t\tfor (NFAEdge nEdge : nEdges) {\n\t\t\t\tif (e.equals(nEdge) && e.getNumParallel() != nEdge.getNumParallel()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (initialState != null && !initialState.equals(n.getInitialState())) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tHashSet<NFAVertexND> myAcceptingStates = new HashSet<NFAVertexND>(acceptingStates);\n\t\tHashSet<NFAVertexND> otherAcceptingStates = new HashSet<NFAVertexND>(n.getAcceptingStates());\n\n\t\tboolean condition1 = myAcceptingStates.size() == otherAcceptingStates.size();\n\t\tboolean condition2 = myAcceptingStates.containsAll(otherAcceptingStates);\n\t\tboolean condition3 = otherAcceptingStates.containsAll(myAcceptingStates);\n\t\t/* first condition might be redundant */\n\t\treturn condition1 && condition2 && condition3 ;\n\n\t}\n\t\n\tpublic NFAGraph reverse() {\n\t\tNFAGraph reversedGraph = this.copy();\n\t\t\n\t\tfor (NFAEdge e : edgeSet()) {\n\t\t\tNFAVertexND newSource = e.getTargetVertex();\n\t\t\tNFAVertexND newTarget = e.getSourceVertex();\n\t\t\tNFAEdge reversedEdge = new NFAEdge(newSource, newTarget, e.getTransitionLabel());\n\t\t\treversedGraph.removeEdge(e);\n\t\t\treversedGraph.addEdge(reversedEdge);\n\t\t}\n\t\t\n\t\treturn reversedGraph;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder(\"I:\" + initialState + \" A:\");\n\t\tif (!acceptingStates.isEmpty()) {\n\t\t\tfor (NFAVertexND a : acceptingStates) {\n\t\t\t\tsb.append(a + \";\");\n\t\t\t}\n\t\t} else {\n\t\t\tsb.append(\"No Accepting states;\");\n\t\t}\n\n\t\t\n\t\treturn sb.toString() + \" \" + super.toString();\n\t}\n\t\t\t\n\tprivate String nameState(NFAVertexND v) {\n\t\t\tStringBuilder sb = new StringBuilder(\"\\\"\");\n\t\t\tArrayList<String> states = v.getStates();\n\t\t\tCollections.sort(states);\n\t\t\tIterator<String> stateIterator = states.iterator();\n\t\t\twhile (stateIterator.hasNext()) {\n\t\t\t\tsb.append(stateIterator.next());\n\t\t\t\tif (stateIterator.hasNext()) {\n\t\t\t\t\tsb.append(\",\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tsb.append(\"\\\"\");\n\t\t\treturn sb.toString();\n\t}\n}", "public class NFAEdge extends DefaultEdge implements Comparable<NFAEdge> {\n\t/* required from super class */\n\tprivate static final long serialVersionUID = 1L;\n\n\t/* the vertex this edge is coming from */\n\tprivate final NFAVertexND sourceVertex;\n\n\tpublic NFAVertexND getSourceVertex() {\n\t\treturn sourceVertex;\n\t}\n\n\t/* the vertex this edge is going to */\n\tprivate final NFAVertexND targetVertex;\n\n\tpublic NFAVertexND getTargetVertex() {\n\t\treturn targetVertex;\n\t}\n\t\n\t/* number of parallel edges */\n\tprivate int numParallel;\n\t\n\tpublic int getNumParallel() {\n\t\treturn numParallel;\n\t}\n\t\n\tpublic void setNumParallel(int numParallel) {\n\t\tthis.numParallel = numParallel;\n\t}\n\t\n\tpublic void incNumParallel() {\n\t\tthis.numParallel++;\n\t}\n\n\t/* The word associated with this transition in the NFA */\n\tprivate TransitionLabel transitionLabel;\n\tpublic TransitionLabel getTransitionLabel() {\n\t\treturn transitionLabel;\n\t}\n\n\tpublic String getATransitionCharacter() {\n\t\treturn transitionLabel.getSymbol();\n\t}\n\n\tpublic void setTransitionLabel(String transitionLabelString) {\n\t\tTransitionLabelParserRecursive tlp = new TransitionLabelParserRecursive(transitionLabelString);\n\t\tthis.transitionLabel = tlp.parseTransitionLabel();\n\t}\n\t\n\tpublic void setTransitionLabel(TransitionLabel transitionLabel) {\n\t\tthis.transitionLabel = transitionLabel;\n\t\t\n\t}\n\n\tprivate final boolean isEpsilonTransition;\n\n\tpublic boolean getIsEpsilonTransition() {\n\t\treturn isEpsilonTransition;\n\t}\n\t\n\tpublic TransitionType getTransitionType() {\n\t\treturn transitionLabel.getTransitionType();\n\t}\n\n\tpublic NFAEdge(NFAVertexND sourceVertex, NFAVertexND targetVertex,\n\t\t\tString transitionLabelString) throws EmptyTransitionLabelException {\n\t\t\n\t\tif (sourceVertex == null || targetVertex == null\n\t\t\t\t|| transitionLabelString == null) {\n\t\t\tthrow new NullPointerException(\"Null parameters are not allowed.\");\n\t\t}\n\n\t\tthis.sourceVertex = sourceVertex;\n\t\tthis.targetVertex = targetVertex;\n\t\t\n\t\tTransitionLabelParserRecursive tlpr = new TransitionLabelParserRecursive(transitionLabelString);\n\t\tthis.transitionLabel = tlpr.parseTransitionLabel();\n\t\tif (transitionLabel.isEmpty()) {\n\t\t\tthrow new EmptyTransitionLabelException(transitionLabelString);\n\t\t}\n\t\tthis.numParallel = 1;\n\n\t\tthis.isEpsilonTransition = isEpsilonCharacter(transitionLabel.getSymbol());\n\t}\n\t\n\tpublic NFAEdge(NFAVertexND sourceVertex, NFAVertexND targetVertex,\n\t\t\tTransitionLabel transitionLabel) {\n\n\t\tif (sourceVertex == null || targetVertex == null\n\t\t\t\t|| transitionLabel == null) {\n\t\t\tthrow new NullPointerException(\"Null parameters are not allowed.\");\n\t\t}\n\t\t\n\t\tif (transitionLabel.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"The transition label of an edge cannot be empty.\");\n\t\t}\n\n\t\tthis.sourceVertex = sourceVertex;\n\t\tthis.targetVertex = targetVertex;\n\t\t\n\t\tthis.transitionLabel = transitionLabel;\n\t\tthis.numParallel = 1;\n\n\t\tthis.isEpsilonTransition = transitionLabel.getTransitionType() == TransitionType.EPSILON;\n\t}\n\n\tprivate boolean isEpsilonCharacter(String transitionLabelString) {\n\t\treturn transitionLabelString.matches(\"ε\\\\d*\");\n\t}\n\n\t/**\n\t * @return A new instance of an NFAEdge equal to this instance.\n\t */\n\tpublic NFAEdge copy() {\n\t\tNFAEdge newEdge = new NFAEdge(sourceVertex, targetVertex, transitionLabel);\n\t\tnewEdge.setNumParallel(numParallel);\n\t\treturn newEdge;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!o.getClass().isAssignableFrom(this.getClass())) {\n\t\t\treturn false;\n\t\t}\n\t\tNFAEdge n = (NFAEdge) o;\n\t\tboolean test1 = sourceVertex.equals(n.getSourceVertex());\n\t\tboolean test2 = targetVertex.equals(n.getTargetVertex());\n\t\tboolean test3 = transitionLabel.equals(n.getTransitionLabel());\n\t\treturn test1 && test2 && test3;\n\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn sourceVertex.hashCode() + targetVertex.hashCode()\n\t\t\t\t+ transitionLabel.hashCode();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn transitionLabel + \"*\" + numParallel;\n\t}\n\t\n\tpublic boolean isTransitionFor(String word) {\n\t\t/* this method distinguishes between epsilon transitions, if this is unwanted rather use getIsEpsilonTransition on both */\n\t\treturn transitionLabel.matches(word);\t\t\n\t}\n\t\n\tpublic boolean isTransitionFor(TransitionLabel tl) {\n\t\t/* this method distinguishes between epsilon transitions, if this is unwanted rather use getIsEpsilonTransition on both */\n\t\treturn transitionLabel.matches(tl);\t\t\n\t}\n\n\t@Override\n\tpublic int compareTo(NFAEdge o) {\n\t\tif (!getIsEpsilonTransition() && o.getIsEpsilonTransition()) {\n\t\t\treturn -1;\n\t\t} else if (getIsEpsilonTransition() && !o.getIsEpsilonTransition()) {\n\t\t\treturn 1;\n\t\t} else if (getIsEpsilonTransition() && o.getIsEpsilonTransition()) {\n\t\t\tEpsilonTransitionLabel etl = (EpsilonTransitionLabel) transitionLabel;\n\t\t\tEpsilonTransitionLabel oetl = (EpsilonTransitionLabel) o.transitionLabel;\n\t\t\treturn etl.compareTo(oetl);\n\t\t} else {\n\t\t\tCharacterClassTransitionLabel cctl = (CharacterClassTransitionLabel) transitionLabel;\n\t\t\tCharacterClassTransitionLabel occtl = (CharacterClassTransitionLabel) o.transitionLabel;\n\t\t\treturn cctl.compareTo(occtl);\n\t\t}\n\n\n\t}\n}", "public class NFAVertexND implements Comparable<NFAVertexND> {\n\n\tprivate ArrayList<String> states;\n\n\t/**\n\t * @return The states contained in this state\n\t */\n\tpublic ArrayList<String> getStates() {\n\t\treturn new ArrayList<String>(states);\n\t}\n\n\t/**\n\t * Returns the state at a specified dimension. Since the states are referred\n\t * to as being at dimensions, they are one indexed.\n\t * \n\t * @param dim\n\t * @return The state number at the dimension\n\t */\n\tpublic String getStateNumberByDimension(int dim) {\n\t\treturn states.get(dim - 1);\n\t}\n\n\t/**\n\t * Gets a state at a certain dimension\n\t * \n\t * @param dim\n\t * The dimension\n\t * @return The state at the dimension.\n\t */\n\tpublic NFAVertexND getStateByDimension(int dim) {\n\t\treturn new NFAVertexND(states.get(dim - 1));\n\t}\n\n\t/**\n\t * Constructs a new state formed from the states from the dimensions between\n\t * two indices.\n\t * \n\t * @param fromIndex\n\t * @param toIndex\n\t * @return The new state\n\t */\n\tpublic NFAVertexND getStateByDimensionRange(int fromIndex, int toIndex) {\n\t\treturn new NFAVertexND(states.subList(fromIndex - 1, toIndex - 1));\n\t}\n\n\t/**\n\t * Adds a state at a new dimension, one more than the current highest\n\t * dimension.\n\t * \n\t * @param state\n\t * The state to add.\n\t */\n\tpublic void addState(String state) {\n\t\tstates.add(state);\n\t}\n\n\t/**\n\t * @return The number of dimensions in this state\n\t */\n\tpublic int getNumDimensions() {\n\t\treturn states.size();\n\t}\n\t\n\t/**\n\t * A constructor for creating the default one dimensional vertex with an integer parameter.\n\t * \n\t * @param m1StateNumber\n\t * The state number at dimension one\n\t */\n\tpublic NFAVertexND(int m1StateNumber) {\n\t\tstates = new ArrayList<String>();\n\t\tstates.add(\"\" + m1StateNumber);\n\t}\n\n\t/**\n\t * A constructor for creating the default one dimensional vertex\n\t * \n\t * @param m1StateNumber\n\t * The state number at dimension one\n\t */\n\tpublic NFAVertexND(String m1StateNumber) {\n\t\tstates = new ArrayList<String>();\n\t\tstates.add(m1StateNumber);\n\t}\n\t\n\t/**\n\t * A constructor for creating the frequently used three dimensional vertex with an integer parameter.\n\t * \n\t * @param m1StateNumber\n\t * The state number at dimension one\n\t * @param m2StateNumber\n\t * The state number at dimension two\n\t * @param m3StateNumber\n\t * The state number at dimension three\n\t */\n\tpublic NFAVertexND(int m1StateNumber, int m2StateNumber, int m3StateNumber) {\n\t\tstates = new ArrayList<String>();\n\t\tstates.add(\"\" + m1StateNumber);\n\t\tstates.add(\"\" + m2StateNumber);\n\t\tstates.add(\"\" + m3StateNumber);\n\t}\n\n\t/**\n\t * A constructor for creating the frequently used three dimensional vertex.\n\t * \n\t * @param m1StateNumber\n\t * The state number at dimension one\n\t * @param m2StateNumber\n\t * The state number at dimension two\n\t * @param m3StateNumber\n\t * The state number at dimension three\n\t */\n\tpublic NFAVertexND(String m1StateNumber, String m2StateNumber, String m3StateNumber) {\n\t\tstates = new ArrayList<String>();\n\t\tstates.add(m1StateNumber);\n\t\tstates.add(m2StateNumber);\n\t\tstates.add(m3StateNumber);\n\t}\n\t\n\t/**\n\t * A constructor for creating the frequently used five dimensional vertex.\n\t * \n\t * @param m1StateNumber\n\t * The state number at dimension one\n\t * @param m2StateNumber\n\t * The state number at dimension two\n\t * @param m3StateNumber\n\t * The state number at dimension three\n\t * @param m4StateNumber\n\t * The state number at dimension four\n\t * @param m5StateNumber\n\t * The state number at dimension five\n\t */\n\tpublic NFAVertexND(int m1StateNumber, int m2StateNumber, int m3StateNumber, int m4StateNumber, int m5StateNumber) {\n\t\tstates = new ArrayList<String>();\n\t\tstates.add(\"\" + m1StateNumber);\n\t\tstates.add(\"\" + m2StateNumber);\n\t\tstates.add(\"\" + m3StateNumber);\n\t\tstates.add(\"\" + m4StateNumber);\n\t\tstates.add(\"\" + m5StateNumber);\n\t}\n\n\t/**\n\t * A constructor for creating the frequently used five dimensional vertex.\n\t * \n\t * @param m1StateNumber\n\t * The state number at dimension one\n\t * @param m2StateNumber\n\t * The state number at dimension two\n\t * @param m3StateNumber\n\t * The state number at dimension three\n\t * @param m4StateNumber\n\t * The state number at dimension four\n\t * @param m5StateNumber\n\t * The state number at dimension five\n\t */\n\tpublic NFAVertexND(String m1StateNumber, String m2StateNumber, String m3StateNumber, String m4StateNumber, String m5StateNumber) {\n\t\tstates = new ArrayList<String>();\n\t\tstates.add(m1StateNumber);\n\t\tstates.add(m2StateNumber);\n\t\tstates.add(m3StateNumber);\n\t\tstates.add(m4StateNumber);\n\t\tstates.add(m5StateNumber);\n\t}\n\t\n\t/**\n\t * A constructor for creating one multidimensional vertex from a list of integers\n\t * \n\t * @param mStates\n\t * The vertices\n\t */\n\tpublic NFAVertexND(int... mStates) {\n\n\t\tstates = new ArrayList<String>();\n\t\tfor (int i : mStates) {\n\t\t\tstates.add(\"\" + i);\n\t\t}\n\t}\n\n\t/**\n\t * A constructor for creating one multidimensional vertex from a list of strings\n\t * \n\t * @param mStates\n\t * The vertices\n\t */\n\tpublic NFAVertexND(String... mStates) {\n\n\t\tstates = new ArrayList<String>();\n\t\tfor (String i : mStates) {\n\t\t\tstates.add(i);\n\t\t}\n\t}\n\t\n\t/**\n\t * A constructor for creating one multidimensional vertex from\n\t * multidimensional vertices\n\t * \n\t * @param mStates\n\t * The vertices\n\t */\n\tpublic NFAVertexND(NFAVertexND... mStates) {\n\n\t\tstates = new ArrayList<String>();\n\t\tfor (NFAVertexND nfavnd : mStates) {\n\t\t\tfor (String i : nfavnd.states) {\n\t\t\t\tstates.add(i);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * A constructor for creating one multidimensional vertex from a collection\n\t * of multidimensional vertices\n\t * \n\t * @param mStates\n\t * The collection of vertices\n\t */\n\tpublic NFAVertexND(Collection<String> states) {\n\n\t\tthis.states = new ArrayList<String>();\n\t\tfor (String i : states) {\n\t\t\tthis.states.add(i);\n\t\t}\n\t}\n\t\n\t/**\n\t * A constructor for creating one multidimensional vertex from a set\n\t * of multidimensional vertices\n\t * \n\t * @param mStates\n\t * The collection of vertices\n\t */\n\tpublic NFAVertexND(Set<NFAVertexND> states) {\n\n\t\tthis.states = new ArrayList<String>();\n\t\tfor (NFAVertexND i : states) {\n\t\t\tthis.states.addAll(i.states);\n\t\t}\n\t}\n\n\t/**\n\t * @return A new instance of an NFAEdge equal to this instance.\n\t */\n\tpublic NFAVertexND copy() {\n\t\tNFAVertexND c = new NFAVertexND(states);\n\t\treturn c;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder(\"(\");\n\t\tIterator<String> i0 = states.iterator();\n\t\twhile (i0.hasNext()) {\n\t\t\tsb.append(i0.next());\n\t\t\tif (i0.hasNext()) {\n\t\t\t\tsb.append(\", \");\n\t\t\t}\n\t\t}\n\t\tsb.append(\")\");\n\t\treturn sb.toString();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (o == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!o.getClass().isAssignableFrom(this.getClass())) {\n\t\t\treturn false;\n\t\t}\n\t\tNFAVertexND p = (NFAVertexND) o;\n\t\tboolean condition = states.equals(p.getStates());\n\t\treturn condition;\n\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint total = 0;\n\t\tfor (String i : states) {\n\t\t\ttotal += i.hashCode();\n\t\t}\n\n\t\treturn total;\n\t}\n\n\t@Override\n\tpublic int compareTo(NFAVertexND o) {\n\n\t\treturn toString().compareTo(o.toString());\n\t}\n\n}", "public enum TransitionType {\n\tEPSILON,\n\tSYMBOL,\n\tOTHER\n}" ]
import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import analysis.NFAAnalyser.IdaSpecialTransitionLabel; import analysis.NFAAnalyserInterface.EdaAnalysisResultsESCC; import analysis.NFAAnalyserInterface.EdaAnalysisResultsFilter; import analysis.NFAAnalyserInterface.EdaAnalysisResultsParallel; import analysis.NFAAnalyserInterface.IdaAnalysisResultsIda; import nfa.NFAGraph; import nfa.NFAEdge; import nfa.NFAVertexND; import nfa.transitionlabel.*; import nfa.transitionlabel.TransitionLabel.TransitionType;
package analysis; public class ExploitStringBuilder implements ExploitStringBuilderInterface<EdaAnalysisResults, IdaAnalysisResults> { @Override public ExploitString buildEdaExploitString(EdaAnalysisResults results) throws InterruptedException { switch (results.edaCase) { case PARALLEL: return getParallelExploitString((EdaAnalysisResultsParallel) results); case ESCC: return getEsccExploitString((EdaAnalysisResultsESCC) results); case FILTER:
return getFilterExploitString((EdaAnalysisResultsFilter) results);
2
hecoding/Pac-Man
src/jeco/core/algorithm/moga/NSGAII.java
[ "public abstract class Algorithm<V extends Variable<?>> extends AlgObservable {\n\n protected Problem<V> problem = null;\n // Attribute to stop execution of the algorithm.\n protected boolean stop = false;\n \n /**\n * Allows to stop execution after finishing the current generation; must be\n * taken into account in children classes.\n */\n public void stopExection() {\n stop = true;\n }\n\n public boolean isStopped() {\n return this.stop;\n }\n\n public Algorithm(Problem<V> problem) {\n this.problem = problem;\n }\n\n public void setProblem(Problem<V> problem) {\n this.problem = problem;\n }\n\n public abstract void initialize();\n\n public abstract void step();\n\n public abstract Solutions<V> execute();\n}", "public abstract class CrossoverOperator<T extends Variable<?>> {\n abstract public Solutions<T> execute(Solution<T> parent1, Solution<T> parent2);\n}", "public abstract class MutationOperator<T extends Variable<?>> {\n\tprotected double probability;\n\t\n\tpublic MutationOperator(double probability) {\n\t\tthis.probability = probability;\n\t}\n\t\n\tpublic void setProbability(double probability) {\n\t\tthis.probability = probability;\n\t}\n\t\n\tpublic double getProb(){\n\t\treturn probability;\n\t}\n\n\tabstract public Solution<T> execute(Solution<T> solution);\n}", "public abstract class Problem<V extends Variable<?>> {\n //private static final Logger logger = Logger.getLogger(Problem.class.getName());\n\n public static final double INFINITY = Double.POSITIVE_INFINITY;\n protected int numberOfVariables;\n protected int numberOfObjectives;\n protected double[] lowerBound;\n protected double[] upperBound;\n\n protected int maxEvaluations;\n protected int numEvaluations;\n\n public Problem(int numberOfVariables, int numberOfObjectives) {\n this.numberOfVariables = numberOfVariables;\n this.numberOfObjectives = numberOfObjectives;\n this.lowerBound = new double[numberOfVariables];\n this.upperBound = new double[numberOfVariables];\n this.maxEvaluations = Integer.MAX_VALUE;\n resetNumEvaluations();\n }\n\n public int getNumberOfVariables() {\n return numberOfVariables;\n }\n\n public int getNumberOfObjectives() {\n return numberOfObjectives;\n }\n\n public double getLowerBound(int i) {\n return lowerBound[i];\n }\n\n public double getUpperBound(int i) {\n return upperBound[i];\n }\n\n public int getMaxEvaluations() {\n return maxEvaluations;\n }\n\n public void setMaxEvaluations(int maxEvaluations) {\n this.maxEvaluations = maxEvaluations;\n }\n\n public int getNumEvaluations() {\n return numEvaluations;\n }\n\n public final void resetNumEvaluations() {\n numEvaluations = 0;\n }\n \n public void setNumEvaluations(int numEvaluations) {\n this.numEvaluations = numEvaluations;\n }\n\n public abstract Solutions<V> newRandomSetOfSolutions(int size);\n\n public void evaluate(Solutions<V> solutions) {\n for (Solution<V> solution : solutions) {\n evaluate(solution);\n }\n }\n\n public abstract void evaluate(Solution<V> solution);\n\n @Override\n public abstract Problem<V> clone();\n\n public boolean reachedMaxEvaluations() {\n return (numEvaluations >= maxEvaluations);\n }\n}", "@SuppressWarnings(\"serial\")\npublic class Solutions<V extends Variable<?>> extends ArrayList<Solution<V>> {\n\n public Solutions() {\n super();\n }\n\n /**\n * Keep this set of solutions non-dominated. Returns the set of dominated\n * solutions.\n *\n * @param comparator Comparator used.\n * @return The set of dominated solutions.\n */\n public Solutions<V> reduceToNonDominated(Comparator<Solution<V>> comparator) {\n Solutions<V> rest = new Solutions<V>();\n int compare;\n Solution<V> solI;\n Solution<V> solJ;\n for (int i = 0; i < size() - 1; i++) {\n solI = get(i);\n for (int j = i + 1; j < size(); j++) {\n solJ = get(j);\n compare = comparator.compare(solI, solJ);\n if (compare < 0) { // i dominates j\n rest.add(solJ);\n remove(j--);\n } else if (compare > 0) { // j dominates i\n rest.add(solI);\n remove(i--);\n j = size();\n } else if (solI.equals(solJ)) { // both are equal, just one copy\n remove(j--);\n }\n }\n }\n return rest;\n }\n\n @Override\n public String toString() {\n StringBuilder buffer = new StringBuilder();\n for (Solution<V> solution : this) {\n buffer.append(solution.toString());\n buffer.append(\"\\n\");\n }\n return buffer.toString();\n }\n\n /**\n * Function that reads a set of solutions from a file.\n * @param filePath File path\n * @return The set of solutions in the archive.\n * @throws IOException \n * @throws java.lang.Exception\n */\n public static Solutions<Variable<?>> readFrontFromFile(String filePath) throws IOException {\n Solutions<Variable<?>> solutions = new Solutions<Variable<?>>();\n BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));\n String line = reader.readLine();\n while (line != null) {\n String[] objectives = line.split(\" \");\n if (line.length() > 0 && objectives != null && objectives.length > 0) {\n Solution<Variable<?>> solution = new Solution<Variable<?>>(objectives.length);\n for (int i = 0; i < objectives.length; ++i) {\n solution.getObjectives().set(i, Double.valueOf(objectives[i]));\n }\n solutions.add(solution);\n }\n line = reader.readLine();\n }\n reader.close();\n return solutions;\n }\n\n /**\n * Function that reads N sets of solutions from a file.\n *\n * @param filePath File path\n * @return The set of solutions in the archive. Each solution set is separated\n * in the file by a blank line.\n */\n public static ArrayList<Solutions<Variable<?>>> readFrontsFromFile(String filePath) throws FileNotFoundException, IOException {\n ArrayList<Solutions<Variable<?>>> result = new ArrayList<Solutions<Variable<?>>>();\n BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));\n String line = reader.readLine();\n Solutions<Variable<?>> solutions = new Solutions<Variable<?>>();\n while (line != null) {\n String[] objectives = line.split(\" \");\n if (line.length() <= 0 || objectives == null || objectives.length == 0) {\n if (solutions.size() > 0) {\n result.add(solutions);\n }\n solutions = new Solutions<Variable<?>>();\n } else {\n Solution<Variable<?>> solution = new Solution<Variable<?>>(objectives.length);\n for (int i = 0; i < objectives.length; ++i) {\n solution.getObjectives().set(i, Double.valueOf(objectives[i]));\n }\n solutions.add(solution);\n }\n line = reader.readLine();\n }\n reader.close();\n return result;\n }\n \n /**\n * Function that normalizes a set of fronts in the given interval.\n * @param setOfSolutions Set of fronts\n * @param dim Number of objectives\n * @param lowerBound lower bound\n * @param upperBound upper bound\n */\n public static void normalize(ArrayList<Solutions<Variable<?>>> setOfSolutions, int dim, double lowerBound, double upperBound) {\n double[] mins = new double[dim];\n double[] maxs = new double[dim];\n for (int i = 0; i < dim; ++i) {\n mins[i] = Double.POSITIVE_INFINITY;\n maxs[i] = Double.NEGATIVE_INFINITY;\n }\n\n Solutions<Variable<?>> allTheSolutions = new Solutions<Variable<?>>();\n for (Solutions<Variable<?>> solutions : setOfSolutions) {\n allTheSolutions.addAll(solutions);\n }\n // Get the maximum and minimun values:\n for (Solution<Variable<?>> solution : allTheSolutions) {\n for (int i = 0; i < dim; ++i) {\n double objI = solution.getObjectives().get(i);\n if (objI < mins[i]) {\n mins[i] = objI;\n }\n if (objI > maxs[i]) {\n maxs[i] = objI;\n }\n }\n }\n\n // Normalize:\n for (Solution<Variable<?>> solution : allTheSolutions) {\n for (int i = 0; i < dim; ++i) {\n double objI = solution.getObjectives().get(i);\n double newObjI = 1.0 + (objI - mins[i]) / (maxs[i] - mins[i]);\n solution.getObjectives().set(i, newObjI);\n }\n }\n\n }\n\n /**\n * Function that normalize a set of fronts in the interval [1,2]\n * @param setOfSolutions Set of fronts\n * @param dim Number of objectives\n */\n public static void normalize(ArrayList<Solutions<Variable<?>>> setOfSolutions, int dim) {\n Solutions.normalize(setOfSolutions, dim, 1.0, 2.0);\n } \n}", "public class Variable<T> {\n protected T value;\n\n public Variable(T value) {\n this.value = value;\n }\n\n public T getValue() { return value; }\n\n public void setValue(T value) { this.value = value; }\n \n @Override\n public Variable<T> clone() {\n return new Variable<T>(value);\n }\n\n @SuppressWarnings(\"unchecked\")\n\t\t@Override\n public boolean equals(Object right) {\n Variable<T> var = (Variable<T>)right;\n return this.value.equals(var.value);\n }\n \n @Override\n public String toString()\n {\n \treturn value.toString();\n }\n}", "public class Maths {\n\n public static double sum(List<Double> numbers) {\n double res = 0;\n for (Double number : numbers) {\n res += number;\n }\n return res;\n }\n\n public static double mean(List<Double> numbers) {\n if (numbers.isEmpty()) {\n return 0;\n }\n double res = sum(numbers) / numbers.size();\n return res;\n }\n\n public static double median(List<Double> numbers) {\n Collections.sort(numbers);\n int middle = numbers.size() / 2;\n if (numbers.size() % 2 == 1) {\n return numbers.get(middle);\n } else {\n return (numbers.get(middle - 1) + numbers.get(middle)) / 2.0;\n }\n }\n\n public static double std(List<Double> numbers) {\n double res = 0;\n double avg = mean(numbers);\n for(Double number : numbers) {\n res += Math.pow(number-avg, 2);\n }\n res = Math.sqrt(res/(numbers.size()-1));\n return res;\n }\n \n public static <V extends Variable<?>> double calculateHypervolume(Solutions<V> solFront, int numObjectives) {\n \n double [][] front = new double[solFront.size()][numObjectives];\n for (int i = 0; i < solFront.size(); i++) {\n for (int obj=0; obj<numObjectives; obj++) {\n front[i][obj] = solFront.get(i).getObjective(obj);\n }\n }\n \n Hypervolume hv = new Hypervolume();\n \n return hv.calculateHypervolume(front, front.length, numObjectives);\n }\n \n}" ]
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.logging.Logger; import jeco.core.algorithm.Algorithm; import jeco.core.operator.assigner.CrowdingDistance; import jeco.core.operator.assigner.FrontsExtractor; import jeco.core.operator.comparator.ComparatorNSGAII; import jeco.core.operator.comparator.SolutionDominance; import jeco.core.operator.crossover.CrossoverOperator; import jeco.core.operator.mutation.MutationOperator; import jeco.core.operator.selection.SelectionOperator; import jeco.core.problem.Problem; import jeco.core.problem.Solution; import jeco.core.problem.Solutions; import jeco.core.problem.Variable; import jeco.core.util.Maths;
package jeco.core.algorithm.moga; /** * * * Input parameters: - MAX_GENERATIONS - MAX_POPULATION_SIZE * * Operators: - CROSSOVER: Crossover operator - MUTATION: Mutation operator - * SELECTION: Selection operator * * @author José L. Risco-Martín * */ public class NSGAII<T extends Variable<?>> extends Algorithm<T> { private static final Logger logger = Logger.getLogger(NSGAII.class.getName()); ///////////////////////////////////////////////////////////////////////// protected int maxGenerations; protected int maxPopulationSize; ///////////////////////////////////////////////////////////////////////// protected Comparator<Solution<T>> dominance; protected int currentGeneration; protected Solutions<T> population; public Solutions<T> getPopulation() { return population; } protected MutationOperator<T> mutationOperator;
protected CrossoverOperator<T> crossoverOperator;
1
BlackCraze/GameResourceBot
src/main/java/de/blackcraze/grb/commands/concrete/Group.java
[ "public interface BaseCommand {\r\n\r\n void run(Scanner scanner, Message message);\r\n\r\n default String help(Message message) {\r\n String className = this.getClass().getSimpleName();\r\n String key = className.toUpperCase();\r\n return Resource.getHelp(key, getResponseLocale(message), BotConfig.getConfig().PREFIX,\r\n \"#\" + BotConfig.getConfig().CHANNEL);\r\n }\r\n\r\n static void checkPublic(Message message) {\r\n if (!ChannelType.TEXT.equals(message.getChannelType())) {\r\n Speaker.err(message,\r\n String.format(\r\n Resource.getError(\"PUBLIC_COMMAND_ONLY\", getResponseLocale(message)),\r\n \"#\" + BotConfig.getConfig().CHANNEL));\r\n throw new IllegalStateException(\"Public command only\");\r\n }\r\n }\r\n\r\n static Collection<Class<BaseCommand>> getCommandClasses() {\r\n ClassPath classPath;\r\n try {\r\n classPath = ClassPath.from(ClassLoader.getSystemClassLoader());\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n return Collections.emptyList();\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n Collection<Class<BaseCommand>> classes =\r\n classPath.getTopLevelClassesRecursive(\"de.blackcraze.grb.commands\").stream()\r\n .map(aClassInfo -> ((Class<BaseCommand>) aClassInfo.load()))\r\n .collect(Collectors.toList());\r\n return classes.stream().filter(BaseCommand.class::isAssignableFrom)\r\n .collect(Collectors.toList());\r\n }\r\n}\r", "public class Speaker {\r\n\r\n public static class Reaction {\r\n public final static String SUCCESS = \"✅\";\r\n public final static String FAILURE = \"❌\";\r\n }\r\n\r\n public static void say(MessageChannel channel, String text) {\r\n say(channel, text, \"\", \"\");\r\n }\r\n\r\n public static void say(MessageChannel channel, List<String> texts) {\r\n texts.forEach(text -> say(channel, text));\r\n }\r\n\r\n public static void sayCode(MessageChannel channel, List<String> texts) {\r\n texts.forEach(text -> sayCode(channel, text));\r\n }\r\n\r\n public static void sayCode(MessageChannel channel, String text) {\r\n say(channel, text, \"```dsconfig\\n\", \"\\n```\");\r\n }\r\n\r\n private static void say(MessageChannel channel, String text, String prefix, String suffix) {\r\n if (StringUtils.isEmpty(text)) {\r\n return;\r\n }\r\n StringTokenizer t = new StringTokenizer(text, \"\\n\", true);\r\n StringBuffer b = new StringBuffer(prefix);\r\n b.append(suffix);\r\n while (t.hasMoreTokens()) {\r\n String token = t.nextToken();\r\n if (b.length() + token.length() <= 2000) {\r\n b.insert(b.length() - suffix.length(), token);\r\n } else {\r\n channel.sendMessage(b.toString()).queue();\r\n b = new StringBuffer(prefix);\r\n b.append(token);\r\n b.append(suffix);\r\n }\r\n }\r\n channel.sendMessage(b.toString()).queue();\r\n }\r\n\r\n public static void err(Message message, String text) {\r\n message.addReaction(Reaction.FAILURE).queue();\r\n say(message.getChannel(), text);\r\n }\r\n\r\n}\r", "public class Resource {\r\n\r\n private Resource() {\r\n\r\n }\r\n\r\n public static String guessItemKey(String item, Locale locale) {\r\n ResourceBundle resourceBundle =\r\n ResourceBundle.getBundle(\"items\", locale, new ResourceBundleControl());\r\n\r\n String itemTyped = correctItemName(item);\r\n String bestMatch = null;\r\n int diffScore = Integer.MAX_VALUE;\r\n\r\n for (String key : resourceBundle.keySet()) {\r\n String itemName = correctItemName(resourceBundle.getString(key));\r\n if (itemTyped.equals(itemName)) {\r\n return key;\r\n } else {\r\n int score = compareFuzzy(itemName, itemTyped);\r\n if (score < diffScore) {\r\n diffScore = score;\r\n bestMatch = key;\r\n }\r\n }\r\n }\r\n if (scoreIsGood(itemTyped, diffScore)) {\r\n return bestMatch;\r\n } else {\r\n throw new RuntimeException(String.format(\"Can't find %s in %s %s.\", item, \"items\",\r\n locale.toLanguageTag()));\r\n }\r\n }\r\n\r\n public static String guessHelpKey(String key, Locale locale) {\r\n ResourceBundle resourceBundle =\r\n ResourceBundle.getBundle(\"help\", locale, new ResourceBundleControl());\r\n String keyTyped = StringUtils.upperCase(key);\r\n String bestMatch = null;\r\n int diffScore = Integer.MAX_VALUE;\r\n\r\n for (String helpKey : resourceBundle.keySet()) {\r\n if (keyTyped.equals(helpKey)) {\r\n return helpKey;\r\n } else {\r\n int score = compareFuzzy(helpKey, keyTyped);\r\n if (score < diffScore) {\r\n diffScore = score;\r\n bestMatch = helpKey;\r\n }\r\n }\r\n }\r\n if (scoreIsGood(keyTyped, diffScore)) {\r\n return bestMatch;\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n private static boolean scoreIsGood(String itemTyped, int diffScore) {\r\n return itemTyped.length() * 0.5 >= diffScore;\r\n }\r\n\r\n public static String correctItemName(String item) {\r\n return item.toUpperCase().replaceAll(\"-\", \"\").replaceAll(\"\\\\s+\", \"\").replace(\"Ü\", \"U\")\r\n .replace(\"Ä\", \"A\").replace(\"Ö\", \"O\");\r\n }\r\n\r\n public static int compareFuzzy(String one, String another) {\r\n DiffMatchPatch matcher = new DiffMatchPatch();\r\n LinkedList<Diff> diffs = matcher.diff_main(one, another);\r\n return matcher.diff_levenshtein(diffs);\r\n }\r\n\r\n public static String getItem(String key, Locale locale) {\r\n return getResource(key, locale, \"items\");\r\n }\r\n\r\n public static String getError(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"errors\", args);\r\n }\r\n\r\n public static String getHeader(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"headers\", args);\r\n }\r\n\r\n public static String getHelp(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"help\", args);\r\n }\r\n\r\n public static String getInfo(String key, Locale locale, Object... args) {\r\n return getResource(key, locale, \"inform\", args);\r\n }\r\n\r\n private static String getResource(String key, Locale locale, String baseName, Object... args) {\r\n ResourceBundle resourceBundle =\r\n ResourceBundle.getBundle(baseName, locale, new ResourceBundleControl());\r\n String string = resourceBundle.getString(key);\r\n if (args != null && args.length > 0) {\r\n return String.format(string, args);\r\n } else {\r\n return string;\r\n }\r\n }\r\n\r\n}\r", "public final class PrintUtils {\r\n\r\n private PrintUtils() {}\r\n\r\n public static List<String> prettyPrint(PrintableTable... stocks) {\r\n List<String> returnHandle = new ArrayList<>(stocks.length);\r\n for (PrintableTable stock : stocks) {\r\n if (stock != null) {\r\n int boardWidth = stock.getWidth();\r\n int headerWidth = boardWidth - 2; // outer borders\r\n StringBuilder b = new StringBuilder();\r\n Board board = new Board(boardWidth);\r\n // board.showBlockIndex(true); // DEBUG\r\n Block header = new Block(board, headerWidth, 1, stock.getHeader());\r\n header.setDataAlign(Block.DATA_MIDDLE_LEFT);\r\n board.setInitialBlock(header);\r\n\r\n Table table = new Table(board, boardWidth, stock.getTitles(), stock.getRows(),\r\n stock.getWidths(), stock.getAligns());\r\n board.appendTableTo(0, Board.APPEND_BELOW, table);\r\n\r\n for (int i = 0; i < stock.getFooter().size(); i++) {\r\n Block footer =\r\n new Block(board, stock.getWidths().get(i), 1, stock.getFooter().get(i));\r\n footer.setDataAlign(stock.getAligns().get(i));\r\n if (i == 0) {\r\n header.getMostBelowBlock().setBelowBlock(footer);\r\n } else {\r\n header.getMostBelowBlock().getMostRightBlock().setRightBlock(footer);\r\n }\r\n }\r\n\r\n board.build();\r\n b.append(board.getPreview());\r\n returnHandle.add(b.toString());\r\n }\r\n }\r\n return returnHandle;\r\n }\r\n\r\n public static List<String> prettyPrint(Map<String, Long> stocks, Locale locale) {\r\n StringBuilder b = new StringBuilder();\r\n for (Entry<String, Long> entry : stocks.entrySet()) {\r\n if (Long.MIN_VALUE != entry.getValue()) {\r\n // In this case, it is the misspelled name. See\r\n // de.blackcraze.grb.util.CommandUtils.parseStocks(Scanner,\r\n // Locale)\r\n String localisedStockName = Resource.getItem(entry.getKey(), locale);\r\n b.append(localisedStockName);\r\n b.append(\": \");\r\n b.append(String.format(locale, \"%,d\", entry.getValue()));\r\n b.append(\"\\n\");\r\n }\r\n }\r\n return Collections.singletonList(b.toString());\r\n }\r\n\r\n public static String getDiffFormatted(Date from, Date to, Locale locale) {\r\n Duration duration = new Duration(to.getTime() - from.getTime()); // in\r\n // milliseconds\r\n PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever()//\r\n .appendWeeks().appendSuffix(Resource.getHeader(\"WEEKS\", locale)).appendSeparator(\" \")//\r\n .appendDays().appendSuffix(Resource.getHeader(\"DAYS\", locale)).appendSeparator(\" \")//\r\n .appendHours().appendSuffix(Resource.getHeader(\"HOURS\", locale)).appendSeparator(\" \")//\r\n .appendMinutes().appendSuffix(Resource.getHeader(\"MINUTES\", locale)).appendSeparator(\" \")//\r\n .appendSeconds().appendSuffix(Resource.getHeader(\"SECONDS\", locale))//\r\n .toFormatter();\r\n String fullTimeAgo = formatter.print(duration.toPeriod(PeriodType.yearMonthDayTime()));\r\n return Arrays.stream(fullTimeAgo.split(\" \")).limit(2).collect(Collectors.joining(\" \"));\r\n }\r\n\r\n public static List<String> prettyPrintStocks(List<StockType> stockTypes, Locale locale) {\r\n if (stockTypes.isEmpty()) {\r\n return Collections.singletonList(Resource.getError(\"RESOURCE_UNKNOWN\", locale));\r\n }\r\n List<String> headers = Arrays.asList(Resource.getHeader(\"USER\", locale),\r\n Resource.getHeader(\"QUANTITY\", locale), Resource.getHeader(\"UPDATED\", locale));\r\n List<Integer> aligns = Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_MIDDLE_RIGHT,\r\n Block.DATA_MIDDLE_RIGHT);\r\n\r\n PrintableTable[] tables = new PrintableTable[stockTypes.size()];\r\n for (int i = 0; i < stockTypes.size(); i++) {\r\n StockType type = stockTypes.get(i);\r\n List<Stock> stocks = getStockDao().findStocksByType(type);\r\n List<List<String>> rows = new ArrayList<>(stocks.size());\r\n long sumAmount = 0;\r\n if (stocks.isEmpty()) {\r\n rows.add(Arrays.asList(\"-\", \"-\", \"-\"));\r\n }\r\n for (Stock stock : stocks) {\r\n String mateName = stock.getMate().getName();\r\n String amount = String.format(locale, \"%,d\", stock.getAmount());\r\n String updated = PrintUtils.getDiffFormatted(stock.getUpdated(), new Date(), locale);\r\n rows.add(Arrays.asList(mateName, amount, updated));\r\n sumAmount += stock.getAmount();\r\n }\r\n String resourceKey = type.getName();\r\n String resourceName = Resource.getItem(resourceKey, locale);\r\n List<String> summary =\r\n Arrays.asList(resourceName, String.format(locale, \"%,d\", sumAmount), \"\");\r\n tables[i] = new PrintableTable(resourceName, summary, headers, rows, aligns);\r\n }\r\n return PrintUtils.prettyPrint(tables);\r\n }\r\n\r\n public static String prettyPrintStockTypes(List<StockType> stockTypes, Locale responseLocale) {\r\n StringBuilder b = new StringBuilder();\r\n if (stockTypes.isEmpty()) {\r\n b.append(Resource.getError(\"NO_DATA\", responseLocale));\r\n }\r\n for (StockType type : stockTypes) {\r\n String resourceKey = type.getName();\r\n String resourceName = Resource.getItem(resourceKey, responseLocale);\r\n b.append(resourceName);\r\n b.append(\"\\n\");\r\n }\r\n return b.toString();\r\n }\r\n\r\n public static List<String> prettyPrintMate(List<Mate> mates, Locale locale) {\r\n if (mates.isEmpty()) {\r\n return Collections.singletonList(Resource.getError(\"USER_UNKNOWN\", locale));\r\n }\r\n List<String> headers = Arrays.asList(Resource.getHeader(\"RAW_MATERIAL\", locale),\r\n Resource.getHeader(\"QUANTITY\", locale), Resource.getHeader(\"UPDATED\", locale));\r\n List<Integer> aligns = Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_MIDDLE_RIGHT,\r\n Block.DATA_MIDDLE_RIGHT);\r\n\r\n PrintableTable[] tables = new PrintableTable[mates.size()];\r\n StockComparator comp = new StockComparator(locale);\r\n for (int i = 0; i < mates.size(); i++) {\r\n Mate mate = mates.get(i);\r\n List<Stock> stocks = getStockDao().findStocksByMate(mate);\r\n stocks.sort(comp);\r\n List<List<String>> rows = new ArrayList<>(stocks.size());\r\n for (Stock stock : stocks) {\r\n String resourceKey = stock.getType().getName();\r\n String resourceName = Resource.getItem(resourceKey, locale);\r\n String amount = String.format(locale, \"%,d\", stock.getAmount());\r\n String updated = PrintUtils.getDiffFormatted(stock.getUpdated(), new Date(), locale);\r\n rows.add(Arrays.asList(resourceName, amount, updated));\r\n }\r\n if (stocks.isEmpty()) {\r\n rows.add(Arrays.asList(\"-\", \"-\", \"-\"));\r\n }\r\n tables[i] = new PrintableTable(mate.getName(), Collections.emptyList(), headers, rows,\r\n aligns);\r\n }\r\n return PrintUtils.prettyPrint(tables);\r\n }\r\n}\r", "public static Locale getResponseLocale(Message message) {\r\n Locale channelLocale = getDefaultLocale();\r\n Mate mate = getMateDao().getOrCreateMate(message, channelLocale);\r\n if (mate != null && !StringUtils.isEmpty(mate.getLanguage())) {\r\n return new Locale(mate.getLanguage());\r\n }\r\n return channelLocale;\r\n}\r", "public static List<String> parseGroupName(Scanner scanner) {\r\n List<String> result = new ArrayList<>();\r\n while (scanner.hasNext()) {\r\n result.add(scanner.next());\r\n }\r\n return result;\r\n}\r" ]
import de.blackcraze.grb.commands.BaseCommand; import de.blackcraze.grb.core.Speaker; import de.blackcraze.grb.i18n.Resource; import de.blackcraze.grb.model.PrintableTable; import de.blackcraze.grb.model.entity.StockType; import de.blackcraze.grb.model.entity.StockTypeGroup; import de.blackcraze.grb.util.PrintUtils; import de.blackcraze.grb.util.StockTypeComparator; import de.blackcraze.grb.util.wagu.Block; import net.dv8tion.jda.api.entities.Message; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Scanner; import static de.blackcraze.grb.util.CommandUtils.getResponseLocale; import static de.blackcraze.grb.util.CommandUtils.parseGroupName; import static de.blackcraze.grb.util.InjectorUtils.getMateDao; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeDao; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeGroupDao;
Speaker.err(message, msg); } }; public static final BaseCommand groupAdd = (Scanner scanner, Message message) -> { Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "ADD"); if (groupOpt.isPresent()) { List<StockType> stockTypes = getTargetStockTypes(scanner, message, "ADD"); StockTypeGroup group = groupOpt.get(); if (!stockTypes.isEmpty()) { List<StockType> types = group.getTypes(); if (types == null) { types = new ArrayList<>(); group.setTypes(types); } types.addAll(stockTypes); // removing doubles types = new ArrayList<>(new HashSet<>(types)); group.setTypes(types); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } }; public static final BaseCommand groupRemove = (Scanner scanner, Message message) -> { Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "REMOVE"); if (groupOpt.isPresent()) { List<StockType> stockTypes = getTargetStockTypes(scanner, message, "REMOVE"); StockTypeGroup group = groupOpt.get(); if (!stockTypes.isEmpty()) { List<StockType> types = group.getTypes(); if (types == null) { group.setTypes(new ArrayList<>()); } group.getTypes().removeAll(stockTypes); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } }; public static final BaseCommand groupDelete = (Scanner scanner, Message message) -> { List<String> groupNames = parseGroupName(scanner); List<String> unknown = new ArrayList<>(); for (String groupName : groupNames) { Optional<StockTypeGroup> group = getStockTypeGroupDao().findByName(groupName); if (group.isPresent()) { getStockTypeGroupDao().delete(group.get()); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } else { unknown.add(groupName); } } if (groupNames.isEmpty()) { Speaker.err(message, Resource.getError("GROUP_DELETE_UNKNOWN", getResponseLocale(message))); } if (!unknown.isEmpty()) { String msg = String.format( Resource.getError("GROUP_DELETE_UNKNOWN", getResponseLocale(message)), unknown.toString()); Speaker.err(message, msg); } }; public static final BaseCommand groupRename = (Scanner scanner, Message message) -> { Locale locale = getResponseLocale(message); Optional<StockTypeGroup> groupOpt = getTargetGroup(scanner, message, "RENAME"); if (groupOpt.isPresent()) { if (scanner.hasNext()) { String groupName = scanner.next(); Optional<StockTypeGroup> newName = getStockTypeGroupDao().findByName(groupName); if (newName.isPresent()) { String msg = String.format( /* TODO maybe a standalone error message? */ Resource.getError("GROUP_CREATE_IN_USE", locale), groupName); Speaker.err(message, msg); } else { StockTypeGroup group = groupOpt.get(); group.setName(groupName); getStockTypeGroupDao().update(group); message.addReaction(Speaker.Reaction.SUCCESS).queue(); } } else { Speaker.err(message, Resource.getError("GROUP_RENAME_UNKNOWN", locale)); } } }; public static final BaseCommand groupList = (Scanner scanner, Message message) -> { Locale locale = getResponseLocale(message); List<String> groupNames = parseGroupName(scanner); List<StockTypeGroup> groups; if (groupNames.isEmpty()) { groups = getStockTypeGroupDao().findAll(); } else { groups = getStockTypeGroupDao().findByNameLike(groupNames); } List<List<String>> rows = new ArrayList<>(); for (StockTypeGroup stockTypeGroup : groups) { List<StockType> types = stockTypeGroup.getTypes(); String amount = String.format(locale, "%,d", types != null ? types.size() : 0); rows.add(Arrays.asList(stockTypeGroup.getName(), amount)); if (types != null) { types.sort(new StockTypeComparator(locale)); for (Iterator<StockType> it2 = types.iterator(); it2.hasNext();) { StockType stockType = it2.next(); String localisedStockName = Resource.getItem(stockType.getName(), locale); String tree = it2.hasNext() ? "├─ " : "└─ "; rows.add(Arrays.asList(tree + localisedStockName, " ")); } } } if (rows.isEmpty()) { rows.add(Arrays.asList(" ", " ")); } List<String> titles = Arrays.asList(Resource.getHeader("NAME", locale), Resource.getHeader("QUANTITY", locale)); String header = Resource.getHeader("GROUP_LIST_HEADER", locale); List<Integer> aligns = Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_BOTTOM_RIGHT); List<String> footer = Collections.emptyList(); PrintableTable table = new PrintableTable(header, footer, titles, rows, aligns);
Speaker.sayCode(message.getChannel(), PrintUtils.prettyPrint(table));
3
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/views/CheckBox.java
[ "public interface Context {\n /**\n * @return Context id\n */\n int contextId();\n\n}", "@SideOnly(Side.CLIENT)\npublic class GuiManager {\n /**\n * Current MineDroid theme\n */\n public static HashMap<Integer, Style> themes = new HashMap<Integer, Style>();\n\n /**\n * Minecraft client instance\n */\n @SideOnly(Side.CLIENT)\n protected static Minecraft mc = Minecraft.getMinecraft();\n\n /**\n * Amounts of generated classes ids\n */\n protected final static HashMap<Class, Integer> amounts = new HashMap<Class, Integer>();\n\n protected static Overlay inGameGui;\n\n /**\n * Default MineDroid XML NameSpace\n */\n public static final String NS = \"http://onkiup.com/minecraft/xml\";\n\n /**\n * Utilizing module Context\n */\n protected Class r;\n\n /**\n * Main Minecraft thread\n */\n protected static Thread mainThread;\n\n /**\n * Initialized MineDroid\n *\n * @param r Mod R class\n */\n public GuiManager(Class r) {\n this.r = r;\n mainThread = Thread.currentThread();\n }\n\n protected static StringCache fontRenderer = new StringCache();\n\n /**\n * generates ids for Overlays\n *\n * @param clazz Class for which should id be generated\n * @return int\n */\n public static int generateId(Class clazz) {\n if (!amounts.containsKey(clazz)) {\n amounts.put(clazz, 0);\n }\n\n int id = amounts.get(clazz);\n amounts.put(clazz, ++id);\n\n return id;\n }\n\n /**\n * Returns Minecraft window size\n *\n * @return Point\n */\n public static Point getWindowSize() {\n Minecraft mc = Minecraft.getMinecraft();\n return new Point(mc.displayWidth, mc.displayHeight);\n }\n\n /**\n * Returns Minecraft's window scaled size\n *\n * @return ScaledResolution\n */\n public static ScaledResolution getScale() {\n Minecraft mc = Minecraft.getMinecraft();\n return new ScaledResolution(mc, mc.displayWidth, mc.displayHeight);\n }\n\n /**\n * Scales coordinate\n *\n * @param x Coordinate value\n * @return int\n */\n public static int scale(int x) {\n ScaledResolution r = getScale();\n return x * r.getScaleFactor();\n }\n\n /**\n * Current GL_SCISSOR clip rect\n */\n protected static Rect clip;\n\n /**\n * Stack of GL_SCISSOR clip rects\n */\n protected static ArrayList<Rect> clips = new ArrayList<Rect>();\n\n /**\n * Adds GL_SCISSOR area\n *\n * @param newClip GL_SCISSOR area\n */\n public static void addClipRect(Rect newClip) {\n if (clip == null) {\n clip = new Rect(new Point(0, 0), getWindowSize());\n } else {\n clips.add(clip);\n }\n newClip = newClip.and(clip);\n if (newClip == null) {\n // The new clip hasn't common pixels with the parent clip.\n // disallow ANY modification\n newClip = new Rect(0, 0, 0, 0);\n }\n\n clip = newClip;\n Point size = clip.getSize();\n// BorderDrawable border = new BorderDrawable(new Color(0x6600ff00));\n// border.setSize(size);\n// border.draw(clip.coords());\n\n Point windowSize = getWindowSize();\n\n GL11.glEnable(GL11.GL_SCISSOR_TEST);\n GL11.glScissor(scale(clip.left), windowSize.y - scale(clip.bottom), scale(size.x), scale(size.y));\n\n// ColorDrawable d = new ColorDrawable(0x66000000);\n// d.setSize(getWindowSize());\n// d.draw(new Point(0, 0));\n// System.out.println(\"+Clip: \"+newClip+\" (\"+clips.size()+\")\");\n// GL11.glViewport(newClip.left, newClip.top, newClip.right, newClip.bottom);\n }\n\n /**\n * Drops last added GL_SCISSOR rect\n */\n public static void restoreClipRect() {\n// System.out.println(\"-Clip: \"+clip+\" (\"+clips.size()+\")\");\n if (clips.size() > 0) {\n clip = clips.remove(clips.size() - 1);\n Point size = clip.getSize();\n GL11.glScissor(scale(clip.left), getWindowSize().y - scale(clip.bottom), scale(size.x), scale(size.y));\n } else {\n clip = null;\n }\n// GL11.glViewport(clip.left, clip.top, clip.right, clip.bottom);\n if (clip == null) {\n GL11.glDisable(GL11.GL_SCISSOR_TEST);\n }\n }\n\n /**\n * Inflates layout from XML file\n *\n * @param context Mod context\n * @param source XML file location\n * @return View\n * @see ResourceManager#inflateLayout(Context, ResourceLocation, Style)\n * @deprecated\n */\n public static View inflateLayout(Context context, ResourceLocation source) {\n return ResourceManager.inflateLayout(context, source, getTheme(context));\n }\n\n /**\n * Loads XML file into XMLParser, wraps it into XmlHelper and returns it\n *\n * @param context Mod context\n * @param source Xml location\n * @return XmlHelper\n * @see ResourceManager#getXmlHelper(Context, ResourceLocation)\n * @deprecated\n */\n public static XmlHelper getXmlHelper(Context context, ResourceLocation source) {\n return ResourceManager.getXmlHelper(context, source);\n }\n\n /**\n * Inflates view from a XML Node element\n *\n * @param context Mod context\n * @param node node element\n * @param theme theme with which View should be inflated\n * @return View\n * @throws ClassNotFoundException\n * @throws IllegalAccessException\n * @throws InstantiationException\n * @throws InvalidClassException\n * @see ResourceManager#processNode(Context, Node, Style)\n * @deprecated\n */\n public static View processNode(Context context, Node node, Style theme) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvalidClassException, NoSuchMethodException, InvocationTargetException {\n return ResourceManager.processNode(new XmlHelper(context, node), theme);\n }\n\n /**\n * Inflates view from a XmlHelper element\n *\n * @param node Item node\n * @param theme theme with which View should be inflated\n * @return Inflated view\n * @throws ClassNotFoundException\n * @throws IllegalAccessException\n * @throws InstantiationException\n * @throws InvalidClassException\n * @see ResourceManager#processNode(XmlHelper, Style)\n * @deprecated\n */\n public static View processNode(XmlHelper node, Style theme) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvalidClassException, NoSuchMethodException, InvocationTargetException {\n return ResourceManager.processNode(node, theme);\n }\n\n /**\n * Inflates drawable from XML Node\n *\n * @param context Mod context\n * @param node Xml Node\n * @return Drawable\n * @throws ClassNotFoundException\n * @throws IllegalAccessException\n * @throws InstantiationException\n * @throws InvalidClassException\n * @see ResourceManager#processNodeDrawable(Context, Node)\n * @deprecated\n */\n public static Drawable processNodeDrawable(Context context, Node node) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvalidClassException {\n return ResourceManager.processNodeDrawable(new XmlHelper(context, node));\n }\n\n /**\n * Inflates Drawable from @XmlHelper\n *\n * @param node wrapped XML Node\n * @return Drawable\n * @throws ClassNotFoundException\n * @throws IllegalAccessException\n * @throws InstantiationException\n * @throws InvalidClassException\n * @see ResourceManager#processNodeDrawable(XmlHelper)\n * @deprecated\n */\n public static Drawable processNodeDrawable(XmlHelper node) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvalidClassException {\n return ResourceManager.processNodeDrawable(node);\n }\n\n /**\n * Inflates Drawable from @ResourceLocation\n *\n * @param context Mod context\n * @param rl Drawable context\n * @return Drawable\n * @see ResourceManager#inflateDrawable(Context, ResourceLocation, Style)\n * @deprecated\n */\n public static Drawable inflateDrawable(Context context, ResourceLocation rl) {\n return ResourceManager.inflateDrawable(context, rl, getTheme(context));\n }\n\n /**\n * Opens Overlay\n *\n * @param overlay Overlay that should be open\n */\n public static void open(Context context, GuiScreen overlay) {\n if (overlay instanceof Notification) {\n NotificationManager.open((Notification) overlay);\n } else {\n OverlayRunnable run = new OverlayRunnable(overlay);\n Modification.getModule(context).getTickHandler().delay(0, run);\n }\n }\n\n public static void open(Overlay overlay) {\n open(overlay, overlay);\n }\n\n /**\n * Returns environment qualifiers for resource managing\n *\n * @return EnvParams\n */\n public static EnvParams getEnvParams() {\n EnvParams result = new EnvParams();\n result.lang = mc.gameSettings.language.substring(0, 2);\n result.graphics = mc.gameSettings.fancyGraphics ? EnvParams.Graphics.FANCY : EnvParams.Graphics.FAST;\n result.mode = MinecraftServer.getServer().isDedicatedServer() ? EnvParams.Mode.REMOTE : EnvParams.Mode.LOCAL;\n result.version = getMCVersion(mc.getVersion());\n return result;\n }\n\n /**\n * Returns integer representation of Minecraft version\n *\n * @param v Minecraft version\n * @return Integer|null\n * @see ResourceManager#getMCVersion(String)\n * @deprecated\n */\n public static Integer getMCVersion(String v) {\n return ResourceManager.getMCVersion(v);\n }\n\n public static void setTheme(Context ctx, Style theme) {\n themes.put(ctx.contextId(), theme);\n }\n\n public static Style getTheme(Context context) {\n Style theme = themes.get(context.contextId());\n if (theme == null) theme = R.style.theme;\n return theme;\n }\n\n public static int scaleFont(int fontSize) {\n return Math.round(scale(fontSize) * getDisplayScale());\n }\n\n private static class OverlayRunnable implements Task.Client {\n\n protected Overlay ovl;\n\n public OverlayRunnable(GuiScreen ovl) {\n this.ovl = (Overlay) ovl;\n }\n\n @Override\n public void execute(Context ctx) {\n LayeredOverlay layers = null;\n if (mc.currentScreen instanceof LayeredOverlay && ((LayeredOverlay) mc.currentScreen).state != Overlay.State.DISMISSED) {\n layers = (LayeredOverlay) mc.currentScreen;\n } else {\n layers = new LayeredOverlay();\n if (mc.currentScreen != null && mc.currentScreen instanceof Overlay) {\n layers.addOverlay((Overlay) mc.currentScreen);\n }\n mc.displayGuiScreen(layers);\n }\n layers.addOverlay(ovl);\n }\n }\n\n public static FontRenderer getBetterFonts() {\n return new FontRenderer(fontRenderer);\n }\n\n public static float getDisplayScale() {\n GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();\n final GraphicsDevice device = env.getDefaultScreenDevice();\n\n try {\n Field field = device.getClass().getDeclaredField(\"scale\");\n\n if (field != null) {\n field.setAccessible(true);\n Object scale = field.get(device);\n\n if (scale instanceof Integer) {\n return ((Integer) scale) * 1f;\n }\n }\n } catch (Exception ignore) {\n }\n\n final Float scaleFactor = (Float) Toolkit.getDefaultToolkit().getDesktopProperty(\"apple.awt.contentScaleFactor\");\n if (scaleFactor != null) {\n return scaleFactor;\n }\n\n return 1f;\n }\n}", "public class XmlHelper extends Contexted {\n\n /**\n * Wrapped XML Node\n */\n protected Node node;\n\n public XmlHelper(Context context, Node node) {\n super(context);\n this.node = node;\n }\n\n /**\n * Returns node attribute\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @return Node Attribute value\n */\n public Node getAttr(String ns, String name) {\n if (ns == null) return node.getAttributes().getNamedItem(name);\n Node result = node.getAttributes().getNamedItemNS(ns, name);\n if (result == null) result = node.getAttributes().getNamedItem(name);\n return result;\n }\n\n /**\n * Reads string attribute or tries to get it from R class\n *\n * @param ns Attribute namespace\n * @param name Attribute name\n * @param def Default value\n * @return String value\n */\n public String getStringAttr(String ns, String name, String def) {\n Node attr = getAttr(ns, name);\n\n\n String val;\n if (attr == null) {\n val = def;\n } else {\n val = attr.getNodeValue();\n }\n\n Object v = ResourceManager.get(this, val);\n if (v == null) return def;\n return v.toString();\n }\n\n public String getStringAttr(String ns, String name, Style fb, String def) {\n return getStringAttr(ns, name, fb.getString(name, def));\n }\n\n /**\n * Reads integer attribute or tries to get it from R class\n *\n * @param ns Attribute namespace\n * @param name Attribute name\n * @param def Default value\n * @return Integer value\n */\n public Integer getIntegerAttr(String ns, String name, Integer def) {\n Node attr = getAttr(ns, name);\n if (attr == null) return def;\n String val = ResourceManager.get(this, attr.getNodeValue()).toString();\n if (val.length() == 0) return 0;\n return Integer.parseInt(val);\n }\n\n public Integer getIntegerAttr(String ns, String name, Style fb, Integer def) {\n return getIntegerAttr(ns, name, fb.getInt(name, def));\n }\n\n /**\n * Reads float attribute or tries to get it from R class\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @param def Default value\n * @return Float value\n */\n public Float getFloatAttr(String ns, String name, Float def) {\n Node attr = getAttr(ns, name);\n if (attr == null) return def;\n String val = ResourceManager.get(this, attr.getNodeValue()).toString();\n return Float.parseFloat(val);\n }\n\n public Float getFloatAttr(String ns, String name, Style fb, Float def) {\n return getFloatAttr(ns, name, fb.getFloat(name, def));\n }\n\n /**\n * Reads drawable link and tries to get Drawable for it from R class\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @param def Default value\n * @return Drawable element\n */\n public Drawable getDrawableAttr(String ns, String name, Drawable def) {\n ResourceLocation rl = getResourceAttr(ns, name, null);\n if (rl == null) return def;\n\n return GuiManager.inflateDrawable(this, rl);\n }\n\n public Drawable getDrawableAttr(String ns, String name, Style fb, Drawable def) {\n return getDrawableAttr(ns, name, fb.getDrawable(name, def));\n }\n\n /**\n * Reads resource location link and gets it from R class\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @param o Default value\n * @return Resource location\n */\n public ResourceLocation getResourceAttr(String ns, String name, ResourceLocation o) {\n Node attr = getAttr(ns, name);\n if (attr == null) return o;\n\n return (ResourceLink) ResourceManager.get(this, attr.getNodeValue());\n }\n\n public ResourceLocation getResourceAttr(String ns, String name, Style fb, ResourceLink def) {\n return getResourceAttr(ns, name, fb.getResource(name, def));\n }\n\n /**\n * Reads dimension attribute value. If it's a link, gets it from R class;\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @param def Default value\n * @return Dimension value\n */\n public Integer getDimenAttr(String ns, String name, Integer def) {\n Node attr = getAttr(ns, name);\n if (attr == null) return def;\n\n String val = attr.getNodeValue().toLowerCase();\n if (val.equals(\"match_parent\")) return View.Layout.MATCH_PARENT;\n if (val.equals(\"wrap_content\")) return View.Layout.WRAP_CONTENT;\n\n val = ResourceManager.get(this, val).toString();\n\n return Integer.parseInt(val);\n }\n\n public Integer getDimenAttr(String ns, String name, Style fb, Integer def) {\n return getDimenAttr(ns, name, fb.getDimen(name, def));\n }\n\n /**\n * Reads rectangle information (name-left, name-top, name-right, and name-botom) from element attirbutes\n *\n * @param ns Attributes namespace URL\n * @param name Attributes name\n * @param def Default value\n * @return Readed rectangle or default value\n */\n public Rect getRectAttr(String ns, String name, Rect def) {\n Integer all = getDimenAttr(ns, name, null);\n if (all == null && def == null) def = new Rect(0, 0, 0, 0);\n else if (all != null) def = new Rect(all, all, all, all);\n else def = def.clone();\n\n def.left = getDimenAttr(ns, name + \"-left\", def.left);\n def.top = getDimenAttr(ns, name + \"-top\", def.top);\n def.right = getDimenAttr(ns, name + \"-right\", def.right);\n def.bottom = getDimenAttr(ns, name + \"-bottom\", def.bottom);\n\n return def;\n }\n\n public Rect getRectAttr(String ns, String name, Style fb, Rect def) {\n return getRectAttr(ns, name, fb.getRect(name, def));\n }\n\n /**\n * The same as @XmlHelper.getStringAttr\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @param def Default value\n * @return String or default value\n * @deprecated\n */\n @Deprecated\n public String getLocalizedAttr(String ns, String name, String def) {\n return getStringAttr(ns, name, def);\n }\n\n /**\n * Reads Enum value from attribute\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @param def Default value, not null\n * @return Enum value or default value\n */\n public Enum getEnumAttr(String ns, String name, Enum def) {\n String val = getStringAttr(ns, name, (String) null);\n if (val == null) return def;\n Class<Enum> clazz = (Class<Enum>) def.getClass();\n if (val != null) return Enum.valueOf(clazz, val.toUpperCase());\n return def;\n }\n\n public Enum getEnumAttr(String ns, String name, Style fb, Enum def) {\n return getEnumAttr(ns, name, fb.getEnum(name, def));\n }\n\n /**\n * Returns node children list\n *\n * @return Children list\n */\n public List<XmlHelper> getChildren() {\n List<XmlHelper> result = new ArrayList<XmlHelper>();\n NodeList list = node.getChildNodes();\n for (int x = 0; x < list.getLength(); x++) {\n Node childNode = list.item(x);\n if (childNode.getNodeType() == Node.ELEMENT_NODE) result.add(new XmlHelper(this, childNode));\n }\n\n return result;\n }\n\n /**\n * Returns wrapped node\n *\n * @return wrapped node\n */\n public Node getNode() {\n return node;\n }\n\n /**\n * Reads id link and fetches it from R class\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @return id value\n */\n public int getIdAttr(String ns, String name) {\n Node attr = getAttr(ns, name);\n if (attr == null) return -1;\n\n String id = attr.getNodeValue();\n if (id.equals(\"parent\")) return 0;\n\n Object val = ResourceManager.get(this, id);\n\n if (val == null) return -1;\n if (val instanceof Integer) {\n return (Integer) val;\n }\n\n return Integer.valueOf(val.toString());\n }\n\n public int getIdAttr(String ns, String name, Style fb) {\n int id = getIdAttr(ns, name);\n if (id == -1) id = fb.getIdAttr(name);\n return id;\n }\n\n /**\n * Reads size values (width + height)\n *\n * @param ns Attributes namespace URL\n * @param def Default value\n * @return Readed size or default value\n */\n public Point getSize(String ns, Point def) {\n if (def == null) def = new Point(0, 0);\n else def = def.clone();\n\n def.x = getDimenAttr(ns, \"width\", def.x);\n def.y = getDimenAttr(ns, \"height\", def.y);\n\n return def;\n }\n\n public Point getSize(String ns, Style fb, Point def) {\n return getSize(ns, fb.getSize(def));\n }\n\n /**\n * Reads color attribute (and tries to fetch it from R class\n *\n * @param ns Attribute namespace URL\n * @param name Attribute name\n * @param def Default value\n * @return Color or default value\n */\n public Long getColorAttr(String ns, String name, Long def) {\n Node attr = getAttr(ns, name);\n if (attr == null) return def;\n\n String value = attr.getNodeValue();\n value = ResourceManager.get(this, value).toString();\n return Long.parseLong(value, 16);\n }\n\n public Long getColorAttr(String ns, String name, Style fb, Long def) {\n return getColorAttr(ns, name, fb.getColor(name, def));\n }\n\n /**\n * @return wrapped node name\n */\n public String getName() {\n return node.getNodeName();\n }\n\n /**\n * @return text value of the node\n */\n public String getText() {\n return node.getTextContent();\n }\n\n public Style getStyleAttr(String ns, String name, Style def) {\n Node sName = getAttr(ns, name);\n if (sName == null) {\n return def;\n }\n\n Style result = (Style) ResourceManager.get(this, sName.getNodeValue());\n if (result == null) return def;\n\n result.setFallbackTheme(def);\n return result;\n }\n\n public Boolean getBoolAttr(String NS, String name, Boolean def) {\n String val = getStringAttr(NS, name, (String) null);\n if (val == null) return def;\n if (val.equals(\"true\")) return true;\n try {\n return Integer.valueOf(val) > 0;\n } catch (NumberFormatException e) {\n return false;\n }\n }\n\n public Boolean getBoolAttr(String ns, String name, Style fb, Boolean def) {\n return getBoolAttr(ns, name, fb.getBool(name, def));\n }\n}", "public interface Drawable {\n /**\n * Draws the drawable\n * @param where Where to draw\n */\n void draw(Point where);\n /**\n * Sets drawable size\n * @param size New drawable size\n */\n void setSize(Point size);\n /**\n * Returns current drawable size\n * @return Drawable size\n */\n Point getSize();\n /**\n * Returns original drawable size\n * @return original size\n */\n Point getOriginalSize();\n\n /**\n * Inflates Drawable from XML\n * @param node XML node\n * @param theme Theme with which it should be inflated\n */\n void inflate(XmlHelper node, Style theme);\n\n /**\n * Clones the drawable\n * @return drawable clone\n */\n Drawable clone();\n\n /**\n * Draws shadow around the drawable\n * @param color\n * @param size\n */\n void drawShadow(Point where, GLColor color, int size);\n\n void setDebug(boolean debug);\n}", "public class TextDrawable implements Drawable {\n\n /**\n * Text to draw\n */\n protected String text;\n /**\n * Drawing color\n */\n protected long color;\n /**\n * Font texture scale factor\n */\n protected float fontSize = 1;\n /**\n * Current font size\n */\n protected Point size = new Point(0, 0), originalSize;\n /**\n * Are line breaks allowed?\n */\n protected boolean multiline;\n\n /**\n * Measured character height with the current MineDroid font texture\n */\n protected static int charHeight = 0;\n\n private boolean debug;\n\n\n static {\n try {\n// Field f = Minecraft.getMinecraft().fontRendererObj.getClass().getDeclaredField(\"locationFontTexture\");\n// f.setAccessible(true);\n// ResourceLocation fontLocation = (ResourceLocation) f.get(Minecraft.getMinecraft().fontRendererObj);\n// BufferedImage bufferedimage = TextureUtil.readBufferedImage(Minecraft.getMinecraft().getResourceManager().getResource(fontLocation).getInputStream());\n// charHeight = bufferedimage.getHeight() / 16;\n charHeight = Minecraft.getMinecraft().fontRendererObj.FONT_HEIGHT;\n } catch (Exception ioexception) {\n throw new RuntimeException(ioexception);\n }\n\n }\n\n public TextDrawable() {\n }\n\n public TextDrawable(String text, int color) {\n setText(text);\n this.color = color;\n }\n\n /**\n * Sets text scale factor\n *\n * @param fontSize new scale factor\n */\n public void setTextSize(float fontSize) {\n this.fontSize = fontSize;\n size.x *= fontSize;\n size.y *= fontSize;\n }\n\n /**\n * Returns text value\n *\n * @return Text value\n */\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n FontRenderer renderer = Minecraft.getMinecraft().getRenderManager().getFontRenderer();\n size.x = renderer.getStringWidth(text);\n size.y = charHeight;\n originalSize = size.clone();\n }\n\n /**\n * Sets text value from value link\n *\n * @param text New text value\n */\n public void setText(ValueLink text) {\n this.setText(text.toString());\n }\n\n /**\n * Sets formatted text value\n *\n * @param s Format string\n * @param args Format arguments\n */\n public void setText(String s, Object... args) {\n setText(String.format(s, args));\n }\n\n /**\n * Sets formatted text value from value link\n *\n * @param s Value link to format string\n * @param args Format arguments\n */\n public void setText(ValueLink s, Object... args) {\n setText(s.toString(), args);\n }\n\n /**\n * Returns current text boundaries\n *\n * @return text boundaries\n */\n public float getTextSize() {\n return fontSize;\n }\n\n @Override\n public void draw(Point where) {\n FontRenderer renderer = Minecraft.getMinecraft().getRenderManager().getFontRenderer();\n // setting global output scale\n if (size.x < 1) {\n return;\n }\n\n GL11.glPushMatrix();\n View.resetBlending();\n GL11.glScalef(fontSize, fontSize, fontSize);\n\n // scaling coordinates\n int left = (int) Math.round(where.x / fontSize);\n int top = (int) Math.round(where.y / fontSize);\n\n // drawing text\n List<String> lines = fitString(text, size.x);\n for (String line : lines) {\n renderer.drawString(line.replaceAll(\"\\\\n+$\", \"\"), left, top, (int) color);\n ColorDrawable d = new ColorDrawable(0xff0000);\n d.setSize(new Point(2, 2));\n d.draw(new Point(left, top));\n top += Math.round(charHeight * fontSize);\n }\n\n // resetting output scale\n GL11.glScalef(1 / fontSize, 1 / fontSize, 1 / fontSize);\n }\n\n @Override\n public void setSize(Point size) {\n this.size = size;\n }\n\n @Override\n public Point getSize() {\n return size;\n }\n\n @Override\n public Point getOriginalSize() {\n Point osize = originalSize.clone();\n osize.x *= fontSize;\n osize.y *= fontSize;\n return osize;\n }\n\n @Override\n public void inflate(XmlHelper node, Style theme) {\n Style s = theme.getStyle(\"text\");\n color = node.getColorAttr(GuiManager.NS, \"color\", Long.valueOf(s.getInt(\"color\", 0)));\n setText(node.getStringAttr(GuiManager.NS, \"text\", \"\"));\n setTextSize(node.getFloatAttr(GuiManager.NS, \"size\", s.getFloat(\"size\", 1f)));\n setSize(node.getSize(GuiManager.NS, getOriginalSize()));\n }\n\n /**\n * Returns calculated char height for current MineCraft font texture\n *\n * @return Char Height\n */\n public int getCharHeight() {\n return (int) (charHeight * fontSize);\n }\n\n /**\n * Calculates last text character bottom right point for given width\n *\n * @param width Width\n * @return Calculated end point\n */\n public Point calculateEndPoint(int width) {\n return calculateEndPoint(text, width);\n }\n\n /**\n * Calculates last character bottom right point for given text in given width\n *\n * @param text Text\n * @param width Width\n * @return Calculated end point\n */\n public Point calculateEndPoint(String text, int width) {\n List<String> lines = fitString(text, width);\n int lastLineWidth = getStringWidth(lines.get(lines.size() - 1));\n return new Point(lastLineWidth, (int) Math.round(charHeight * lines.size() * fontSize));\n }\n\n /**\n * Calculates coordinate for text position\n *\n * @param text Text\n * @param width width limit\n * @param position Text position\n * @return Calculated coordinate\n */\n public Point calculatePosition(String text, int width, int position) {\n List<String> lines = fitString(text, width);\n int currentPosition = 0;\n Point result = new Point(0, 0);\n\n if (position != 0) {\n for (int y = 0; y < lines.size(); y++) {\n String line = lines.get(y);\n for (int x = 0; x < line.length(); x++) {\n char c = line.charAt(x);\n if (++currentPosition == position) {\n if (c == '\\n') {\n result.x = 0;\n result.y = Math.round(charHeight * (y + 1) * fontSize);\n } else {\n result.x = getStringWidth(line.substring(0, x + 1));\n result.y = Math.round(charHeight * y * fontSize);\n }\n break;\n }\n }\n\n if (currentPosition == position) break;\n }\n }\n\n result.y += Math.round(charHeight * fontSize);\n\n return result;\n }\n\n /**\n * Splits text to fit given width\n *\n * @param text Text to split\n * @param width Width limit\n * @return Text lines\n */\n public List<String> getTextLines(String text, int width) {\n return fitString(text, width);\n }\n\n /**\n * Splits text until given position to fit given width\n *\n * @param text Text to split\n * @param width Width limit\n * @param position Position limit\n * @return Text lines\n */\n public List<String>[] getSplitLines(String text, int width, int position) {\n List[] result = new List[]{new ArrayList<String>(), new ArrayList<String>()};\n List<String> lines = fitString(text, width);\n int index = 0;\n int currentPosition = 0;\n for (int i = 0; i < lines.size(); i++) {\n String line = lines.get(i);\n if (index == 0) {\n if (currentPosition + line.length() > position) {\n result[0].add(line.substring(0, position - currentPosition));\n result[1].add(line.substring(position - currentPosition));\n index = 1;\n continue;\n } else if (currentPosition + line.length() == position) {\n index = 1;\n result[0].add(line);\n if (i < lines.size() - 1) {\n result[0].add(\"\");\n }\n continue;\n }\n\n result[0].add(line);\n currentPosition += line.length();\n } else {\n result[1].add(line);\n }\n }\n\n return result;\n }\n\n /**\n * Allows/dissalows line breaks\n * @param multiline line breaks flag\n */\n public void setMultiline(boolean multiline) {\n this.multiline = multiline;\n }\n\n /**\n * Calculates given string width without adding any line breaks to it\n * but with respect to already existing ones\n * @param text Text to measure\n * @return Calculated width\n */\n public int getStringWidth(String text) {\n float currentLine = 0, result = 0;\n FontRenderer renderer = Minecraft.getMinecraft().getRenderManager().getFontRenderer();\n\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c == '\\n') {\n currentLine = 0;\n } else {\n currentLine += renderer.getCharWidth(c) * fontSize;\n }\n if (currentLine > result) result = currentLine;\n }\n\n return Math.round(result);\n }\n\n public List<String> fitString(String text, int width) {\n return fitString(text, width, fontSize);\n }\n\n /**\n * Splits string to make it fit given width\n * @param text Text to split\n * @param width Width limit\n * @return Splitted text\n */\n public List<String> fitString(String text, int width, float fontSize) {\n FontRenderer renderer = Minecraft.getMinecraft().getRenderManager().getFontRenderer();\n List<String> result = new ArrayList<String>();\n float lineWidth = 0;\n String separators = \" .,!:;)-=\";\n StringBuilder line = new StringBuilder();\n if (text.length() == 0) {\n result.add(\"\");\n return result;\n }\n\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n float charWidth = renderer.getCharWidth(c) * fontSize;\n if (c == '\\n') {\n result.add(line.toString() + \"\\n\");\n line.setLength(0);\n lineWidth = 0;\n } else if (Math.floor(lineWidth + charWidth) <= width) {\n line.append(c);\n lineWidth += charWidth;\n } else {\n int separator = -1;\n for (int j = line.length(); j > 0; j--) {\n if (separators.contains(String.valueOf(line.charAt(j - 1)))) {\n separator = j;\n break;\n }\n }\n if (separator > -1) {\n result.add(line.substring(0, separator));\n line = new StringBuilder(line.substring(separator));\n } else {\n result.add(line.toString());\n line.setLength(0);\n }\n line.append(c);\n lineWidth = getStringWidth(line.toString());\n }\n }\n result.add(line.toString());\n return result;\n }\n\n @Override\n public TextDrawable clone() {\n TextDrawable result = new TextDrawable(text, (int) color);\n if (size != null) result.setSize(size);\n result.setTextSize(fontSize);\n\n return result;\n }\n\n @Override\n public void drawShadow(Point where, GLColor color, int size) {\n\n }\n\n @Override\n public void setDebug(boolean debug) {\n this.debug = debug;\n }\n\n public void setColor(long color) {\n this.color = color;\n }\n\n public long getColor() {\n return color;\n }\n}", "public interface Event<Argument> {\n /**\n * Handles event\n * @param event event information\n */\n void handle(Argument event);\n}", "public class MouseEvent {\n /**\n * Event type class\n */\n public Class type;\n /**\n * Event coordinates\n */\n public Point coords;\n /**\n * View that currently handles the event\n */\n public View target;\n /**\n * View that was an original target of the event\n */\n public View source;\n /**\n * Button numder (if pressed/released)\n */\n public int button;\n /**\n * Event coordinates offset of previous event\n */\n public Point diff;\n /**\n * Event cancelation flag\n */\n public boolean cancel = false;\n /**\n * Scroll amount values\n */\n public Point wheel;\n /**\n * Some useful keyboard flags\n */\n public boolean shift, control, alt;\n\n @Override\n public MouseEvent clone() {\n MouseEvent result = new MouseEvent();\n result.type = type;\n result.coords = coords;\n result.target = target;\n result.source = source;\n result.button = button;\n result.diff = diff;\n result.cancel = cancel;\n result.wheel = wheel.clone();\n result.shift = shift;\n result.control = control;\n result.alt = alt;\n\n return result;\n }\n}", "public class Rect {\n /**\n * Rectangle coordinates\n */\n public int left, top, right, bottom;\n\n public Rect(int left, int top, int right, int bottom) {\n this.left = left;\n this.top = top;\n this.right = right;\n this.bottom = bottom;\n }\n\n public Rect(Point leftTop, Point rightBottom) {\n left = leftTop.x;\n top = leftTop.y;\n right = rightBottom.x;\n bottom = rightBottom.y;\n }\n\n public Rect() {\n this(0, 0, 0, 0);\n }\n\n @Override\n public Rect clone() {\n return new Rect(left, top, right, bottom);\n }\n\n /**\n * Calculates rectangle size\n * @return Calculated size\n */\n public Point getSize() {\n return new Point(right - left, bottom - top);\n }\n\n /**\n * Returns rectangle top left point coordinates\n * @return top left point coordinates\n */\n public Point coords() {\n return new Point(left, top);\n }\n\n @Override\n public String toString() {\n return \"[(\" + left + \", \" + top + \") — (\" + right + \", \" + bottom + \")]\";\n }\n\n /**\n * Checks if the point inside of the rectangle\n * @param point Test pont\n * @return check result\n */\n public boolean contains(Point point) {\n return point.x > left && point.x < right && point.y > top && point.y < bottom;\n }\n\n /**\n * Copies rectangle to the position\n * @param position new position\n * @return moved copy\n */\n public Rect move(Point position) {\n Rect result = clone();\n result.left += position.x;\n result.top += position.y;\n result.bottom += position.y;\n result.right += position.x;\n return result;\n }\n\n /**\n * returns rectangles intesection rectangle\n * @param other other rectangle\n * @return intersection area\n */\n public Rect and(Rect other) {\n Rect result = new Rect(0, 0, 0, 0);\n result.left = Math.max(left, other.left);\n result.top = Math.max(top, other.top);\n result.right = Math.min(right, other.right);\n result.bottom = Math.min(bottom, other.bottom);\n if (result.left > result.right || result.top > result.bottom) {\n // There is no intersection.\n return null;\n }\n return result;\n }\n\n /**\n * Moves rectangle bottom right point to fit given width\n * @param width new width\n */\n public void setWidth(int width) {\n this.right = this.left + width;\n }\n\n /**\n * Moves rectangle bottom right point to fit given height\n * @param height new height\n */\n public void setHeight(int height) {\n this.bottom = this.top + height;\n }\n}", "public class Style implements Context {\n\n protected HashMap<String, Object> props;\n protected ResourceLocation source;\n protected Integer modId;\n protected Class r;\n protected String parentName;\n protected Style parent;\n private Style fallbackTheme;\n\n public Style(ResourceLocation source, Class r) {\n this.source = source;\n this.r = r;\n }\n\n public Style(ResourceLocation source, Class r, String parent) {\n this.source = source;\n this.r = r;\n this.parentName = parent;\n }\n\n protected void inflate() {\n XmlHelper helper = GuiManager.getXmlHelper(this, source);\n List<XmlHelper> items = helper.getChildren();\n props = new HashMap<String, Object>();\n\n for (XmlHelper item : items) {\n String name = item.getStringAttr(null, \"name\", null);\n if (name == null) continue;\n String value = item.getText();\n if (!StringUtils.isEmpty(value) && value.charAt(0) == '@') {\n props.put(name, ResourceManager.get(this, value));\n } else {\n props.put(name, value);\n }\n }\n\n if (parentName == null) {\n parentName = helper.getStringAttr(GuiManager.NS, \"parent\", null);\n }\n\n if (parentName != null) {\n this.parent = (Style) ResourceManager.get(this, parentName);\n }\n\n// if (false && parent == null) {\n// Class p = getClass().getEnclosingClass();\n// if (Style.class.isAssignableFrom(p)) {\n// try {\n// Method getInstance = p.getDeclaredMethod(\"getInstance\");\n// parent = (Style) getInstance.invoke(null);\n// } catch (Exception e) {\n// e.printStackTrace();\n// }\n// }\n// }\n }\n\n protected Object getProperty(String property) {\n if (props == null) inflate();\n Object result = null;\n if (!props.containsKey(property)) {\n if (parent != null) result = parent.get(property);\n } else {\n result = props.get(property);\n }\n if (result == null && fallbackTheme != null) result = fallbackTheme.getProperty(property);\n\n return result;\n }\n\n public Object get(String property) {\n return getProperty(property);\n }\n\n public String getString(String property, String def) {\n String val = (String) getProperty(property);\n if (val == null) return def;\n return val;\n }\n\n public Integer getInt(String property, Integer def) {\n Object val = get(property);\n if (val == null) return def;\n return Integer.valueOf(val.toString());\n }\n\n public Rect getRect(String property, Rect def) {\n Integer all = getInt(property, null);\n if (all == null && def == null) def = new Rect(0, 0, 0, 0);\n else if (all != null) def = new Rect(all, all, all, all);\n else def = def.clone();\n\n def.left = getInt(property + \"-left\", def.left);\n def.top = getInt(property + \"-top\", def.top);\n def.right = getInt(property + \"-right\", def.right);\n def.bottom = getInt(property + \"-bottom\", def.bottom);\n\n return def;\n }\n\n public Style getStyle(String name) {\n Style val = (Style) getProperty(name);\n\n return val;\n }\n\n public Style getStyle(String name, Style def) {\n Style v = getStyle(name);\n if (v == null) return def;\n return v;\n }\n\n protected static Style getInstance() {\n throw new RuntimeException(\"Style.getInstance method SHOULD be overwritten!\");\n }\n\n public void setFallbackTheme(Style fallbackTheme) {\n if (this == fallbackTheme) return;\n this.fallbackTheme = fallbackTheme;\n }\n\n public Enum getEnum(String s, Enum def) {\n Object val = getProperty(s);\n if (val == null) return def;\n\n Class<Enum> clazz = (Class<Enum>) def.getClass();\n return Enum.valueOf(clazz, val.toString().toUpperCase());\n }\n\n public Float getFloat(String name, Float def) {\n Object val = getProperty(name);\n if (val == null) return def;\n\n return Float.valueOf(val.toString());\n }\n\n public ResourceLocation getResource(String name, ResourceLocation def) {\n Object val = getProperty(name);\n if (val == null) return def;\n\n return (ResourceLocation) val;\n }\n\n public Long getColor(String property, Long def) {\n Object val = get(property);\n if (val == null) return def;\n return Long.parseLong(val.toString(), 16);\n }\n\n public Drawable getDrawable(String name, Drawable o) {\n ResourceLocation l = getResource(name, null);\n if (l == null) return o;\n return GuiManager.inflateDrawable(this, l);\n }\n\n public int getIdAttr(String name) {\n String id = getString(name, null);\n if (id == null) return -1;\n if (id.equals(\"parent\")) return 0;\n\n Object val = ResourceManager.get(this, id);\n if (val == null) return -1;\n if (val instanceof Integer) return (Integer) val;\n return Integer.valueOf(val.toString());\n }\n\n public Point getSize(Point def) {\n if (def == null) def = new Point(0, 0);\n else def = def.clone();\n\n def.x = getDimen(\"width\", def.x);\n def.y = getDimen(\"height\", def.y);\n return def;\n }\n\n public Integer getDimen(String name, Integer def) {\n String val = getString(name, null);\n if (val == null) return def;\n\n val = val.toLowerCase();\n if (val.equals(\"match_parent\")) return View.Layout.MATCH_PARENT;\n if (val.equals(\"wrap_content\")) return View.Layout.WRAP_CONTENT;\n\n val = ResourceManager.get(this, val).toString();\n\n return Integer.parseInt(val);\n }\n\n public Boolean getBool(String name, Boolean def) {\n String val = getString(name, null);\n if (val == null) return def;\n if (val.equals(\"true\")) return true;\n try {\n return Integer.valueOf(val) > 0;\n } catch (NumberFormatException e) {\n return false;\n }\n }\n\n @Override\n public int contextId() {\n if (modId == null) {\n modId = Modification.getModuleByR(r).hashCode();\n }\n return modId;\n }\n}" ]
import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.GuiManager; import com.onkiup.minedroid.gui.XmlHelper; import com.onkiup.minedroid.gui.drawables.Drawable; import com.onkiup.minedroid.gui.drawables.TextDrawable; import com.onkiup.minedroid.gui.events.Event; import com.onkiup.minedroid.gui.events.MouseEvent; import com.onkiup.minedroid.gui.primitives.Rect; import com.onkiup.minedroid.gui.resources.Style;
package com.onkiup.minedroid.gui.views; /** * Created by chedim on 5/31/15. */ public class CheckBox extends ContentView { protected Drawable check; protected boolean value; protected TextDrawable label;
public CheckBox(Context context) {
0
CMPUT301F14T14/android-question-answer-app
QuestionApp/src/ca/ualberta/cs/cmput301f14t14/questionapp/MainActivity.java
[ "public interface Callback<T> {\n\t/**\n\t * Run by the onPostExecute method of a Task\n\t * @param object\n\t */\n\tpublic void run(T object);\n}", "public class ClientData {\n\n\tprivate static final String PREF_SET = \"cs.ualberta.cs.cmput301f14t14.questionapp.prefs\";\n\tprivate static final String VAL_USERNAME = \"username\";\n\tprivate static final String VAL_FAVORITES_LIST = \"favqlist\";\n\tprivate static final String VAL_READ_LATER_LIST = \"readlaterlist\";\n\tprivate static final String VAL_UPVOTED_LIST = \"upvotelist\";\n\t\n\tprivate SharedPreferences prefs;\n\n\tpublic ClientData(Context context) {\n\t\tthis.prefs = context.getSharedPreferences(PREF_SET, Context.MODE_PRIVATE);\n\t}\n\n\t/**\n\t * Get username record\n\t * @return\n\t */\n\tpublic String getUsername() {\n\t\treturn this.prefs.getString(VAL_USERNAME, null);\n\t}\n\n\t/**\n\t * Set username record\n\t * @param username\n\t */\n\tpublic void setUsername(String username) {\n\t\tusername = username.trim();\n\t\tif (username.length() == 0) {\n\t\t\tthrow new IllegalArgumentException(\"New username may not be blank.\");\n\t\t}\n\t\tEditor e = prefs.edit();\n\t\te.putString(VAL_USERNAME, username);\n\t\te.apply();\n\t}\n\n\t/**\n\t * Get a list UUIDs for favorite items\n\t * @return List of UUIDs\n\t */\n\tpublic List<UUID> getFavorites() {\n\t\treturn getItems(VAL_FAVORITES_LIST);\n\t}\n\n\t/**\n\t * Set the list of UUIDs for favorite items\n\t * @param list List of UUIDs\n\t */\n\tpublic void saveFavorites(List<UUID> list){\n\t\tsaveItems(list, VAL_FAVORITES_LIST);\n\t}\n\n\t/**\n\t * Set the list of UUIDs for items to read later\n\t * @return List of UUIDs\n\t */\n\tpublic List<UUID> getReadLaterItems() {\n\t\treturn getItems(VAL_READ_LATER_LIST);\n\t}\n\n\t/**\n\t * Add a UUID to the read later list\n\t * @param u UUID\n\t */\n\tpublic void markReadLater(UUID u) {\n\t\tList<UUID> appendlist = getItems(VAL_READ_LATER_LIST);\n\t\tappendlist.add(u);\n\t\tsaveItems(appendlist, VAL_READ_LATER_LIST);\n\t}\n\n\t/**\n\t * Remove a UUID from the read later list\n\t * @param u UUID\n\t */\n\tpublic void unmarkReadLater(UUID u){\n\t\tList<UUID> list = getItems(VAL_READ_LATER_LIST);\n\t\tlist.remove(u);\n\t\tsaveItems(list,VAL_READ_LATER_LIST);\n\t}\n\n\t/**\n\t * Check if an item's UUID is in the read later list.\n\t * \n\t * A user will still have to call the DataManager to get\n\t * the desired item.\n\t * @param id UUID of item\n\t * @return True if the item is in the list, false otherwise.\n\t */\n\tpublic boolean isReadLater(UUID id) {\n\t\tList<UUID> rllist = getItems(VAL_READ_LATER_LIST);\n\t\tif (rllist.contains(id)) {\n\t\t\treturn true; \n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Add an item's UUID to the list of items that have been upvoted\n\t * @param id UUID\n\t */\n\tpublic void markItemUpvoted(UUID id) {\n\t\tList<UUID> upvoteList = getItems(VAL_UPVOTED_LIST);\n\t\tupvoteList.add(id);\n\t\tsaveItems(upvoteList, VAL_UPVOTED_LIST);\n\t}\n\n\t/**\n\t * Check that a UUID is in the list of items that have been upvoted\n\t * @param id UUID\n\t * @return True if an item has been upvoted, false otherwise\n\t */\n\tpublic boolean isItemUpvoted(UUID id) {\n\t\tList<UUID> list = getItems(VAL_UPVOTED_LIST);\n\t\treturn (list.contains(id)) ? true : false;\n\t}\n\n\t/**\n\t * Get a list of UUIDs from a named list\n\t * @param name Name of list\n\t * @return List of UUIDs\n\t */\n\tprivate List<UUID> getItems(String name) {\n\t\t// Get set of data from SharedPreferences\n\t\tSet<String> set = prefs.getStringSet(name, null);\n\n\t\t// Set may be null on first run of app\n\t\tif (set == null) {\n\t\t\treturn new ArrayList<UUID>();\n\t\t}\n\n\t\t// Need to build up a new set of UUIDs before converting to List\n\t\tSet<UUID> intermediateSet = new HashSet<UUID>();\n\t\tfor (String s: set) {\n\t\t\tif (s == null) continue;\n\t\t\tintermediateSet.add(UUID.fromString(s));\n\t\t}\n\n\t\t// Construct the final list\n\t\tArrayList<UUID> returnlist = new ArrayList<UUID>();\n\t\treturnlist.addAll(intermediateSet);\n\t\treturn returnlist;\n\t}\n\n\t/**\n\t * Save a list of UUIDs to a named list\n\t * @param list List of UUIDs\n\t * @param name Name of list\n\t */\n\tprivate void saveItems(List<UUID> list, String name) {\n\t\tEditor e = prefs.edit();\n\t\tSet<String> set = new HashSet<String>();\n\n\t\tfor (UUID i: list) {\n\t\t\tset.add(i.toString());\n\t\t}\n\t\te.putStringSet(name, set);\n\t\te.commit();\n\t}\n\n\t/**\n\t * Clear all data in this store\n\t */\n\tpublic void clear() {\n\t\tEditor e = prefs.edit();\n\t\te.clear();\n\t\te.apply();\n\t}\n\n}", "public class DataManager {\n\t\n\tprivate static DataManager instance;\n\n\tprivate IDataStore localDataStore;\n\tprivate IDataStore remoteDataStore;\n\tprivate List<UUID> recentVisit;\n\tprivate List<UUID> readLater;\n\tprivate Context context;\n\tString Username;\n\tstatic final String favQ = \"fav_Que\";\n\tstatic final String favA = \"fav_Ans\";\n\tstatic final String recV = \"rec_Vis\";\n\tstatic final String redL = \"red_Lat\";\n\tstatic final String pusO = \"pus_Onl\";\n\tstatic final String upvO = \"upv_Onl\";\n\n\t\n\tprivate EventBus eventbus = EventBus.getInstance();\n\n\n\t\n\tprivate DataManager(Context context) {\n\t\tthis.context = context;\n\t}\n\n\t/**\n\t * Create data stores\n\t * \n\t * This must be done after the constructor, because some data stores\n\t * refer back to DataManager, and cannot do so until it is constructed.\n\t */\n\tprivate void initDataStores() {\n\t\tthis.localDataStore = new LocalDataStore(context);\n\t\tthis.remoteDataStore = new RemoteDataStore(context);\n\t}\n\n\t/**\n\t * Singleton getter\n\t * @param context\n\t * @return Instance of DataManager\n\t */\n\tpublic static DataManager getInstance(Context context){\n\t\tif (instance == null){\n\t\t\tinstance = new DataManager(context.getApplicationContext());\n\t\t\tinstance.initDataStores();\n\t\t}\n\t\t\n\t\treturn instance;\n\t}\n\t/**\n\t * Starts the uploader service that copies cached creations in local to remote.\n\t */\n\tpublic void startUploaderService() {\n\t\t//Hackery. No idea how to start a service only once and not get into threading problems.\n\t\tif (UploaderService.isServiceAlreadyRunning == false) {\n\t\t\tIntent i = new Intent(context, UploaderService.class);\n\t\t\tcontext.startService(i);\n\t\t}\n\t}\n\t\n\t\n\t//View Interface Begins\n\tpublic void addQuestion(Question validQ, Callback<Void> c) {\n\t\tAddQuestionTask aqt = new AddQuestionTask(context);\n\t\taqt.setCallBack(c);\n\t\taqt.execute(validQ);\n\t}\n\n\t/**\n\t * Get a question by its UUID\n\t * @param id\n\t * @return\n\t */\n\tpublic Question getQuestion(UUID id, Callback<Question> c) {\n\t\tGetQuestionTask task = new GetQuestionTask(context);\n\t\tif (c == null) {\n\t\t\treturn task.blockingRun(id);\n\t\t}\n\t\ttask.setCallBack(c);\n\t\ttask.execute(id);\n\t\treturn null;\n\t\t \n\t}\n\t\n\t/**\n\t * Add an answer record\n\t * @param A Answer to add\n\t */\n\tpublic void addAnswer(Answer A){\n\t\tAddAnswerTask aat = new AddAnswerTask(context);\n\t\taat.execute(A);\n\t}\n\n\t/**\n\t * Get answer record\n\t * @param Aid Answer ID\n\t * @return\n\t */\n\tpublic Answer getAnswer(UUID Aid, Callback<Answer> c) {\n\t\t//Add this answer to the recentVisit list\n\t\tGetAnswerTask gat = new GetAnswerTask(context);\n\t\tAnswer anull = null;\n\t\tif (c == null) {\n\t\t\t//User wants an answer within a thread, or doesn't care about blocking.\n\t\t\treturn gat.blockingRun(Aid);\n\t\t}\n\t\tgat.setCallBack(c);\n\t\tgat.execute(Aid);\n\t\treturn anull; //Hopefully eclipse will warn users this method always returns null\n\t}\n\n\t/**\n\t * Add comment record to question\n\t * @param C\n\t */\n\tpublic void addQuestionComment(Comment<Question> C){\n\t\tAddQuestionCommentTask aqct = new AddQuestionCommentTask(context);\n\t\taqct.execute(C); //May have a problem here. Look here first if crashing.\n\t}\n\n\t/**\n\t * Get comment record from question\n\t * @param cid\n\t * @return\n\t */\n\t//Wtf, when I added a Callback parameter, nothing broke... Is this \n\t//method actually called anywhere in the app?\n\tpublic Comment<Question> getQuestionComment(UUID cid, Callback<Comment<? extends ICommentable>> c) {\n\t\tGetQuestionCommentTask gqct = new GetQuestionCommentTask(context);\n\t\tif (c == null){\n\t\t\t//User does not care about blocking\n\t\t\treturn (Comment<Question>) gqct.blockingRun(cid);\n\t\t}\n\t\tgqct.setCallBack(c);\n\t\tgqct.execute(cid);\n\t\t//If the user is using threading, they will care to extract their result from the callback\n\t\treturn null;\n\t\t\n\t}\n\n\t/**\n\t * Add comment record for answer\n\t * @param C\n\t */\n\tpublic void addAnswerComment(Comment<Answer> C){\n\t\tAddAnswerCommentTask aact = new AddAnswerCommentTask(context);\n\t\taact.execute(C); //Possibly trouble here.\n\t}\n\n\t/**\n\t * Get comment record from answer\n\t * @param Cid\n\t * @return\n\t */\n\t//Another case where adding a callback to the function signature didn't break the app\n\t//Are we using this?\n\tpublic Comment<Answer> getAnswerComment(UUID Cid, Callback<Comment<? extends ICommentable>> c){\n\t\tGetAnswerCommentTask gact = new GetAnswerCommentTask(context);\n\t\tif (c == null) {\n\t\t\t//User doesn't care about threading and expects this to be blocking.\n\t\t\treturn (Comment<Answer>) gact.blockingRun(Cid);\n\t\t}\n\t\tgact.setCallBack(c);\n\t\tgact.execute(Cid);\n\t\t//The user, by not setting a null callback, should know to fetch the result \n\t\t//out of the callback, and should not be surprised at an NPE.\n\t\treturn null;\n\t}\n\n\t/**\n\t * Get a list of all existing questions.\n\t * \n\t * This list is not returned with any particular order.\n\t * @return\n\t */\n\tpublic List<Question> getQuestionList(Callback callback) {\n\t\tGetQuestionListTask task = new GetQuestionListTask(context);\n\t\tif (callback == null) {\n\t\t\t//User doesn't care this is blocking\n\t\t\treturn task.blockingRun();\n\t\t}\n\t\ttask.setCallBack(callback);\n\t\ttask.execute();\n\t\t//User should expect this to be null, since the result should be pulled out of the callback\n\t\treturn null;\n\t}\n\n\t/**\n\t * Get a list of comments from an answer asynchronously\n\t * @param a\n\t * @param c\n\t * @return\n\t */\n\tpublic List<Comment<Answer>> getCommentList(Answer a, Callback<List<Comment<Answer>>> c){\n\t\tGetCommentListTask<Answer> gclat = new GetCommentListTask<Answer>(context);\n\t\tif (c == null) {\n\t\t\t//User doesn't care this is blocking\n\t\t\treturn gclat.blockingRun(a);\n\n\n\t\t}\n\t\tgclat.setCallBack(c);\n\t\tgclat.execute(a);\n\t\t//User should expect this to be null, since the result should be pulled out of the callback\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Get a list of comments from a question asynchronously\n\t * @param q\n\t * @param c\n\t * @return\n\t */\n\tpublic List<Comment<Question>> getCommentList(Question q, Callback<List<Comment<Question>>> c){\n\t\tGetCommentListTask<Question> gclqt = new GetCommentListTask<Question>(context);\n\t\tif (c == null) {\n\t\t\t//User doesn't care this is blocking\n\t\t\treturn gclqt.blockingRun(q);\n\t\t}\n\t\tgclqt.setCallBack(c);\n\t\tgclqt.execute(q);\n\t\t//User should pull result out of callback\n\t\treturn null;\n\t}\n\t\n\tpublic List<Answer> getAnswerList(Question q, Callback<List<Answer>> c){\n\t\tGetAnswerListTask galt = new GetAnswerListTask(context);\n\t\tif (c == null) {\n\t\t\t//User does not care this is blocking\n\t\t\treturn galt.blockingRun(q);\n\t\t\t\n\t\t}\n\t\tgalt.setCallBack(c);\n\t\tgalt.execute(q);\n\t\t//User should pull result out of callback\n\t\treturn null;\n\t}\n\n\tpublic IDataStore getLocalDataStore() {\n\t\treturn localDataStore;\n\t}\n\n\tpublic IDataStore getRemoteDataStore() {\n\t\treturn remoteDataStore;\n\n\n\t}\n\t// Cache old location lookups for speed\n\tprivate HashMap<Location, String> oldloclookups = new HashMap<Location, String>();\n\t\n\tpublic String getCityFromLocation(Location l) {\n\t\t//Go to here: http://stackoverflow.com/questions/2296377/how-to-get-city-name-from-latitude-and-longitude-coordinates-in-google-maps\n\t\t\n\t\t//Cache old locations for speed\n\t\tif (oldloclookups.containsKey(l)) {\n\t\t\treturn oldloclookups.get(l);\n\t\t}\n\t\t\n\t\tGeocoder g = new Geocoder(context, Locale.getDefault());\n\t\tif (Geocoder.isPresent()){\n\t\t\t//ROck and roll bitches we can find the place!\n\t\t\tList<Address> la = null;\n\t\t\ttry {\n\t\t\t\tla = g.getFromLocation(l.getLatitude(), l.getLongitude(), 1);\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn \"a Universe\";\n\t\t\t}\n\t\t\tif (la != null && la.size() > 0){\n\t\t\t\tString city = la.get(0).getLocality();\n\t\t\t\toldloclookups.put(l, city);\n\t\t\t\treturn city;\n\t\t\t}\n\t\t} \n\t\treturn \"a Universe\";\n\t\n\t\t\n\t}\n\n}", "public class Image implements Serializable {\n\n\tprivate static final long serialVersionUID = -5471444176345711312L;\n\n\tprivate byte[] imageData;\n\t\n\tpublic Image(Context context, Uri path) {\n\t\tBitmap b = null;\n\t\ttry {\n\t\t\tb = MediaStore.Images.Media.getBitmap(context.getContentResolver(), path);\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t\timageData = null;\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t\timageData = null;\n\t\t}\n\t\tByteArrayOutputStream stream = new ByteArrayOutputStream();\n\t\tb.compress(Bitmap.CompressFormat.JPEG, 50, stream);\n\t\timageData = stream.toByteArray();\n\t}\n\n\tpublic Image(byte[] imageData) {\n\t\tthis.imageData = imageData;\n\t}\n\n\tpublic byte[] getImageData() {\n\t\treturn imageData;\n\t}\n\n\tpublic void setImageData(byte[] imageData) {\n\t\tthis.imageData = imageData;\n\t}\n\t\n\tpublic long getSize(){\n\t\treturn imageData.length;\n\t}\n\tpublic Bitmap getBitmap() {\n\t\tint width = 100;\n\t\tint height = 100;\n\t\tBitmapFactory.Options op = new BitmapFactory.Options();\n\t\top.inPreferredConfig = Bitmap.Config.ARGB_8888;\n\t\tBitmap bmp = BitmapFactory.decodeByteArray(getImageData(), 0,\n\t\t\t\tgetImageData().length);\n\t\tbmp = Bitmap.createScaledBitmap(bmp, width, height, true);\n\t\treturn bmp;\n\t}\n\t\n\tpublic byte[] compress(Bitmap b){\n\t\tByteArrayOutputStream stream = new ByteArrayOutputStream();\n\t\tb.compress(Bitmap.CompressFormat.JPEG, 50, stream);\n\t\tbyte[] imageD = stream.toByteArray();\n\t\treturn imageD;\n\t}\n\n}", "public class Question extends Model implements Serializable, ICommentable {\n\t\n\tprivate static final long serialVersionUID = -8123919371607337418L;\n\n\tprivate UUID id;\n\tprivate String title;\n\tprivate String body;\n\tprivate Image image;\n\tprivate String author;\n\t@SerializedName(\"answers\") private List<UUID> answerList; \n\t@SerializedName(\"comments\") private List<UUID> commentList;\n\tprivate Date date;\n\tprivate int upvotes;\n\tprivate LocationHolder location;\n\n\tpublic Question() {\n\t\tid = new UUID(0L, 0L);\n\t\ttitle = \"\";\n\t\tbody = \"\";\n\t\timage = null;\n\t\tauthor = \"\";\n\t\tanswerList = new ArrayList<UUID>();\n\t\tcommentList = new ArrayList<UUID>();\n\t\tsetDate(new Date());\n\t\tupvotes = 0;\n\t}\n\n\tpublic Question(String title, String body, String author, Image image) {\n\t\tsuper();\n\t\tsetId(UUID.randomUUID());\n\t\tsetTitle(title);\n\t\tsetBody(body);\n\t\tsetAuthor(author);\n\t\tsetImage(image);\n\t\tthis.setAnswerList(new ArrayList<UUID>());\n\t\tthis.setCommentList(new ArrayList<UUID>());\n\t\tupvotes = 0;\n\t\tsetDate(new Date());\n\t}\n\n\t//Add an answer if it already hasn't been\n\tpublic void addAnswer(UUID a) {\n\t\tif (!answerList.contains(a)) {\n\t\t\tanswerList.add(a);\n\t\t}\n\t}\n\t\n\tpublic boolean hasAnswer(UUID a) {\n\t\treturn answerList.contains(a);\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\t/**\n\t * Set the title if there is one and trim the whitespace\n\t * @param title\n\t */\n\tpublic void setTitle(String title) {\n\t\tif (title == null || title.trim().length() == 0)\n\t\t\tthrow new IllegalArgumentException(\"Question title may not be blank.\");\n\t\tthis.title = title.trim();\n\t}\n\t\n\tpublic String getBody() {\n\t\treturn body;\n\t}\n\n\t/**\n\t * Set the body if there is one and trim the whitespace\n\t * @param body\n\t */\n\tpublic void setBody(String body) {\n\t\tif (body == null || body.trim().length() == 0)\n\t\t\tthrow new IllegalArgumentException(\"Question body may not be blank.\");\n\t\tthis.body = body.trim();\n\t}\n\t\n\tpublic Image getImage() {\n\t\treturn image;\n\t}\n\n\tpublic void setImage(Image image) {\n\t\tthis.image = image;\n\t}\n\t\n\tpublic UUID getId() {\n\t\treturn id;\n\t}\n\t\n\tpublic void setId(UUID id) {\n\t\tthis.id = id;\n\t}\n\t\n\tpublic boolean hasComment(UUID comment) {\n\t\treturn commentList.contains(comment);\n\t}\n\n\t//Add comment if it already hasn't been added\n\tpublic void addComment(UUID comment) {\n\t\tif (!commentList.contains(comment)) {\n\t\t\tcommentList.add(comment);\n\t\t}\n\t}\n\n\tpublic void addUpvote() {\n\t\tupvotes++;\n\t}\n\n\tpublic Integer getUpvotes() {\n\t\treturn upvotes;\n\t}\n\t\n\tpublic void setUpvotes(int val) {\n\t\tupvotes = val;\n\t}\n\n\tpublic String getAuthor() {\n\t\treturn this.author;\n\t}\n\n\tpublic void setAuthor(String author) {\n\t\tthis.author = author;\n\t}\n\n\tpublic List<UUID> getCommentList() {\n\t\treturn commentList;\n\t}\n\n\tpublic void setCommentList(List<UUID> commentList) {\n\t\tthis.commentList = commentList;\n\t}\n\n\tpublic List<UUID> getAnswerList() {\n\t\treturn answerList;\n\t}\n\n\tpublic void setAnswerList(List<UUID> answerList) {\n\t\tthis.answerList = answerList;\n\t}\n\t\n\t//Check the Question attributes against each other and return true if they are the same. \n\t//Returns false if a non question is put in\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!(o instanceof Question)) return false;\n\t\tQuestion q = (Question) o;\n\t\t\n\t\treturn q.id.equals(this.id) && q.title.equals(this.title) && q.body.equals(this.body) &&\n\t\t\t\tq.author.equals(this.author) && q.answerList.equals(this.answerList) &&\n\t\t\t\tq.commentList.equals(this.commentList);\n\t}\n\n\t//Return the string representation of a question\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Question [%s: %s - %s]\", title, body, author);\n\t}\n\n\tpublic Date getDate() {\n\t\treturn date;\n\t}\n\n\tpublic void setDate(Date date) {\n\t\tthis.date = date;\n\t}\n\n\tpublic Location getLocation() {\n\t\tif(location == null){\n\t\t\treturn null;\n\t\t}\n\t\treturn location.getLocation();\n\t}\n\n\tpublic void setLocation(LocationHolder lh) {\n\t\tthis.location = lh;\n\t}\n\n\tpublic void setLocation(Location location) {\n\t\tthis.location = LocationHolder.getLocationHolder(location);\n\t}\n\n}", "public class AddImage {\n\t\n \n\tprivate Uri Urifile;\n\tImageButton img;\n\t\n\tpublic Intent takeAPhoto(){\n\t\tString path = Environment.getExternalStorageDirectory().getAbsolutePath() + \"/QAImages\";\n\t\tFile folder = new File(path);\n\t\t\n\t\tif (!folder.exists()){\n\t\t\tfolder.mkdir();\n\t\t}\n\t\t\t\n\t\tString imagePathAndFileName = path + File.separator + \n\t\t\t\tString.valueOf(System.currentTimeMillis()) + \".jpg\" ;\n\t\t\n\t\tFile imageFile = new File(imagePathAndFileName);\n\t\t\n\t\tUrifile = Uri.fromFile(imageFile); \n\t\t\n\t\tIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);\n\t\t\n\t\tintent.putExtra(MediaStore.EXTRA_OUTPUT, Urifile);\n\t\t\n\t\treturn intent;\n\t}\n\t\n\tpublic Uri getImgUri(){\n\t\treturn Urifile;\n\t}\n\t\n\tpublic Intent addPhoto(){\n\t\tIntent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);\n\t\t\n\t\treturn intent;\n\t}\n}", "public class AddQuestionDialogFragment extends DialogFragment\nimplements IView{\n\tprivate LayoutInflater inflater;\n\tprivate View text;\n\tprivate Image img;\n\t@Override\n\tpublic void update() {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\t\n\t@Override\n\tpublic Dialog onCreateDialog(Bundle savedInstanceState) {\n\t\t\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n\t\tfinal Context context = this.getActivity().getApplicationContext();\n\t\tinflater = getActivity().getLayoutInflater();\n\t\ttext = inflater.inflate(R.layout.addquestiondialogfragmentlayout , null);\n\t\tbuilder.setView(text)\n\t\t\t.setPositiveButton(R.string.OK, \n\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\t//Create a new question from data given\n\t\t\t\t\t\t\tDataManager datamanager = DataManager.getInstance(context);\n\t\t\t\t\t\t\tEditText title = (EditText) text.findViewById(R.id.add_question_title);\n\t\t\t\t\t\t\tEditText body = (EditText) text.findViewById(R.id.add_question_body);\n\t\t\t\t\t\t\tCheckBox locationBox = (CheckBox) text.findViewById(R.id.questionLocationBox);\n\t\t\t\t\t\t\tString bd = body.getText().toString();\n\t\t\t\t\t\t\tString tle = title.getText().toString();\n\t\t\t\t\t\t\tLocation loc = null;\n\t\t\t\t\t\t\tif (bd.isEmpty() || tle.isEmpty()) {\n\t\t\t\t\t\t\t\tToast.makeText(getActivity(), \"Questions must have both a valid title and a valid body\", Toast.LENGTH_LONG).show();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(locationBox.isChecked()){\n\t\t\t\t\t\t\t\tLocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);\n\t\t\t\t\t\t\t\tif(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){\n\t\t\t\t\t\t\t\t\tloc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\tToast.makeText(context, \"Please enable GPS to use Location Service\", Toast.LENGTH_SHORT).show();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tMainActivity a = (MainActivity) getActivity();\n\t\t\t\t\t\t\tClientData cd = new ClientData(context);\n\t\t\t\t\t\t\tQuestion newQues = new Question(tle, bd, cd.getUsername(), a.img);\n\t\t\t\t\t\t\tnewQues.setLocation(loc);\n\t\t\t\t\t\t\tdatamanager.addQuestion(newQues, null);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//Populate the list with what we have.\n\t\t\t\t\t\t\ta.updateList(newQues);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t).setNegativeButton(R.string.cancel,\n\t\t\t\t\tnew DialogInterface.OnClickListener() {\t\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\t\t//Do nothing\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\n\t\treturn builder.create();\t\t\t\t\n\t}\n\t\n\tpublic void onResume() {\n\t\tsuper.onResume();\n\t\tMainActivity ma = (MainActivity) getActivity();\n\t\timg = ma.img;\n\n\t\tif (img != null) {\n\t\t\tImageView imgV = (ImageView) text.findViewById(R.id.imageView1);\n\t\t\tBitmap bmp = img.getBitmap();\n\t\t\timgV.setImageBitmap(bmp);\n\t\t}\n\t}\n\t\t\n\n}", "public class QuestionListAdapter extends ArrayAdapter<Question> implements IView {\n\n\tpublic QuestionListAdapter(Context context, int resource, List<Question> objects) {\n\t\tsuper(context, resource, objects);\n\t}\n\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tif (convertView == null) {\n\t\t\tconvertView = LayoutInflater.from(getContext()).inflate(R.layout.list_question, parent, false);\n\t\t}\n\t\tClientData cd = new ClientData(getContext());\n\t\tQuestion q = getItem(position);\n\t\tif(!cd.getFavorites().contains(q.getId())){\n\t\t\t((ImageView)convertView.findViewById(R.id.question_favourite)).setVisibility(View.INVISIBLE);\n\t\t}\n\t\telse{\n\t\t\t((ImageView)convertView.findViewById(R.id.question_favourite)).setVisibility(View.VISIBLE);\n\t\t}\n\t\t//Set the views with data\n\t\tTextView qTitle = (TextView) convertView.findViewById(R.id.question_title); \n\t\tTextView qText = (TextView) convertView.findViewById(R.id.question_body);\n\t\tTextView qAuthor = (TextView) convertView.findViewById(R.id.question_username);\n\t\tTextView qDate = (TextView) convertView.findViewById(R.id.question_date);\n\t\tTextView qUpVotes = (TextView) convertView.findViewById(R.id.question_upvotes);\n\t\tTextView qLocation = (TextView) convertView.findViewById(R.id.questionLocation);\n\n\t\tqTitle.setText(q.getTitle());\n\t\tqText.setText(q.getBody());\n\t\tqAuthor.setText(q.getAuthor());\n\t\tqDate.setText(q.getDate().toString());\n\t\tqUpVotes.setText(q.getUpvotes().toString());\n\t\tif(q.getLocation() != null){\n\t\t\tqLocation.setText(\"near: \" + DataManager.getInstance(getContext()).getCityFromLocation(q.getLocation()));\n\t\t}\n\t\t\n\t\t//Add Read later functionality\n\t\tfinal ImageButton readLaterbutton = (ImageButton)convertView.findViewById(R.id.list_question_read_later);\n\t\treadLaterbutton.setTag(q);\n\t\tClientData clientData = new ClientData(getContext());\n\t\tif(clientData.isReadLater(q.getId())) {\n\t\t\treadLaterbutton.setImageResource(R.drawable.ic_read_later_set);\n\t\t}\n\t\telse{\n\t\t\treadLaterbutton.setImageResource(R.drawable.ic_action_readlater);\n\t\t}\n\t\t\n\t\treadLaterbutton.setFocusable(false);\n\t\treadLaterbutton.setOnClickListener(new ImageButton.OnClickListener(){\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View arg0) {\n\t\t\t\tQuestion question = (Question) readLaterbutton.getTag();\n\t\t\t\tClientData clientData = new ClientData(getContext());\n\t\t\t\tif (clientData.isReadLater(question.getId())) {\n\t\t\t\t\t//Question is already flagged read later.\n\t\t\t\t\tclientData.unmarkReadLater(question.getId());\n\t\t\t\t\treadLaterbutton.setImageResource(R.drawable.ic_action_readlater);\n\t\t\t\t} else {\n\t\t\t\t\tclientData.markReadLater(question.getId());\n\t\t\t\t\treadLaterbutton.setImageResource(R.drawable.ic_read_later_set);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t});\n\t\treturn convertView;\t\n\t}\n\n\t@Override\n\tpublic void update() {\n\t\t//This is proper MVC\n\t\tnotifyDataSetChanged();\n\t}\n\n}", "public class SearchQueryDialogFragment extends DialogFragment{\n\n\t\n\t@Override\n\tpublic Dialog onCreateDialog(Bundle savedInstanceState) {\n\t\tAlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n\t\t\n\t\tLayoutInflater inflater = getActivity().getLayoutInflater();\n\t\tfinal View queryText = inflater.inflate(R.layout.search_fragment, null);\n\t\tbuilder.setTitle(R.string.enter_search_query);\n\t\tbuilder.setView(queryText)\n\t\t.setPositiveButton(R.string.enter, \n\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t// Fire off to SearchActivity with given phrase\n\t\t\t\t\t\tEditText query = (EditText) queryText.findViewById(R.id.queryText);\n\t\t\t\t\t\tString q = query.getText().toString();\n\t\t\t\t\t\tMainActivity ac = (MainActivity) getActivity();\n\t\t\t\t\t\tac.searchQuestions(q);\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\t).setNegativeButton(R.string.cancel,\n\t\t\t\tnew DialogInterface.OnClickListener() {\t\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void onClick(DialogInterface dialog, int which) {\n\t\t\t\t\t\t//Do nothing\n\t\t\t\t\t}\n\t\t\n\t\t\t\n\t\t});\n\t\t\n\t\treturn builder.create();\n\t}\n}" ]
import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.UUID; import ca.ualberta.cs.cmput301f14t14.questionapp.data.Callback; import ca.ualberta.cs.cmput301f14t14.questionapp.data.ClientData; import ca.ualberta.cs.cmput301f14t14.questionapp.data.DataManager; import ca.ualberta.cs.cmput301f14t14.questionapp.model.Image; import ca.ualberta.cs.cmput301f14t14.questionapp.model.Question; import ca.ualberta.cs.cmput301f14t14.questionapp.view.AddImage; import ca.ualberta.cs.cmput301f14t14.questionapp.view.AddQuestionDialogFragment; import ca.ualberta.cs.cmput301f14t14.questionapp.view.QuestionListAdapter; import ca.ualberta.cs.cmput301f14t14.questionapp.view.SearchQueryDialogFragment; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.FragmentManager; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import android.content.Context;
package ca.ualberta.cs.cmput301f14t14.questionapp; public class MainActivity extends Activity { private DataManager dataManager; private QuestionListAdapter qla = null; private List<Question> qList = null; private ClientData cd = null; private Callback<List<Question>> listCallback = null; private Callback<Question> favouriteQuestionCallback = null; private Callback<Question> readLaterQuestionCallback = null; private AddImage AI = new AddImage(); private static final int CAMERA = 1; private static final int ADD_IMAGE = 2;
public Image img;
3
Robyer/Gamework
GameworkApp/src/cz/robyer/gamework/app/activity/GameMapActivity.java
[ "public class GameEvent implements Serializable {\n\n\tprivate static final long serialVersionUID = -624979683919801177L;\n\n\tpublic enum EventType {\n\t\tGAME_START,\t\t\t/** Game start/continue. */\n\t\tGAME_PAUSE,\t\t\t/** Event for pausing game service. */\n\t\tGAME_WIN,\t\t\t/** Player won the game. */\n\t\tGAME_LOSE,\t\t\t/** Player lost the game. */\n\t\tGAME_QUIT,\t\t\t/** Event for stop game service. */\n\t\tUPDATED_LOCATION, \t/** Player's location was updated. */\n\t\tUPDATED_TIME,\t\t/** Game time was updated. */\n\t\tUPDATED_MESSAGES,\t/** Game message was received */\n\t\tSCANNED_CODE,\t\t/** User scanned some QR code */\n\t\tCUSTOM,\t\t\t\t/** Custom event whose value was defined in scenario */\n\t}\n\t\n\tpublic final EventType type;\n\tpublic final Object value;\n\t\n\t/**\n\t * Class constructor for basic events without value.\n\t * @param type\n\t */\n\tpublic GameEvent(EventType type) {\n\t\tthis(type, null);\n\t}\n\t\n\t/**\n\t * Class constructor for events which contains additional value.\n\t * @param type\n\t * @param value\n\t */\n\tpublic GameEvent(EventType type, Object value) {\n\t\tthis.type = type;\n\t\tthis.value = value;\n\t}\n}", "public abstract class GameService extends Service implements GameEventListener, LocationListener {\t\t\n\tprivate static final String TAG = GameService.class.getSimpleName();\n\t\n\t/** signalize that instance of GameService exists */\n\tprivate static boolean running;\n\tprivate static GameService instance;\n\t\n\tprivate Scenario scenario;\n\tprivate GameStatus status = GameStatus.GAME_NONE;\n\tprotected final GameHandler gameHandler = new GameHandler(this);\n\t\n\tprivate Timer timer;\n\tprivate long start, time;\n\t\n\tprivate LocationManager locationManager;\n\tprivate Location location;\n\t\n\t/** help variable for incrementing time value. */\n\tprivate long lastTime;\n\t\n\t/**\n\t * Shortcut for registering {@link GameEventListener}s.\n\t */\n\tpublic final boolean registerListener(GameEventListener listener) {\n \treturn gameHandler.addListener(listener);\n }\n \n\t/**\n\t * Shortcut for unregistering {@link GameEventListener}s.\n\t */\n public final boolean unregisterListener(GameEventListener listener) {\n \treturn gameHandler.removeListener(listener);\n }\n \n @Override\n public final void onCreate() {\n // The service is being created \t\n \tLog.i(TAG, \"onCreate()\");\n \t\n \tinstance = this;\n \trunning = true;\n \tlocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);\n }\n \n @Override\n public final int onStartCommand(Intent intent, int flags, int startId) {\n \tLog.i(TAG, \"onStartCommand()\");\n\n\t\t// TODO: allow starting new game also when in GAME_WON, GAME_LOST status?\n \tif (status != GameStatus.GAME_NONE) {\n \t\t// game is already running, do nothing\n \t\tLog.i(TAG, \"Game is already running\");\n \t\t// inform about game was already started\n \t\tonGameStart(false, intent);\n \t\treturn 0; \t\t\n \t}\n \t\n \tstatus = GameStatus.GAME_LOADING;\n \tscenario = loadScenario(intent);\n \tif (scenario == null) {\n \t\tLog.e(TAG, \"Scenario wasn't loaded\");\n \t\tstatus = GameStatus.GAME_NONE;\n \t\treturn 0;\n \t}\n \t\n \tLog.i(TAG, \"Scenario '\" + scenario.getInfo().title + \"' was loaded\");\n\n \tscenario.setHandler(gameHandler);\n \tregisterListener(this);\n \t\n \tstart = System.currentTimeMillis();\n \tlastTime = SystemClock.uptimeMillis();\n \ttime = 0;\n \t\n \tstatus = GameStatus.GAME_WAITING;\n \t \t\n \t// make this service foreground and show notification\n \tstartForeground(Constants.NOTIFICATION_GAMEPLAY, getGameNotification());\n \t\n \t// register getting location updates\n \tstartLocationUpdates();\n\t\t\n \t// inform about game starting\n\t\tonGameStart(true, intent);\n \t\n \t// service is starting, due to a call to startService()\n return START_NOT_STICKY; // or START_REDELIVER_INTENT?\n }\n \n /**\n * Default method for load scenario from assets.\n * @param intent which was used with startService\n * @return scenario or null if error occurs\n */\n protected Scenario loadScenario(Intent intent) {\n \tString filename = intent.getStringExtra(\"filename\");\n \tScenario scenario = XmlScenarioParser.fromAsset(getApplicationContext(), filename);\n\t\treturn scenario;\n\t}\n\n\t@Override\n public final IBinder onBind(Intent intent) {\n \tLog.i(TAG, \"onBind()\");\n \treturn null; // we don't support binding\n }\n\n @Override\n public final void onDestroy() {\n // service is no longer used and is being destroyed\n \tLog.i(TAG, \"onDestroy()\");\n \t\n \trunning = false;\n \tinstance = null;\n \t\n \tgameHandler.clearListeners();\n \tstopAllUpdates();\n }\n \n /**\n * Returns info whether instance of service exists or not.\n * @return true if instance of GameService exists, false otherwise.\n */\n public static final boolean isRunning() {\n\t\treturn running;\n\t}\n \n /**\n * Returns last saved location of user.\n */\n public final Location getLocation() {\n \treturn location;\n }\n \n /**\n * Returns actual {@link Scenario}.\n */\n public final Scenario getScenario() {\n \treturn scenario;\n }\n\n /**\n * Returns time when game started.\n * @return\n */\n public final long getStartTime() {\n \treturn start;\n }\n \n /**\n * Returns actual game time in milliseconds.\n */\n public final long getTime() {\n \treturn time;\n }\n \n /**\n * Returns actual status of game.\n */\n public final GameStatus getStatus() {\n \treturn status;\n }\n \n /**\n * Returns instance of this game.\n */\n public static final GameService getInstance() {\n \treturn instance;\n }\n \n /**\n\t * Calculate and update actual game time.\n\t * @return time - actual game time\n\t */\n\tprivate final long updateGameTime() {\n\t\tlong now = SystemClock.uptimeMillis();\n\t\ttime += now - lastTime;\n\t\tlastTime = now;\n\t\treturn time;\n\t}\n\t\n\t/**\n\t * Gets and broadcasts new user location.\n\t */\n @Override\n public final void onLocationChanged(Location location) {\n \tthis.location = location;\n \tgameHandler.broadcastEvent(new GameEvent(EventType.UPDATED_LOCATION, location));\n }\n\n\t@Override public final void onProviderDisabled(String provider) {}\n\t@Override public final void onProviderEnabled(String provider) {}\n\t@Override public final void onStatusChanged(String provider, int status, Bundle extras) {}\n\t\n\t/**\n\t * Returns game notification to show when game is running.\n\t */\n\tprotected abstract Notification getGameNotification();\n\t\n\t/**\n\t * This is called after receiving new startService intent.\n\t * @param starting means that {@link GameService} was just started for first time (true)\n\t * or that new intent was received when game is running (false).\n\t * @param intent which was used when starting this service\n\t * @see #startService(Intent)\n\t */\n\tprotected abstract void onGameStart(boolean starting, Intent intent);\n\t\n\t/**\n\t * This method is called every time when there was new event received.\n\t * @param event\n\t */\n\tprotected abstract void onEvent(GameEvent event);\n\t\n\t/**\n\t * Show or update this service's notification.\n\t * This method uses {@link #getGameNotification()} to get notification.\n\t */\n\tpublic final void refreshNotification(boolean foreground) {\n\t\tif (foreground) {\n\t\t\tstartForeground(Constants.NOTIFICATION_GAMEPLAY, getGameNotification());\n\t\t} else {\n \t\tNotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n \t\t\tmNotificationManager.notify(Constants.NOTIFICATION_GAMEPLAY, getGameNotification());\n \t}\n\t}\n\t\n\t/**\n\t * Starts requesting location updates.\n\t */\n\tprivate final void startLocationUpdates() {\n\t\tif (locationManager != null) { \t\t\n \t\tlocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);\n \t\tlocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);\n \t}\n\t}\n\t\n\t/**\n\t * Creates and starts timer (if not exists already) for getting time updates.\n\t */\n\tprivate final void startTimeUpdates() {\n\t\tif (timer == null) {\n \t\ttimer = new Timer();\n \ttimer.schedule(new TimerTask() {\n \t\t@Override\n \t\tpublic void run() {\n \t\t\tlong time = updateGameTime();\n \t\t\tgameHandler.broadcastEvent(new GameEvent(EventType.UPDATED_TIME, time));\n \t\t}\n \t}, 1000, 1000);\n\t\t}\n\t}\n\t\n\t/**\n\t * Stops location and time updates.\n\t */\n\tprivate final void stopAllUpdates() {\n\t\tif (locationManager != null)\n\t\t\tlocationManager.removeUpdates(this);\n\t\t\n\t\tif (timer != null) {\n\t\t\ttimer.cancel();\n\t\t\ttimer.purge();\n\t\t\ttimer = null;\n\t\t}\n\t}\n\n\t/**\n\t * Received game event handling.\n\t */\n @Override\n\tpublic final void receiveEvent(GameEvent event) {\n \t\n \tswitch (event.type) {\n \tcase GAME_START:\n \t\tif (status != GameStatus.GAME_WAITING && status != GameStatus.GAME_PAUSED) {\n \t\t\tLog.w(TAG, \"Game can't be started in '\" + status + \"' state. Only GAME_WAITING and GAME_PAUSED allowed\");\n \t\t\tbreak;\n \t\t}\n \t\tlastTime = SystemClock.uptimeMillis();\n \t\t\n \t\tstartTimeUpdates();\n \t\t\t\n \t// requesting location updates was already done if game service is in waiting state\n \tif (status != GameStatus.GAME_WAITING)\n \t\tstartLocationUpdates();\n \t\n \tstatus = GameStatus.GAME_RUNNING;\n \t\tbreak;\n \t\n \tcase GAME_PAUSE:\n \tcase GAME_WIN:\n \tcase GAME_LOSE:\n \t\tif (status != GameStatus.GAME_RUNNING) {\n \t\t\tLog.w(TAG, \"Game can't be paused/won/lost in '\" + status + \"' state. Only GAME_RUNNING allowed\");\n \t\t\tbreak;\n \t\t} \t\t\n \t\tstopAllUpdates();\n\n \t\tif (event.type == EventType.GAME_WIN)\n \t\t\tstatus = GameStatus.GAME_WON;\n \t\telse if (event.type == EventType.GAME_LOSE)\n \t\t\tstatus = GameStatus.GAME_LOST;\n \t\telse\n \t\t\tstatus = GameStatus.GAME_PAUSED;\n \t\t\n \t \t\tbreak;\n \t \t\t\n \tcase GAME_QUIT:\n \t\tstopSelf();\n \t\tstatus = GameStatus.GAME_NONE;\n \t\tbreak;\n \t \t\t\n \tcase UPDATED_LOCATION:\n \t\tif (status == GameStatus.GAME_RUNNING && location != null) {\n \t\t\tLocation loc = event.value != null ? (Location)event.value : location;\n \t\t\tscenario.onLocationUpdate(loc.getLatitude(), loc.getLongitude());\n \t\t}\n \t\tbreak;\n \t\t\n \tcase UPDATED_TIME:\n \t\tif (status == GameStatus.GAME_RUNNING) {\n \t\t\tlong t = event.value != null ? (Long)event.value : time;\n \t\t\tscenario.onTimeUpdate(t);\n \t\t}\n \t\tbreak;\n \t\t\n \tcase CUSTOM:\n \t\tif (status == GameStatus.GAME_RUNNING && event.value != null)\n \t\t\tscenario.onCustomEvent(event.value);\n \t\tbreak;\n \t\t\n \tcase SCANNED_CODE:\n \t\tif (status == GameStatus.GAME_RUNNING && event.value != null)\n \t\t\tscenario.onScanned(event.value);\n \t\tbreak;\n\n \tdefault:\n \t\tbreak;\n \t}\n \t\n \tonEvent(event);\n\t}\n \n /**\n * Starts scanner activity or show alert dialog asking for download scanner application first.\n * @param activity which will wait for result.\n * @see GameService#onActivityResult(int, int, Intent)\n */\n public void startScanner(final Activity activity) {\n \tIntent intent = new Intent(Constants.SCANNER_SCAN);\n\n \tif (Utils.isIntentCallable(getApplicationContext(), intent)) {\n \t\tactivity.startActivityForResult(intent, Constants.SCANNER_CODE);\n \t} else {\n \t\tAlertDialog.Builder builder = new AlertDialog.Builder(activity);\n \t\tbuilder.setMessage(Constants.SCANNER_MISSING)\n \t\t\t.setCancelable(true)\n \t\t\t.setPositiveButton(\"Google Play\", new DialogInterface.OnClickListener() {\n \t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n \t\t\t\t\tIntent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.SCANNER_URL_MARKET));\n \t\t\t\t\tactivity.startActivity(intent);\n \t\t\t\t}\n \t\t\t})\n \t\t\t.setNeutralButton(\"Web browser\", new DialogInterface.OnClickListener() {\n \t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n \t\t\t\t\tIntent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.SCANNER_URL_DIRECT));\n \t\t\t\t\tactivity.startActivity(intent);\n \t\t\t\t}\n \t\t\t})\n \t\t\t.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n \t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n \t\t\t\t\tdialog.cancel();\n \t\t\t\t}\n \t\t\t});\n\n \t\tbuilder.create().show(); \t\t\n \t}\n }\n\n /**\n * Process activity result to handle scanned data. This must be called from Activity, which started {@link #startScanner(Activity)}. \n * @param requestCode\n * @param resultCode\n * @param data\n * @return true if code was properly scanned, false otherwise.\n * @see Activity#onActivityResult(int, int, Intent)\n * @see GameService#startScanner(Activity)\n */\n public boolean onActivityResult(int requestCode, int resultCode, Intent data) {\n \tif (requestCode == Constants.SCANNER_CODE && data != null && data.getExtras() != null) {\n\t\t\tString result = data.getExtras().getString(Constants.SCANNER_RESULT);\n \t\tgameHandler.broadcastEvent(new GameEvent(EventType.SCANNED_CODE, result));\n \t\treturn true;\n \t}\n \treturn false;\n }\n\n}", "public class Scenario {\n\tprivate static final String TAG = Scenario.class.getSimpleName();\n\t\n\tprotected final Context context;\n\tprotected final ScenarioInfo info;\n\tprotected GameHandler handler;\n\t\n\tprotected final Map<String, Area> areas = new HashMap<String, Area>();\n\tprotected final Map<String, Variable> variables = new HashMap<String, Variable>();\n\tprotected final Map<String, Reaction> reactions = new HashMap<String, Reaction>();\n\tprotected final Map<String, Message> messages = new HashMap<String, Message>();\n\tprotected final List<Hook> hooks = new ArrayList<Hook>();\n\t\n\t// TODO: implement onLoadComplete listener and wait for its loading before starting game\n\t// http://stackoverflow.com/questions/14782579/waiting-for-soundpool-to-load-before-moving-on-with-application\n\t// http://stackoverflow.com/questions/14300293/soundpool-loading-never-ends\n\t// http://stackoverflow.com/questions/5202510/soundpool-sample-not-ready\n\tprotected final SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);\n\t\n\t// Helpers providing hookable interface for special events\n\tprotected final TimeHookable timeHookable = new TimeHookable(this);\n\tprotected final ScannerHookable scannerHookable = new ScannerHookable(this);\n\tprotected final EventHookable eventHookable = new EventHookable(this);\n\t\n\t/**\n\t * Class constructor.\n\t * @param context - application context\n\t * @param info - scenario info\n\t */\n\tpublic Scenario(Context context, ScenarioInfo info) {\n\t\tthis.context = context;\n\t\tthis.info = info;\n\t}\n\t\n\t/**\n\t * Class constructor\n\t * @param context - application context\n\t * @param handler - game handler\n\t * @param info - scenario info\n\t */\n\tpublic Scenario(Context context, GameHandler handler, ScenarioInfo info) {\n\t\tthis(context, info);\n\t\tsetHandler(handler);\n\t}\n\n\tpublic Context getContext() {\n\t\treturn context;\n\t}\n\t\n\tpublic GameHandler getHandler() {\n\t\treturn handler;\n\t}\n\t\n\tpublic void setHandler(GameHandler handler) {\n\t\tthis.handler = handler;\n\t}\n\n\tpublic SoundPool getSoundPool() {\n\t\treturn soundPool;\n\t}\n\t\n\tpublic void addArea(String id, Area area) {\n\t\tif (area == null) {\n\t\t\tLog.w(TAG, \"addArea() with null area\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (areas.containsKey(id))\n\t\t\tLog.w(TAG, \"Duplicit definition of area id='\" + id + \"'\");\n\t\t\n\t\tareas.put(id, area);\n\t\tarea.setScenario(this);\n\t}\n\t\n\tpublic void addArea(Area area) {\n\t\taddArea(area.getId(), area);\n\t}\n\t\n\tpublic Area getArea(String id) {\n\t\treturn areas.get(id);\n\t}\n\t\n\tpublic Map<String, Area> getAreas() {\n\t\treturn areas;\n\t}\n\t\n\tpublic void addVariable(String id, Variable variable) {\n\t\tif (variable == null) {\n\t\t\tLog.w(TAG, \"addVariable() with null variable\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (variables.containsKey(id))\n\t\t\tLog.w(TAG, \"Duplicit definition of variable id='\" + id + \"'\");\n\t\t\n\t\tvariables.put(id, variable);\n\t\tvariable.setScenario(this);\n\t}\n\t\n\tpublic void addVariable(Variable variable) {\n\t\taddVariable(variable.getId(), variable);\n\t}\n\t\n\tpublic Variable getVariable(String id) {\n\t\treturn variables.get(id);\n\t}\n\n\tpublic void addReaction(String id, Reaction reaction) {\n\t\tif (reaction == null) {\n\t\t\tLog.w(TAG, \"addReaction() with null reaction\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (reactions.containsKey(id))\n\t\t\tLog.w(TAG, \"Duplicit definition of reaction id='\" + id + \"'\");\n\t\t\n\t\treactions.put(id, reaction);\n\t\treaction.setScenario(this);\n\t}\n\t\n\tpublic void addReaction(Reaction reaction) {\n\t\taddReaction(reaction.getId(), reaction);\n\t}\n\t\n\tpublic Reaction getReaction(String id) {\n\t\treturn reactions.get(id);\n\t}\n\t\n\tpublic void addMessage(String id, Message message) {\n\t\tif (message == null) {\n\t\t\tLog.w(TAG, \"addMessage() with null message\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (messages.containsKey(id))\n\t\t\tLog.w(TAG, \"Duplicit definition of message id='\" + id + \"'\");\n\t\t\n\t\tmessages.put(id, message);\n\t\tmessage.setScenario(this);\n\t}\n\t\n\tpublic void addMessage(Message message) {\n\t\taddMessage(message.getId(), message);\n\t}\n\t\n\tpublic Message getMessage(String id) {\n\t\treturn messages.get(id);\n\t}\n\t\n\t/**\n\t * Returns all visible (received and not deleted) messages with specified tag.\n\t * @param tag of message, use empty string for messages without tag or null for all messages\n\t * @return list of messages\n\t */\n\tpublic List<Message> getVisibleMessages(String tag) {\n\t\tList<Message> list = new ArrayList<Message>();\n\t\tfor (Message m : messages.values()) {\n\t\t\tif (m.isVisible() && (tag == null || tag.equalsIgnoreCase(m.getTag())))\n\t\t\t\tlist.add(m);\n\t\t}\n\t\treturn list;\n\t}\n\n\tpublic void addHook(Hook hook) {\n\t\tif (hook == null) {\n\t\t\tLog.w(TAG, \"addHook() with null hook\");\n\t\t\treturn;\n\t\t}\n\t\t\n\t\thooks.add(hook);\n\t\thook.setScenario(this);\n\t}\n\n\tpublic ScenarioInfo getInfo() {\n\t\treturn info;\n\t}\n\n\tpublic void onTimeUpdate(long time) {\n\t\ttimeHookable.updateTime(time);\n\t}\n\n\tpublic void onLocationUpdate(double lat, double lon) {\n\t\tfor (Area a : areas.values()) {\n\t\t\ta.updateLocation(lat, lon);\n\t\t}\n\t}\n\t\n\tpublic void onCustomEvent(Object data) {\n\t\teventHookable.update(data);\n\t}\n\t\n\t/**\n\t * Called after sucessfuly scanned code.\n\t * @param data - scanned value from code\n\t */\n\tpublic void onScanned(Object data) {\n\t\tscannerHookable.update(data);\n\t}\n\n\tprivate void initializeHooks() {\n\t\tLog.i(TAG, \"Initializing hooks\");\n\t\tfor (Hook hook : hooks) {\n\t\t\tHookableObject hookable = null;\n\t\t\tString type = null;\n\t\t\t\n\t\t\tswitch (hook.getType()) {\n\t\t\tcase AREA:\n\t\t\tcase AREA_ENTER:\n\t\t\tcase AREA_LEAVE:\n\t\t\t\thookable = areas.get(hook.getValue());\n\t\t\t\ttype = \"Area\";\n\t\t\t\tbreak;\n\t\t\tcase VARIABLE:\n\t\t\t\thookable = variables.get(hook.getValue());\n\t\t\t\ttype = \"Variable\";\n\t\t\t\tbreak;\n\t\t\tcase TIME:\n\t\t\t\thookable = timeHookable;\n\t\t\t\ttype = \"Time\";\n\t\t\t\tbreak;\n\t\t\tcase SCANNER:\n\t\t\t\thookable = scannerHookable;\n\t\t\t\ttype = \"Scanner\";\n\t\t\t\tbreak;\n\t\t\tcase EVENT:\n\t\t\t\thookable = eventHookable;\n\t\t\t\ttype = \"Event\";\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (hookable != null) {\n\t\t\t\thookable.addHook(hook);\n\t\t\t} else {\n\t\t\t\tLog.e(TAG, String.format(\"Hook can't be attached to %s '%s'\", type, hook.getValue()));\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Called after whole scenario was loaded (all game items are present).\n\t */\n\tpublic void onLoaded() {\n\t\tLog.i(TAG, \"Scenario objects was loaded\");\n\t\t\n\t\tinitializeHooks();\n\t\t\n\t\tboolean ok = true;\n\t\t\n\t\tfor (BaseObject obj : areas.values())\n\t\t\tif (!obj.onScenarioLoaded())\n\t\t\t\tok = false;\n\t\t\n\t\tfor (BaseObject obj : reactions.values())\n\t\t\tif (!obj.onScenarioLoaded())\n\t\t\t\tok = false;\n\t\t\n\t\tfor (BaseObject obj : variables.values())\n\t\t\tif (!obj.onScenarioLoaded())\n\t\t\t\tok = false;\n\t\t\n\t\tfor (BaseObject obj : hooks)\n\t\t\tif (!obj.onScenarioLoaded())\n\t\t\t\tok = false;\n\t\t\n\t\tif (!ok)\n\t\t\tLog.e(TAG, \"onScenarioLoaded() finished with errors\");\n\t\telse\n\t\t\tLog.i(TAG, \"onScenarioLoaded() finished without errors\");\n\t}\n\n}", "public abstract class Area extends HookableObject {\n\tprotected boolean inArea = false;\n\t\n\t/**\n\t * Class constructor\n\t * @param id Identificator of area.\n\t */\n\tpublic Area(String id) {\n\t\tsuper(id);\n\t}\n\t\n\t/**\n\t * Checks if user is inside area.\n\t * @return true if user is inside, false otherwise.\n\t */\n\tpublic final boolean isInside() {\n\t\treturn inArea;\n\t}\n\t\n\t/**\n\t * Checks if particular latitude and longitude is in this area.\n\t * @param lat latitude\n\t * @param lon longitude\n\t * @return true if location is inside area, false otherwise\n\t */\n\tabstract protected boolean isPointInArea(double lat, double lon);\n\t\n\t/**\n\t * Updates actual location of player for this area and call hooks if entering/leaving.\n\t * @param lat latitude of player\n\t * @param lon longitude of player\n\t */\n\tpublic void updateLocation(double lat, double lon) {\n\t\tboolean r = isPointInArea(lat, lon);\n\t\t\n\t\tif (inArea != r) {\n\t\t\t// entering or leaving area\n\t\t\tLog.i(TAG, String.format(\"We %s location\", (r ? \"entered\" : \"leaved\")));\n\t\t\tinArea = r;\n\t\t\tcallHooks(r);\n\t\t}\n\t}\n\t\n\t/**\n\t * Call valid attached hooks.\n\t * @param inside - did player entered or leaved this area?\n\t */\n\tprotected void callHooks(boolean inside) {\n\t\tif (hooks == null)\n\t\t\treturn;\n\t\t\n\t\tfor (Hook h : hooks) {\n\t\t\tboolean valid = false;\n\t\t\t\t\n\t\t\tswitch (h.getType()) {\n\t\t\tcase AREA:\n\t\t\t\tvalid = true;\n\t\t\t\tbreak;\n\t\t\tcase AREA_ENTER:\n\t\t\t\tvalid = inside;\n\t\t\t\tbreak;\n\t\t\tcase AREA_LEAVE:\n\t\t\t\tvalid = !inside;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\t\n\t\t\tif (valid)\n\t\t\t\th.call(null);\n\t\t}\n\t}\n\n}", "public class MultiPointArea extends Area {\n\tprotected List<GPoint> points;\n\tprotected double minLat;\n\tprotected double maxLat;\n\tprotected double minLon;\n\tprotected double maxLon;\n\n\t/**\n\t * Class constructor.\n\t * @param id - identificator of area.\n\t */\n\tpublic MultiPointArea(String id) {\n\t\tsuper(id);\n\t}\n\n\t/**\n\t * Add point of Area.\n\t * There is no need to \"close-circle\" (add also \"first point\" as the end point again)\n\t * @param point\n\t */\n\tpublic void addPoint(GPoint point) {\n\t\tif (point == null)\n\t\t\treturn;\n\t\t\n\t\tif (points == null)\n\t\t\tpoints = new ArrayList<GPoint>();\n\t\t\t\n\t\tpoints.add(point);\n\t\tcalcBoundaries(point.latitude, point.longitude);\n\t}\n\n\t/**\n\t * Return list of all points of this area.\n\t * @return list of points or null, if no points.\n\t */\n\tpublic List<GPoint> getPoints() {\n\t\treturn points;\n\t}\n\n\t/**\n\t * Calculate min/max latitude/longitude for new point for optimalization.\n\t * @param lat - latitude of newly added point\n\t * @param lon - longitude of newly added point\n\t */\n\tprivate void calcBoundaries(double lat, double lon) {\n\t\tif (minLat > lat) minLat = lat;\t\t\n\t\tif (maxLat < lat) maxLat = lat;\t\t\n\t\tif (minLon > lon) minLon = lon;\t\t\n\t\tif (maxLon < lon) maxLon = lon;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see cz.robyer.gamework.scenario.area.Area#isPointInArea(double, double)\n\t */\n\t@Override\n\tprotected boolean isPointInArea(double lat, double lon) {\n\t\tif (points.size() < 3) {\n\t\t\tLog.e(TAG, \"MultiPointArea must contain at least 3 points\");\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// little optimalization - check min-max rectangle first \n\t\tif (lat < minLat || lat > maxLat || lon < minLon || lon > maxLon)\n\t\t\treturn false;\n\t\t\n\t\tboolean c = false;\n\t\t// algorithm from http://www.faqs.org/faqs/graphics/algorithms-faq/\n\t\tfor (int i = 0, j = points.size()-1; i < points.size(); j = i++) {\n\t\t\tif ((((points.get(i).latitude <= lat) && (lat < points.get(j).latitude)) ||\n\t\t\t\t((points.get(j).latitude <= lat) && (lat < points.get(i).latitude))) &&\n\t\t\t\t(lon < (points.get(j).longitude - points.get(i).longitude) * (lat - points.get(i).latitude) / (points.get(j).latitude - points.get(i).latitude) + points.get(i).longitude))\n\t\t\t\tc = !c;\n\t\t}\n\t\t\n\t\t// algorithm from http://en.wikipedia.org/wiki/Even-odd_rule\n\t\t/*for (int i = 0, j = points.size()-1; i < points.size(); j = i++) {\n\t\t\tif (((points.get(i).latitude > lat) != (points.get(j).latitude > lat)) &&\n\t\t\t\t(lon < (points.get(j).longitude - points.get(i).longitude) *\n\t\t\t\t(lat - points.get(i).latitude) / (points.get(j).latitude - points.get(i).latitude) + points.get(i).longitude))\t\n\t\t\t\tc = !c;\n\t\t}*/\n\t\t\n\t\treturn c;\n\t}\n\n}", "public class PointArea extends Area {\n\tprotected static int LEAVE_RADIUS = 3;\n\t\n\tprotected GPoint point; // center\n\tprotected int radius; // radius in meters\n\t\n\tpublic PointArea(String id, GPoint point, int radius) {\n\t\tsuper(id);\n\t\tthis.point = point;\n\t\tthis.radius = radius;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see cz.robyer.gamework.scenario.area.Area#isPointInArea(double, double)\n\t */\n\t@Override\n\tprotected boolean isPointInArea(double lat, double lon) {\n\t\treturn GPoint.distanceBetween(point.latitude, point.longitude, lat, lon) < (radius + (inArea ? LEAVE_RADIUS : 0));\n\t}\n\n\t/**\n\t * Returns center point of this area.\n\t * @return center point\n\t */\n\tpublic GPoint getPoint() {\n\t\treturn point;\n\t}\n\n\t/**\n\t * Returns radius of this area.\n\t * @return radius in meters\n\t */\n\tpublic int getRadius() {\n\t\treturn radius;\n\t}\n\t\n}", "public class SoundArea extends PointArea {\n\tprotected String value;\n\tprotected int soundId = -1;\n\tprotected float maxVolume = 1.0f;\n\tprotected float minVolume = 0.0f;\n\tprotected float pitch = 1.0f;\n\tprotected int loop = -1; // loop forever\n\tprotected int soundRadius;\n\tprotected boolean inSoundRadius = false;\n\t\n\t/**\n\t * Class constructor\n\t * @param id - identificator of area\n\t * @param point - center point of area\n\t * @param radius - radius in meters\n\t * @param value - sound to be played\n\t * @param soundRadius - radius in which sound will be played, in meters\n\t */\n\tpublic SoundArea(String id, GPoint point, int radius, String value, int soundRadius) {\n\t\tsuper(id, point, radius);\n\t\tthis.value = value;\n\t\tthis.soundRadius = soundRadius;\n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see cz.robyer.gamework.scenario.BaseObject#setScenario(cz.robyer.gamework.scenario.Scenario)\n\t */\n\t@Override\n\tpublic void setScenario(Scenario scenario) {\n\t\tsuper.setScenario(scenario);\n\t\t\n\t\tif (soundId == -1) {\n\t\t\tAssetFileDescriptor descriptor = null;\n\t\t\ttry {\n\t\t\t\t// TODO: maybe not use soundpool but classic audiomanager for this, as this could be music\n\t\t\t\tdescriptor = getContext().getAssets().openFd(value);\n\t\t\t\tsoundId = getScenario().getSoundPool().load(descriptor, 1);\n\t\t\t} catch (IOException e) {\n\t\t\t\tLog.e(TAG, String.format(\"Can't load sound '%s'\", value));\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t \tif (descriptor != null)\n\t\t \t\tdescriptor.close();\n\t\t } catch (IOException ioe) {\n\t\t \tLog.e(TAG, ioe.getMessage(), ioe);\n\t\t }\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sets volume limit for this sound, must be min < max.\n\t * @param min - minimal value, must be >= 0.0f, otherwise will be used 0.0f\n\t * @param max - maximal value, must be <= 1.0f, otherwise will be used 1.0f\n\t */\n\tpublic void setVolumeLimit(float min, float max) {\n\t\tif (min >= max) {\n\t\t\tLog.e(TAG, String.format(\"Volume limit is incorrect - min '%.2f' must be lower than max '%.2f'\", min, max));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tthis.minVolume = Math.min(Math.max(min, 0.0f), 1.0f);\n\t\tthis.maxVolume = Math.max(Math.min(max, 1.0f), 0.0f);\n\t}\n\t\n\t/**\n\t * Calculate sound volume depending on distance\n\t * @param distance in meters\n\t * @return volume between minVolume to maxVolume\n\t */\n\tprotected float calcVolume(double distance) {\n\t\treturn minVolume + (maxVolume - minVolume) * (float)((soundRadius - distance) / soundRadius); \n\t}\n\t\n\t/* (non-Javadoc)\n\t * @see cz.robyer.gamework.scenario.area.Area#updateLocation(double, double)\n\t */\n\t@Override\n\tpublic void updateLocation(double lat, double lon) {\n\t\t// update state of inArea and eventually call hooks\n\t\tsuper.updateLocation(lat, lon);\n\t\t\n\t\tif (soundId == -1) {\n\t\t\tLog.e(TAG, String.format(\"Sound '%s' is not loaded\", value));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// start/stop playing sound or update volume\n\t\tdouble distance = GPoint.distanceBetween(point.latitude, point.longitude, lat, lon);\n\t\tboolean r = distance < (soundRadius + (inSoundRadius ? LEAVE_RADIUS : 0));\n\t\tfloat actualVolume = calcVolume(distance);\n\n\t\tSoundPool soundPool = getScenario().getSoundPool();\n\n\t\tif (inSoundRadius != r) {\n\t\t\tinSoundRadius = r;\n\t\t\t\n\t\t\tif (inSoundRadius) {\n\t\t\t\tLog.d(TAG, String.format(\"Started playing sound '%s' at volume '%.2f'\", value, actualVolume));\n\t\t\t\tsoundPool.play(soundId, actualVolume, actualVolume, 1, loop, pitch);\n\t\t\t} else {\n\t\t\t\tLog.d(TAG, String.format(\"Stopped playing sound '%s'\", value));\n\t\t\t\tsoundPool.stop(soundId);\n\t\t\t}\n\t\t} else if (inSoundRadius) {\n\t\t\t// update sound volume \n\t\t\tLog.d(TAG, String.format(\"Changed volume of sound '%s' to '%.2f'\", value, actualVolume));\n\t\t\tsoundPool.setVolume(soundId, actualVolume, actualVolume);\n\t\t}\n\t}\n\t\n}", "public class GPoint {\n\n\tpublic final double latitude;\n\tpublic final double longitude;\n\t\n\t/**\n\t * @param latitude\n\t * @param longitude\n\t */\n\tpublic GPoint(double latitude, double longitude) {\n\t\tthis.latitude = latitude;\n\t\tthis.longitude = longitude;\n\t}\n\n\t/**\n\t * Slightly modified version of code from http://www.androidsnippets.com/distance-between-two-gps-coordinates-in-meter\n\t * @return Distance in meters between given coordinates\n\t */\n\tpublic static double distanceBetween(double latFrom, double lonFrom, double latTo, double lonTo) {\n\t double pk = 180 / Math.PI;\n\n\t double a1 = latFrom / pk;\n\t double a2 = lonFrom / pk;\n\t double b1 = latTo / pk;\n\t double b2 = lonTo / pk;\n\n\t double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);\n\t double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);\n\t double t3 = Math.sin(a1) * Math.sin(b1);\n\t double tt = Math.acos(t1 + t2 + t3);\n\t \n\t double ellipsoidRadius = 6378.137 * (1 - 0.0033493 * Math.pow(Math.sin(0.5 * (latFrom + latTo)), 2));\n\t \n\t return ellipsoidRadius * tt * 1000;\n\t}\n\n}" ]
import java.util.List; import java.util.Map; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolygonOptions; import cz.robyer.gamework.game.GameEvent; import cz.robyer.gamework.game.GameService; import cz.robyer.gamework.scenario.Scenario; import cz.robyer.gamework.scenario.area.Area; import cz.robyer.gamework.scenario.area.MultiPointArea; import cz.robyer.gamework.scenario.area.PointArea; import cz.robyer.gamework.scenario.area.SoundArea; import cz.robyer.gamework.utils.GPoint; import cz.robyer.gamework.app.R;
package cz.robyer.gamework.app.activity; /** * Represents game map with showed areas and player position. * @author Robert Pösel */ public class GameMapActivity extends BaseGameActivity { private static final String TAG = GameMapActivity.class.getSimpleName(); private GoogleMap map; private Marker playerMarker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_map); initButtons(); } @Override protected void onResume() { super.onResume(); if (!GameService.isRunning()) return; final GameService game = getGame(); if (map == null) { map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); if (map != null) { Scenario scenario = null; if (game != null) scenario = game.getScenario(); if (scenario != null) { Map<String, Area> areas = scenario.getAreas(); for (Area a : areas.values()) { Log.d(TAG, "Draw area " + a.getId()); if (a instanceof PointArea || a instanceof SoundArea) { PointArea area = (PointArea)a; CircleOptions circle = new CircleOptions(); circle.center(toLatLng(area.getPoint())); circle.radius(area.getRadius()); circle.strokeWidth(2); circle.fillColor(Color.argb(40, 255, 0, 0)); map.addCircle(circle); } else if (a instanceof MultiPointArea) { MultiPointArea area = (MultiPointArea)a; PolygonOptions polygon = new PolygonOptions(); List<GPoint> points = area.getPoints(); for (GPoint p : points) { polygon.add(toLatLng(p)); } polygon.strokeWidth(2); polygon.fillColor(Color.argb(40, 0, 255, 0)); map.addPolygon(polygon); } } } map.setOnMapLongClickListener(new OnMapLongClickListener() { @Override public void onMapLongClick(LatLng point) { Toast.makeText(GameMapActivity.this, "Player location set.", Toast.LENGTH_SHORT).show(); Location location = new Location("custom"); location.setLatitude(point.latitude); location.setLongitude(point.longitude); game.onLocationChanged(location); } }); } } if (game != null) updateMarker(game.getLocation()); } /** * Checks game events and enabled/disables player location layer. */
public void receiveEvent(final GameEvent event) {
0
gill3s/opentipbot
opentipbot-service/src/main/java/opentipbot/service/OpenTipBotUserService.java
[ "@Entity\n@Table(name = \"opentipbot_command\")\npublic class OpenTipBotCommand extends BaseEntity<Long> {\n\n @Id\n @GeneratedValue\n private Long id;\n\n @NotNull\n private OpenTipBotCommandEnum opentipbotCommandEnum;\n\n private String fromUserName;\n\n private String toUserName;\n\n private String toUsernames;\n\n private String txId;\n\n private Double amout;\n\n private String errorMessage;\n\n private String notificationText;\n\n private Long tweetIdentifier;\n\n private String coinAddress;\n\n private String originaleTweet;\n\n @NotNull\n private OpenTipBotCommandStatus opentipbotCommandStatus;\n\n public OpenTipBotCommandEnum getOpenTipBotCommandEnum() {\n return opentipbotCommandEnum;\n }\n\n public OpenTipBotCommandStatus getOpenTipBotCommandStatus() {\n return opentipbotCommandStatus;\n }\n\n public void setOpenTipBotCommandStatus(OpenTipBotCommandStatus opentipbotCommandStatus) {\n this.opentipbotCommandStatus = opentipbotCommandStatus;\n }\n\n public Long getTweetIdentifier() {\n return tweetIdentifier;\n }\n\n public void setTweetIdentifier(Long tweetId) {\n this.tweetIdentifier = tweetId;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n @Override\n public Long getId() {\n return this.id;\n }\n\n public OpenTipBotCommandEnum getCommand() {\n return this.opentipbotCommandEnum;\n }\n\n public void setOpenTipBotCommandEnum(OpenTipBotCommandEnum opentipbotCommandEnum) {\n this.opentipbotCommandEnum = opentipbotCommandEnum;\n }\n\n public String getFromUserName() {\n return fromUserName;\n }\n\n public void setFromUserName(String fromUserName) {\n this.fromUserName = fromUserName;\n }\n\n public String getToUserName() {\n return toUserName;\n }\n\n public void setToUserName(String toUserName) {\n this.toUserName = toUserName;\n }\n\n public Double getAmout() {\n return amout;\n }\n\n public void setAmout(Double amout) {\n this.amout = amout;\n }\n\n public String getCoinAddress() {\n return coinAddress;\n }\n\n public void setCoinAddress(String coinAddress) {\n this.coinAddress = coinAddress;\n }\n\n public String getToUsernames() {\n return toUsernames;\n }\n\n public void setToUsernames(String toUsernames) {\n this.toUsernames = toUsernames;\n }\n\n @Transient\n public String[] getToUsernamesList(){\n return this.toUsernames.split(\",\");\n }\n\n public String getTxId() {\n return txId;\n }\n\n public void setTxId(String txId) {\n this.txId = txId;\n }\n\n public String getErrorMessage() {\n return errorMessage;\n }\n\n public void setErrorMessage(String errorMessage) {\n this.errorMessage = errorMessage;\n }\n\n public String getNotificationText() {\n return notificationText;\n }\n\n public void setNotificationText(String notificationText) {\n this.notificationText = notificationText;\n }\n\n public String getOriginaleTweet() {\n return originaleTweet;\n }\n\n public void setOriginaleTweet(String originaleTweet) {\n this.originaleTweet = originaleTweet;\n }\n}", "@Entity\n@Table(name = \"opentipbot_user\")\n/**\n * @author Gilles Cadignan\n */\npublic class OpenTipBotUser extends BaseEntity<Long>{\n\n @Id\n @GeneratedValue\n private Long id;\n\n private String email;\n private String displayName;\n private String userName;\n private String twitterIdentifier;\n private String coinAddress;\n private String profileImageUrl;\n private String profileUrl;\n\n @Basic(fetch = FetchType.LAZY)\n private byte[] coinAddressQRCode;\n\n @Transient\n private double balance;\n\n @Transient\n private double pendingBalance;\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public String getCoinAddress() {\n return coinAddress;\n }\n\n public void setCoinAddress(String coinAddress) {\n this.coinAddress = coinAddress;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public String getTwitterIdentifier() {\n return twitterIdentifier;\n }\n\n public void setTwitterIdentifier(String twitterIdentifier) {\n this.twitterIdentifier = twitterIdentifier;\n }\n\n public double getBalance() {\n return balance;\n }\n\n public void setBalance(double balance) {\n this.balance = balance;\n }\n\n public String getProfileImageUrl() {\n return profileImageUrl;\n }\n\n public void setProfileImageUrl(String profileImageUrl) {\n this.profileImageUrl = profileImageUrl;\n }\n\n public byte[] getCoinAddressQRCode() {\n return coinAddressQRCode;\n }\n\n public void setCoinAddressQRCode(byte[] coinAddressQRCode) {\n this.coinAddressQRCode = coinAddressQRCode;\n }\n\n public String getProfileUrl() {\n return profileUrl;\n }\n\n public void setProfileUrl(String profileUrl) {\n this.profileUrl = profileUrl;\n }\n\n public double getPendingBalance() {\n return pendingBalance;\n }\n\n public void setPendingBalance(double pendingBalance) {\n this.pendingBalance = pendingBalance;\n }\n}", "public interface OpenTipBotCommandRepository extends JpaRepository<OpenTipBotCommand, Long> {\n List<OpenTipBotCommand> findByTweetIdentifier(Long tweetIdentifier);\n\n List<OpenTipBotCommand> findByOpenTipBotCommandStatusAndOpenTipBotCommandEnumOrderByCreationTimeAsc(OpenTipBotCommandStatus status, OpenTipBotCommandEnum commandEnum);\n\n @Query(\"SELECT c from OpenTipBotCommand c WHERE c.fromUserName = :userName AND ( c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP\" +\n \" OR c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP_RAIN \" +\n \"OR c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP_RANDOM ) order by c.modificationTime desc\")\n List<OpenTipBotCommand> getTipsSent(@Param(\"userName\") String userName);\n\n\n @Query(\"SELECT c from OpenTipBotCommand c WHERE c.toUserName = :userName AND ( c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP\" +\n \" OR c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP_RAIN \" +\n \"OR c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP_RANDOM ) order by c.modificationTime desc\")\n List<OpenTipBotCommand> getTipsReceived(@Param(\"userName\") String userName);\n\n @Query(\"SELECT c from OpenTipBotCommand c WHERE c.fromUserName = :userName AND c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.WITHDRAW order by c.modificationTime desc\")\n List<OpenTipBotCommand> getWithDrawals(@Param(\"userName\") String userName);\n\n @Query(\"SELECT c from OpenTipBotCommand c WHERE c.opentipbotCommandStatus = opentipbot.persistence.model.OpenTipBotCommandStatus.PROCESSED AND (c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP\" +\n \" OR c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP_RAIN \" +\n \"OR c.opentipbotCommandEnum = opentipbot.persistence.model.OpenTipBotCommandEnum.TIP_RANDOM) order by c.modificationTime desc\")\n Page<OpenTipBotCommand> getLastTips(Pageable page);\n\n}", "public interface OpenTipBotUserRepository extends JpaRepository<OpenTipBotUser, Long> {\n OpenTipBotUser findByTwitterIdentifier(String twitterIdentifier);\n OpenTipBotUser findByUserName(String UserName);\n}", "public class OpenTipBotServiceException extends Exception {\n\n //the opentipbotCommand object which has generated this exception\n private OpenTipBotCommand command;\n\n /**\n * Build BitcoinServiceException with a message only\n * @param message\n */\n public OpenTipBotServiceException(String message) {\n super(message);\n }\n\n /**\n * Build BitcoinServiceException with message and cause\n * @param message\n * @param cause\n */\n public OpenTipBotServiceException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Build BitcoinServiceException with message and specific BitcoinServiceException fields\n * @param message\n * @param command\n */\n public OpenTipBotServiceException(String message, OpenTipBotCommand command) {\n super(message);\n this.command = command;\n }\n\n /**\n * Build BitcoinServiceException with message, cause and specific BitcoinServiceException fields\n * @param message\n * @param cause\n * @param command\n */\n public OpenTipBotServiceException(String message, Throwable cause, OpenTipBotCommand command) {\n super(message, cause);\n this.command = command;\n }\n\n // Getters and setters\n //********************\n\n\n public OpenTipBotCommand getCommand() {\n return command;\n }\n\n public void setCommand(OpenTipBotCommand command) {\n this.command = command;\n }\n}" ]
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.social.twitter.api.impl.TwitterTemplate; import org.springframework.stereotype.Service; import opentipbot.persistence.model.OpenTipBotCommand; import opentipbot.persistence.model.OpenTipBotUser; import opentipbot.persistence.repository.OpenTipBotCommandRepository; import opentipbot.persistence.repository.OpenTipBotUserRepository; import opentipbot.service.exception.OpenTipBotServiceException; import java.util.List;
package opentipbot.service; @Service public class OpenTipBotUserService { @Autowired private OpenTipBotUserRepository opentipbotUserRepository; @Autowired private OpenTipBotCommandRepository opentipbotCommandRepository; @Autowired private BitcoinService bitcoinService; @Autowired Environment env; @Autowired TwitterTemplate twitterTemplate; public OpenTipBotUser findByTwitterIdentifier(String twitterIndentifier){ return opentipbotUserRepository.findByTwitterIdentifier(twitterIndentifier); } public OpenTipBotUser findByUserName(String userName){ return opentipbotUserRepository.findByUserName(userName); }
public void createNewOpenTipBotUser(OpenTipBotUser opentipbotUser) throws OpenTipBotServiceException {
4
jansoren/akka-persistence-java-example
mymicroservice-server/src/main/java/no/jansoren/mymicroservice/MymicroserviceApplication.java
[ "public class EventStore {\n\n private static final Logger LOG = LoggerFactory.getLogger(EventStore.class);\n\n private ActorRef persistenceActor;\n private LeveldbReadJournal readJournal;\n private Map<Class<? extends Projection>, Projection> projections = new HashMap<>();\n\n public EventStore(MymicroserviceConfiguration configuration) {\n LOG.info(\"Initializing actor system for the event store\");\n ActorSystem actorSystem = ActorSystem.create(configuration.getActorSystemName());\n persistenceActor = actorSystem.actorOf(Props.create(MymicroservicePersistenceActor.class, configuration.getApplicationPersistenceId()), configuration.getPersistenceActorName());\n readJournal = PersistenceQuery.get(actorSystem).getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier());\n projections = initializeProjections();\n\n Source<EventEnvelope, NotUsed> source = readJournal.eventsByPersistenceId(configuration.getApplicationPersistenceId(), 0, Long.MAX_VALUE);\n source.runForeach(eventEnvelope -> {\n Event event = (Event) eventEnvelope.event();\n projections.forEach((projectionName, projection)->projection.handleEvent(event));\n }, ActorMaterializer.create(actorSystem));\n }\n\n public <T extends Projection> T getProjection(Class<T> projectionClass) {\n return (T)projections.get(projectionClass);\n\n }\n\n public ActorRef getPersistenceActor() {\n return persistenceActor;\n }\n\n public void tell(Object msg, ActorRef sender) {\n persistenceActor.tell(msg, sender);\n }\n\n public Object ask(Object msg) throws Exception {\n Future<Object> askEventStore = Patterns.ask(persistenceActor, msg, 3000);\n return Await.result(askEventStore, Duration.create(\"3 seconds\"));\n }\n\n private Map<Class<? extends Projection>, Projection> initializeProjections() {\n Map<Class<? extends Projection>, Projection> projections = new HashMap<>();\n projections.put(EventLogProjection.class, new EventLogProjection());\n projections.put(SomethingProjection.class, new SomethingProjection());\n projections.put(SomethingElseProjection.class, new SomethingElseProjection());\n return projections;\n }\n}", "public class ShutdownManager implements Managed {\n\n private static final Logger LOG = LoggerFactory.getLogger(ShutdownManager.class);\n\n private EventStore eventStore;\n\n public ShutdownManager(EventStore eventStore) {\n this.eventStore = eventStore;\n }\n\n @Override\n public void start() throws Exception {\n \n }\n\n @Override\n public void stop() throws Exception {\n LOG.info(\"Shutting down actor system for the event store\");\n eventStore.tell(new Shutdown(), null);\n }\n}", "public class ActorSystemHealthCheck extends HealthCheck {\n\n private EventStore eventStore;\n\n public ActorSystemHealthCheck(EventStore eventStore) {\n this.eventStore = eventStore;\n }\n\n @Override\n protected Result check() throws Exception {\n try {\n Object askIsRunning = eventStore.ask(new IsRunning());\n if(askIsRunning instanceof Yes) {\n return Result.healthy();\n }\n return Result.unhealthy(\"EventStore is not running properly. \" + askIsRunning);\n } catch (Exception e) {\n return Result.unhealthy(\"EventStore did not respond within 3 seconds. \" + e.getMessage());\n }\n }\n}", "public class ApplicationIsStartingCommand extends Command {\n\n}", "@Path(\"/monitoring\")\n@Produces(MediaType.APPLICATION_JSON)\npublic class MonitoringResource {\n\n private EventStore eventStore;\n\n public MonitoringResource(EventStore eventStore) {\n this.eventStore = eventStore;\n }\n\n @GET\n @Path(\"/eventlog\")\n public List<String> getEventLog() {\n EventLogProjection projection = eventStore.getProjection(EventLogProjection.class);\n List<String> eventLog = projection.getEventLog();\n return eventLog;\n }\n}", "@Path(\"/something\")\n@Produces(MediaType.APPLICATION_JSON)\npublic class SomethingResource {\n\n private EventStore eventStore;\n\n public SomethingResource(EventStore eventStore) {\n this.eventStore = eventStore;\n }\n\n @GET\n @Path(\"/do\")\n public Response doSomething() {\n eventStore.tell(new DoSomethingCommand(), null);\n return Response.ok().build();\n }\n\n @GET\n @Path(\"/get\")\n public Integer getSomething() {\n SomethingProjection projection = eventStore.getProjection(SomethingProjection.class);\n int somethingDoneCounter = projection.getSomethingDoneCounter();\n return somethingDoneCounter;\n }\n\n}", "@Path(\"/somethingelse\")\n@Produces(MediaType.APPLICATION_JSON)\npublic class SomethingElseResource {\n\n private EventStore eventStore;\n\n public SomethingElseResource(EventStore eventStore) {\n this.eventStore = eventStore;\n }\n\n @GET\n @Path(\"/do\")\n public Response doSomethingElse() {\n eventStore.tell(new DoSomethingElseCommand(), null);\n return Response.ok().build();\n }\n\n @GET\n @Path(\"/get\")\n public Integer getSomethingElse() {\n SomethingElseProjection projection = eventStore.getProjection(SomethingElseProjection.class);\n int somethingElseDoneCounter = projection.getSomethingElseDoneCounter();\n return somethingElseDoneCounter;\n }\n}" ]
import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import no.jansoren.mymicroservice.eventsourcing.EventStore; import no.jansoren.mymicroservice.eventsourcing.ShutdownManager; import no.jansoren.mymicroservice.health.ActorSystemHealthCheck; import no.jansoren.mymicroservice.monitoring.ApplicationIsStartingCommand; import no.jansoren.mymicroservice.monitoring.MonitoringResource; import no.jansoren.mymicroservice.something.SomethingResource; import no.jansoren.mymicroservice.somethingelse.SomethingElseResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package no.jansoren.mymicroservice; public class MymicroserviceApplication extends Application<MymicroserviceConfiguration> { private static final Logger LOG = LoggerFactory.getLogger(MymicroserviceApplication.class); public static final String APPLICATION_NAME = "Mymicroservice"; private EventStore eventStore; public static void main(final String[] args) throws Exception { new MymicroserviceApplication().run(args); } @Override public String getName() { return APPLICATION_NAME; } @Override public void initialize(final Bootstrap<MymicroserviceConfiguration> bootstrap) { } @Override public void run(final MymicroserviceConfiguration configuration, final Environment environment) { eventStore = new EventStore(configuration); environment.healthChecks().register("ActorSystemHealthCheck", new ActorSystemHealthCheck(eventStore)); environment.lifecycle().manage(new ShutdownManager(eventStore)); environment.jersey().register(new MymicroserviceResource(getName())); environment.jersey().register(new MonitoringResource(eventStore)); environment.jersey().register(new SomethingResource(eventStore)); environment.jersey().register(new SomethingElseResource(eventStore));
eventStore.tell(new ApplicationIsStartingCommand(), null);
3
dgrunwald/arden2bytecode
src/arden/tests/ActionTests.java
[ "public final class Compiler {\n\tprivate boolean isDebuggingEnabled = false;\n\tprivate String sourceFileName;\n\n\t/** Enables debugging for the code being produced. */\n\tpublic void enableDebugging(String sourceFileName) {\n\t\tthis.isDebuggingEnabled = true;\n\t\tthis.sourceFileName = sourceFileName;\n\t}\n\n\t/** Compiles a single MLM given in the input stream. */\n\tpublic CompiledMlm compileMlm(Reader input) throws CompilerException, IOException {\n\t\tList<CompiledMlm> output = compile(input);\n\t\tif (output.size() != 1)\n\t\t\tthrow new CompilerException(\"Expected only a single MLM per file\", 0, 0);\n\t\treturn output.get(0);\n\t}\n\n\t/** Compiles a list of MLMs given in the input stream. */\n\tpublic List<CompiledMlm> compile(Reader input) throws CompilerException, IOException {\n\t\tLexer lexer = new Lexer(new PushbackReader(input, 1024));\n\t\tParser parser = new Parser(lexer);\n\t\tStart syntaxTree;\n\t\ttry {\n\t\t\tsyntaxTree = parser.parse();\n\t\t} catch (ParserException e) {\n\t\t\tthrow new CompilerException(e);\n\t\t} catch (LexerException e) {\n\t\t\tthrow new CompilerException(e);\n\t\t}\n\t\treturn compile(syntaxTree);\n\t}\n\n\t/** Compiles a list of MLMs given in the syntax tree. */\n\tpublic List<CompiledMlm> compile(Start syntaxTree) throws CompilerException {\n\t\ttry {\n\t\t\tfinal ArrayList<CompiledMlm> output = new ArrayList<CompiledMlm>();\n\t\t\t// find all AMlm nodes and compile each individually\n\t\t\tsyntaxTree.apply(new DepthFirstAdapter() {\n\t\t\t\t@Override\n\t\t\t\tpublic void caseAMlm(AMlm node) {\n\t\t\t\t\toutput.add(doCompileMlm(node));\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn output;\n\t\t} catch (RuntimeCompilerException ex) {\n\t\t\tthrow new CompilerException(ex);\n\t\t}\n\t}\n\n\t/** Compiles a single MLMs given in the syntax tree. */\n\tpublic MedicalLogicModule compileMlm(AMlm mlm) throws CompilerException {\n\t\ttry {\n\t\t\treturn doCompileMlm(mlm);\n\t\t} catch (RuntimeCompilerException ex) {\n\t\t\tthrow new CompilerException(ex);\n\t\t}\n\t}\n\n\tprivate CompiledMlm doCompileMlm(AMlm mlm) {\n\t\tMetadataCompiler metadata = new MetadataCompiler();\n\t\tmlm.getMaintenanceCategory().apply(metadata);\n\t\tmlm.getLibraryCategory().apply(metadata);\n\n\t\tAKnowledgeCategory knowledgeCategory = (AKnowledgeCategory) mlm.getKnowledgeCategory();\n\t\tAKnowledgeBody knowledge = (AKnowledgeBody) knowledgeCategory.getKnowledgeBody();\n\t\tknowledge.getPrioritySlot().apply(metadata);\n\n\t\t// System.out.println(knowledge.toString());\n\t\t// knowledge.apply(new PrintTreeVisitor(System.out));\n\n\t\tCodeGenerator codeGen = new CodeGenerator(metadata.maintenance.getMlmName(), knowledgeCategory.getKnowledge()\n\t\t\t\t.getLine());\n\t\tif (isDebuggingEnabled)\n\t\t\tcodeGen.enableDebugging(sourceFileName);\n\n\t\tcompileData(codeGen, knowledge.getDataSlot());\n\t\tcompileLogic(codeGen, knowledge.getLogicSlot());\n\t\tcompileAction(codeGen, knowledge.getActionSlot());\n\t\tcompileUrgency(codeGen, knowledge.getUrgencySlot());\n\n\t\tbyte[] data;\n\t\ttry {\n\t\t\tByteArrayOutputStream bos = new ByteArrayOutputStream();\n\t\t\tDataOutputStream s = new DataOutputStream(bos);\n\t\t\tcodeGen.save(s);\n\t\t\ts.close();\n\t\t\tdata = bos.toByteArray();\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn new CompiledMlm(data, metadata.maintenance, metadata.library, metadata.priority);\n\t}\n\n\tprivate void compileData(CodeGenerator codeGen, PDataSlot dataSlot) {\n\t\tint lineNumber = ((ADataSlot) dataSlot).getDataColon().getLine();\n\t\tCompilerContext context = codeGen.createConstructor(lineNumber);\n\t\tdataSlot.apply(new DataCompiler(context));\n\t\tcontext.writer.returnFromProcedure();\n\t}\n\n\tprivate void compileLogic(CodeGenerator codeGen, PLogicSlot logicSlot) {\n\t\tCompilerContext context = codeGen.createLogic();\n\t\tlogicSlot.apply(new LogicCompiler(context));\n\t\t// CONCLUDE FALSE; is default\n\t\tcontext.writer.loadIntegerConstant(0);\n\t\tcontext.writer.returnIntFromFunction();\n\t}\n\n\tprivate void compileAction(CodeGenerator codeGen, PActionSlot actionSlot) {\n\t\tCompilerContext context = codeGen.createAction();\n\t\tif (actionSlot != null) {\n\t\t\tactionSlot.apply(new ActionCompiler(context));\n\t\t}\n\t\tcontext.writer.loadNull();\n\t\tcontext.writer.returnObjectFromFunction();\n\t}\n\n\tprivate void compileUrgency(CodeGenerator codeGen, PUrgencySlot urgencySlot) {\n\t\t// urgency_slot =\n\t\t// {empty}\n\t\t// | {urg} urgency urgency_val semicolons;\n\t\tif (urgencySlot instanceof AUrgUrgencySlot) {\n\t\t\tPUrgencyVal val = ((AUrgUrgencySlot) urgencySlot).getUrgencyVal();\n\t\t\tCompilerContext context = codeGen.createUrgency();\n\t\t\tcontext.writer.sequencePoint(((AUrgUrgencySlot) urgencySlot).getUrgency().getLine());\n\t\t\t// urgency_val =\n\t\t\t// {num} P.number\n\t\t\t// | {id} identifier;\n\t\t\tif (val instanceof ANumUrgencyVal) {\n\t\t\t\tcontext.writer.loadDoubleConstant(ParseHelpers\n\t\t\t\t\t\t.getLiteralDoubleValue(((ANumUrgencyVal) val).getNumberLiteral()));\n\t\t\t} else if (val instanceof AIdUrgencyVal) {\n\t\t\t\tTIdentifier ident = ((AIdUrgencyVal) val).getIdentifier();\n\t\t\t\tVariable var = codeGen.getVariableOrShowError(ident);\n\t\t\t\tif (var instanceof DataVariable) {\n\t\t\t\t\tvar.loadValue(context, ident);\n\t\t\t\t\tcontext.writer.invokeStatic(getRuntimeHelper(\"urgencyGetPrimitiveValue\", ArdenValue.class));\n\t\t\t\t} else {\n\t\t\t\t\tthrow new RuntimeCompilerException(ident, \"Urgency cannot use this type of variable.\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new RuntimeException(\"Unknown urgency value\");\n\t\t\t}\n\t\t\tcontext.writer.returnDoubleFromFunction();\n\t\t}\n\t}\n\n\tstatic Method getRuntimeHelper(String name, Class<?>... parameterTypes) {\n\t\ttry {\n\t\t\treturn RuntimeHelpers.class.getMethod(name, parameterTypes);\n\t\t} catch (SecurityException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t} catch (NoSuchMethodException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n}", "public class CompilerException extends Exception {\n\tprivate static final long serialVersionUID = -4674298085134149649L;\n\n\tprivate final int line, pos;\n\n\tpublic CompilerException(ParserException innerException) {\n\t\tsuper(innerException);\n\t\tif (innerException.getToken() != null) {\n\t\t\tthis.line = innerException.getToken().getLine();\n\t\t\tthis.pos = innerException.getToken().getPos();\n\t\t} else {\n\t\t\tthis.line = 0;\n\t\t\tthis.pos = 0;\n\t\t}\n\t}\n\n\tpublic CompilerException(LexerException innerException) {\n\t\tsuper(innerException);\n\t\tthis.line = 0;\n\t\tthis.pos = 0;\n\t}\n\n\tCompilerException(RuntimeCompilerException innerException) {\n\t\tsuper(innerException.getMessage(), innerException);\n\t\tthis.line = innerException.line;\n\t\tthis.pos = innerException.pos;\n\t}\n\n\tpublic CompilerException(String message, int pos, int line) {\n\t\tsuper(message);\n\t\tthis.line = line;\n\t\tthis.pos = pos;\n\t}\n\n\t/** Gets the line number where the compile error occurred. */\n\tpublic int getLine() {\n\t\treturn line;\n\t}\n\n\t/** Gets the line position (column) where the compile error occurred. */\n\tpublic int getPos() {\n\t\treturn pos;\n\t}\n}", "public interface ArdenRunnable {\n\t/**\n\t * Executes the MLM.\n\t * \n\t * @return Returns the value(s) provided by the \"return\" statement, or\n\t * (Java) null if no return statement was executed.\n\t */\n\tArdenValue[] run(ExecutionContext context, ArdenValue[] arguments) throws InvocationTargetException;\n}", "public final class ArdenString extends ArdenValue {\n\tpublic final String value;\n\n\tpublic ArdenString(String value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic ArdenString(String value, long primaryTime) {\n\t\tsuper(primaryTime);\n\t\tthis.value = value;\n\t}\n\n\t@Override\n\tpublic ArdenValue setTime(long newPrimaryTime) {\n\t\treturn new ArdenString(value, newPrimaryTime);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder b = new StringBuilder();\n\t\tb.append('\"');\n\t\tfor (int i = 0; i < value.length(); i++) {\n\t\t\tchar c = value.charAt(i);\n\t\t\tb.append(c);\n\t\t\tif (c == '\"')\n\t\t\t\tb.append('\"'); // double \"\n\t\t}\n\t\tb.append('\"');\n\t\treturn b.toString();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn (obj instanceof ArdenString) && value.equals(((ArdenString) obj).value);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn value.hashCode();\n\t}\n\n\t@Override\n\tpublic int compareTo(ArdenValue rhs) {\n\t\tif (rhs instanceof ArdenString) {\n\t\t\treturn Integer.signum(value.compareTo(((ArdenString) rhs).value));\n\t\t} else {\n\t\t\treturn Integer.MIN_VALUE;\n\t\t}\n\t}\n}", "public abstract class ArdenValue {\n\tpublic static final long NOPRIMARYTIME = Long.MIN_VALUE;\n\tpublic final long primaryTime;\n\n\tprotected ArdenValue() {\n\t\tthis.primaryTime = NOPRIMARYTIME;\n\t}\n\n\tprotected ArdenValue(long primaryTime) {\n\t\tthis.primaryTime = primaryTime;\n\t}\n\n\t/**\n\t * Creates a copy of this value with the primary time set to newPrimaryTime.\n\t */\n\tpublic abstract ArdenValue setTime(long newPrimaryTime);\n\n\t/**\n\t * Returns whether this value is 'true' in a boolean context. Returns 'true'\n\t * for boolean true; false for everything else (even for the list \",true\")\n\t */\n\tpublic boolean isTrue() {\n\t\treturn false;\n\t}\n\n\t/**\n\t * Returns whether this value is 'false' in a boolean context. Returns\n\t * 'true' for boolean false; returns 'false' for everything else (boolean\n\t * true or null)\n\t */\n\tpublic boolean isFalse() {\n\t\treturn false;\n\t}\n\n\t/** Gets the elements that a FOR loop will iterate through */\n\tpublic ArdenValue[] getElements() {\n\t\treturn new ArdenValue[] { this };\n\t}\n\n\t/**\n\t * Compares this ArdenValue with another. Does not implement Comparable\n\t * interface because we have an additional return value MIN_VALUE with\n\t * special meaning.\n\t * \n\t * @return Returns Integer.MIN_VALUE if the types don't match or the type is\n\t * not ordered. Returns -1 if this is less than rhs. Returns 0 if\n\t * this is equal to rhs. Returns 1 if this is larger than rhs.\n\t */\n\tpublic int compareTo(ArdenValue rhs) {\n\t\treturn Integer.MIN_VALUE;\n\t}\n}", "public class ExecutionContext {\n\t/**\n\t * Creates a database query using a mapping clause. The DatabaseQuery object\n\t * can be used to limit the number of results produced.\n\t * \n\t * @param mapping\n\t * The contents of the mapping clause (=text between { and }).\n\t * The meaning is implementation-defined. The Arden language\n\t * specification uses mapping clauses like\n\t * \"medication_cancellation where class = gentamicin\".\n\t * \n\t * @return This method may not return Java null. Instead, it can return\n\t * DatabaseQuery.NULL, a query that will always produce an empty\n\t * result set.\n\t */\n\tpublic DatabaseQuery createQuery(String mapping) {\n\t\treturn DatabaseQuery.NULL;\n\t}\n\n\t/** Gets a value represents the message of a MESSAGE variable. */\n\tpublic ArdenValue getMessage(String mapping) {\n\t\treturn new ArdenString(mapping);\n\t}\n\n\t/**\n\t * Called by write statements.\n\t * \n\t * @param message\n\t * The message to be written.\n\t * @param destination\n\t * The mapping clause describing the message destination.\n\t */\n\tpublic void write(ArdenValue message, String destination) {\n\t}\n\n\t/**\n\t * Retrieves another MLM.\n\t * \n\t * @param name\n\t * The name of the requested MLM.\n\t * @param institution\n\t * The institution of the requested MLM.\n\t * @return The requested MLM.\n\t */\n\tpublic ArdenRunnable findModule(String name, String institution) {\n\t\tthrow new RuntimeException(\"findModule not implemented\");\n\t}\n\n\t/**\n\t * Retrieves an interface implementation.\n\t * \n\t * @param mapping\n\t * The mapping clause of the interface.\n\t * @return The interface implementation.\n\t */\n\tpublic ArdenRunnable findInterface(String mapping) {\n\t\tthrow new RuntimeException(\"findInterface not implemented\");\n\t}\n\n\t/**\n\t * Calls another MLM using a delay.\n\t * \n\t * @param mlm\n\t * The MLM that should be called. This will be an instance\n\t * returned from findModule() or findInterface().\n\t * @param arguments\n\t * The arguments being passed. Can be null if no arguments were\n\t * specified.\n\t * @param delay\n\t * The delay for calling the MLM (as ArdenDuration).\n\t */\n\tpublic void callWithDelay(ArdenRunnable mlm, ArdenValue[] arguments, ArdenValue delay) {\n\t\tthrow new RuntimeException(\"callWithDelay not implemented\");\n\t}\n\n\tprivate ArdenTime eventtime = new ArdenTime(new Date());\n\n\t/** Gets the eventtime. */\n\tpublic ArdenTime getEventTime() {\n\t\treturn eventtime;\n\t}\n\n\t/** Gets the triggertime. */\n\tpublic ArdenTime getTriggerTime() {\n\t\treturn eventtime;\n\t}\n\n\t/** Gets the current time. */\n\tpublic ArdenTime getCurrentTime() {\n\t\treturn new ArdenTime(new Date());\n\t}\n}", "public interface MedicalLogicModule extends ArdenRunnable {\n\t/** Creates a new instance of the implementation class. */\n\tMedicalLogicModuleImplementation createInstance(ExecutionContext context, ArdenValue[] arguments)\n\t\t\tthrows InvocationTargetException;\n\n\t/** Gets the mlmname */\n\tString getName();\n\n\t/** Gets the maintenance metadata */\n\tMaintenanceMetadata getMaintenance();\n\n\t/** Gets the library metadata */\n\tLibraryMetadata getLibrary();\n\n\t/** Gets the priority of this module. */\n\tdouble getPriority();\n}" ]
import java.io.InputStreamReader; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import arden.compiler.Compiler; import arden.compiler.CompilerException; import arden.runtime.ArdenRunnable; import arden.runtime.ArdenString; import arden.runtime.ArdenValue; import arden.runtime.ExecutionContext; import arden.runtime.MedicalLogicModule; import org.junit.Assert; import org.junit.Test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream;
// arden2bytecode // Copyright (c) 2010, Daniel Grunwald // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // - Neither the name of the owner nor the names of its contributors may be used to // endorse or promote products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER // IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package arden.tests; public class ActionTests { private static String inputStreamToString(InputStream in) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append("\n"); } bufferedReader.close(); return stringBuilder.toString(); } public static MedicalLogicModule parseTemplate(String dataCode, String logicCode, String actionCode) throws CompilerException { try { InputStream s = ActionTests.class.getResourceAsStream("ActionTemplate.mlm"); String fullCode = inputStreamToString(s).replace("$ACTION", actionCode).replace("$DATA", dataCode).replace( "$LOGIC", logicCode);
Compiler c = new Compiler();
0
dariober/ASCIIGenome
src/main/java/tracks/TrackSeqRegex.java
[ "public class InvalidColourException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class InvalidGenomicCoordsException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class InvalidRecordException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}", "public class GenomicCoords implements Cloneable {\n\t\n\tpublic static final String SPACER= \"-\"; // Background character as spacer\n\tpublic static final String TICKED= \"*\"; // Char to use to mark region\n\t\n\tprivate String chrom;\n\tprivate Integer from;\n\tprivate Integer to;\n\tprivate SAMSequenceDictionary samSeqDict; // Can be null\n\t/** Size of the screen window \n\t * Only user getUserWindowSize() to access it after init at constructor.\n\t */\n\tprivate String fastaFile= null;\n\tprivate String samSeqDictSource= null; // Source of the sequence dictionary. Can be path to file of fasta, bam, genome. Or genome tag e.g. hg19. \n\tprivate byte[] refSeq= null;\n\tpublic boolean isSingleBaseResolution= false;\n\tprivate int terminalWidth;\n\tprivate List<Double> mapping;\n\t\n\t/* Constructors */\n\tpublic GenomicCoords(String region, int terminalWidth, SAMSequenceDictionary samSeqDict, String fastaFile, boolean verbose) throws InvalidGenomicCoordsException, IOException{\n\t\t\n\t\tthis.setTerminalWidth(terminalWidth);\n\t\t\n\t\tGenomicCoords xgc= parseStringToGenomicCoords(region);\n\n\t\tthis.chrom= xgc.getChrom();\n\t\tthis.from= xgc.getFrom();\n\t\tthis.to= xgc.getTo();\n\t\t\n\t\tif(from == null){ \n\t\t\tfrom= 1; \n\t\t}\n\t\t\n\t\tif(to == null){ \n\t\t\tto= from + this.getTerminalWidth() - 1;\n\t\t}\n\t\t\n\t\t// Check valid input\n\t\tif(chrom == null || (to != null && from == null) || (from > to) || from < 1 || to < 1){\n\t\t\tSystem.err.println(\"Got: \" + chrom + \":\" + from + \"-\" + to);\n\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\tthrow e;\n\t\t}\n\t\tif(samSeqDict != null && samSeqDict.size() > 0){ // If dict is present, check against it\n\t\t\tif(samSeqDict.getSequence(chrom) == null){\n\t\t\t\tif(verbose){\n\t\t\t\t\tSystem.err.println(\"\\nCannot find chromosome '\" + chrom + \"' in sequence dictionary.\");\n\t\t\t\t}\n\t\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tthis.samSeqDict= samSeqDict;\n\t\tif(this.samSeqDict != null && this.samSeqDict.size() > 0){\n\t\t\tcorrectCoordsAgainstSeqDict(samSeqDict);\n\t\t}\n\t\tif(fastaFile != null){\n\t\t\tthis.setSamSeqDictFromFasta(fastaFile);\n\t\t\tthis.setFastaFile(fastaFile);\n\t\t}\n\t\t\n\t\tthis.update();\n\t}\n\t\n\tpublic GenomicCoords(String region, int terminalWidth, SAMSequenceDictionary samSeqDict, String fastaFile) throws InvalidGenomicCoordsException, IOException{\n\t\tthis(region, terminalWidth, samSeqDict, fastaFile, true);\n\t}\n\t\n\tGenomicCoords(int terminalWidth) throws InvalidGenomicCoordsException, IOException{ \n\t\tthis.terminalWidth= terminalWidth;\n\t};\n\n\t/**Update a bunch of fields when coordinates change*/\n\tprivate void update() throws InvalidGenomicCoordsException, IOException {\n\t\t// this.setTerminalWindowSize();\n\t\tthis.setSingleBaseResolution(); // True if one text character corresponds to 1 bp\n\t\tthis.setRefSeq();\n\t\tthis.mapping= this.seqFromToLenOut(this.getTerminalWidth());\n\t}\n\t\n\t/* Methods */\n\t\n\t/** Set genome dictionary and fasta file ref if available. See \n\t * GenomicCoords.getSamSeqDictFromAnyFile() for available inputs.\n\t * @param includeGenomeFile: Should the input data be treated as a genome file?\n\t * Set to true only if the input can be a genome file. Other files (bed, vcf, gff) \n\t * look like valid genome file and this can result in wring dictionary. \n\t * */\n\tpublic void setGenome(List<String> input, boolean includeGenomeFile) throws IOException {\n\t\t\n\t\tList<String> cleanList= new ArrayList<String>(); \n\t\tfor(String x : input){\n\t\t\tif(x != null && ! x.trim().isEmpty()){\n\t\t\t\tcleanList.add(Utils.tildeToHomeDir(x));\n\t\t\t}\n\t\t}\t\t\n\t\tif(cleanList.size() == 0){\n\t\t\treturn;\n\t\t}\t\t\n\n\t\t// Set Dictionary\n\t\tthis.setSamSeqDictFromAnySource(cleanList, includeGenomeFile);\n\t\t// Try to set fasta sequence\n\t\tfor(String x : cleanList){\n\t\t\tboolean done= true;\n\t\t\ttry{\n\t\t\t\tif(new File(x + \".fai\").exists()){\n\t\t\t\t\tthis.setFastaFile(x);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new FileNotFoundException();\n\t\t\t\t}\n\t\t\t} catch(FileNotFoundException e){\n\t\t\t\ttry {\n\t\t\t\t\tnew Faidx(new File(x));\n\t\t\t\t\t(new File(x + \".fai\")).deleteOnExit();\n\t\t\t\t\tthis.setFastaFile(x);\n\t\t\t\t} catch (Exception e1) {\n\t\t\t\t\tdone= false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(done){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprotected void setRefSeq() throws IOException, InvalidGenomicCoordsException{\n\t\tif(this.fastaFile == null || ! this.isSingleBaseResolution){\n\t\t\tthis.refSeq= null;\n\t\t\treturn;\n\t\t}\n\t\tthis.refSeq= this.getSequenceFromFasta();\n\t}\n\t\n\tpublic byte[] getRefSeq() throws IOException, InvalidGenomicCoordsException {\n\t\tif(this.refSeq == null){\n\t\t\tthis.setRefSeq();\n\t\t}\n\t\treturn this.refSeq;\n\t}\n\t\n\t\n\tpublic byte[] getSequenceFromFasta() throws IOException{\n\t\tIndexedFastaSequenceFile faSeqFile = null;\n\t\ttry {\n\t\t\tfaSeqFile = new IndexedFastaSequenceFile(new File(this.fastaFile));\n\t\t\ttry{\n\t\t\t\tbyte[] seq= faSeqFile.getSubsequenceAt(this.chrom, this.from, this.to).getBases();\n\t\t\t\tfaSeqFile.close();\n\t\t\t\treturn seq;\n\t\t\t} catch (NullPointerException e){\n\t\t\t\tSystem.err.println(\"Cannot fetch sequence \" + this.chrom + \":\" + this.from + \"-\" + this.to +\n\t\t\t\t\t\t\" for fasta file \" + this.fastaFile);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tfaSeqFile.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\t\n\t}\n\t\n\t/**\n\t * Parse string to return coordinates. This method simply populates the fields chrom, from, to by \n\t * parsing the input string. \n\t * This object can't be used as such as there is no check for valid input. It should be used only by the constructor.\n\t * @return\n\t * @throws InvalidGenomicCoordsException \n\t * @throws IOException \n\t */\n\tprivate GenomicCoords parseStringToGenomicCoords(String x) throws InvalidGenomicCoordsException, IOException{\n\n\t\tInteger from= 1; // Default start/end coords.\n\t\tInteger to= this.getTerminalWidth();\n\t\t\n\t\tGenomicCoords xgc= new GenomicCoords(this.getTerminalWidth());\n\t\t\n\t\tif(x == null || x.isEmpty()){\n\t\t\tx= \"Undefined_contig\";\n\t\t}\n\t\t\n\t\tx= x.trim();\n\t\t\n\t\tString[] region= new String[3];\n\t\tif(x.contains(\" \")) {\n\t\t\t// Format chrom[ from [to]]\n\t\t\tregion= this.parseStringSpaceSep(x);\n\t\t} else {\n\t\t\t// Format chrom[:from[-to]]\n\t\t\tregion= this.parseStringColonSep(x);\n\t\t} \n\t\txgc.chrom= region[0];\n\t\t\n\t\tif(region[1] == null && region[2] == null) {\n\t\t\t// Only chrom present. It will not handle well chrom names containing ':'\n\t\t\txgc.from= from;\n\t\t\txgc.to= to;\n\t\t\tif(xgc.samSeqDict != null && xgc.to > samSeqDict.getSequence(xgc.chrom).getSequenceLength()){\n\t\t\t\txgc.to= samSeqDict.getSequence(xgc.chrom).getSequenceLength(); \n\t\t\t}\n\t\t} \n\t\telse if(region[2] == null) {\n\t\t\t// Only chrom and start given\n\t\t\txgc.from= Integer.parseInt(region[1]);\n\t\t\txgc.to= xgc.from + this.getTerminalWidth() - 1;\n\t\t} \n\t\telse {\n\t\t\t// chrom, start and end given\n\t\t\txgc.from= Integer.parseInt(region[1]);\n\t\t\txgc.to= Integer.parseInt(region[2]);\n\t\t}\n\t\treturn xgc;\n\n\t}\n\t\n\tprivate String[] parseStringSpaceSep(String x) throws InvalidGenomicCoordsException {\n\t\tString[] region= new String[3];\n\t\tList<String> reg = new ArrayList<String>();\n\t\tList<String> xreg= Splitter.on(\" \").omitEmptyStrings().trimResults().splitToList(x);\n\t\treg.add(xreg.get(0));\n\t\tfor(int i= 1; i < xreg.size(); i++) {\n\t\t\tif(xreg.get(i).equals(\"-\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tList<String> pos= Splitter.on(\"-\").omitEmptyStrings().trimResults().splitToList(xreg.get(i));\n\t\t\tfor(String p : pos) {\n\t\t\t\treg.add(p.replaceAll(\",\", \"\"));\n\t\t\t}\n\t\t}\n\n\t\tregion[0]= reg.get(0);\n\t\tif(reg.size() == 1) {\n\t\t\treturn region;\n\t\t}\n\t\tif(reg.size() == 2) {\n\t\t\tregion[1]= reg.get(1);\n\t\t} \n\t\telse if(reg.size() > 2) {\n\t\t\tregion[1]= reg.get(1);\n\t\t\tregion[2]= reg.get(reg.size()-1);\n\t\t} else {\n\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\tSystem.err.println(\"\\nUnexpected format for region \" + x + \"\\n\");\n\t\t\te.printStackTrace();\n\t\t\tthrow e;\n\t\t}\n\t\treturn region;\n\t}\n\n\tprivate String[] parseStringColonSep(String x) throws InvalidGenomicCoordsException {\n\n\t\tString[] region= new String[3];\n\t\t\n\t\tint nsep= StringUtils.countMatches(x, \":\");\n\t\tif(nsep == 0){\n\t\t\tregion[0]= x;\n\t\t} else {\n\t\t\tregion[0]= StringUtils.substringBeforeLast(x, \":\").trim();\n\t\t\t\n\t\t\t// Strip chromosome name, remove commas from integers.\n\t\t\tString fromTo= StringUtils.substringAfterLast(x, \":\").replaceAll(\",\", \"\").trim();\n\t\t\tnsep= StringUtils.countMatches(fromTo, \"-\");\n\t\t\tif(nsep == 0){ // Only start position given\n\t\t\t\tregion[1]= StringUtils.substringBefore(fromTo, \"-\").trim();\n\t\t\t} else if(nsep == 1){ // From and To positions given.\n\t\t\t\tregion[1]= StringUtils.substringBefore(fromTo, \"-\").trim();\n\t\t\t\tregion[2]= StringUtils.substringAfter(fromTo, \"-\").trim();\n\t\t\t} else {\n\t\t\t\tInvalidGenomicCoordsException e = new InvalidGenomicCoordsException();\n\t\t\t\tSystem.err.println(\"\\nUnexpected format for region \" + x + \"\\n\");\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\treturn region;\n\t}\n\t\n\tpublic void correctCoordsAgainstSeqDict(SAMSequenceDictionary samSeqDict) throws InvalidGenomicCoordsException, IOException{\n\n\t\tif(samSeqDict == null || samSeqDict.size() == 0){\n\t\t\t// Just check start pos\n\t\t\tif (this.from <=0 ){\n\t\t\t\tthis.from= 1;\n\t\t\t}\t\t\t\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif(this.chrom == null){ // Nothing to do\n\t\t\treturn;\n\t\t}\n\t\tif(samSeqDict.getSequence(this.chrom) == null){ // Not found: Nullify everything\n\t\t\tthis.chrom= null;\n\t\t\tthis.from= null;\n\t\t\tthis.to= null;\n\t\t\treturn;\n\t\t} \n\t\t// Reset min coords\n\t\tif( this.from != null && this.from < 1) {\n\t\t\tthis.from= 1;\n\t\t}\n\t\t// Reset max coords\n\t\tif( this.from != null && this.from > samSeqDict.getSequence(this.chrom).getSequenceLength() ) {\n\t\t\tthis.from= samSeqDict.getSequence(this.chrom).getSequenceLength() - this.getGenomicWindowSize() + 1;\n\t\t\tif(this.from <= 0){\n\t\t\t\tthis.from= 1;\n\t\t\t}\n\t\t\tthis.to= this.from + this.getGenomicWindowSize() - 1;\n\t\t\tif(this.to > samSeqDict.getSequence(this.chrom).getSequenceLength()){\n\t\t\t\tthis.to= samSeqDict.getSequence(this.chrom).getSequenceLength();\n\t\t\t}\n\t\t}\n\t\tif( this.to != null && this.to > samSeqDict.getSequence(this.chrom).getSequenceLength() ) {\t\t\t\n\t\t\tthis.to= samSeqDict.getSequence(this.chrom).getSequenceLength();\n\t\t}\n\t}\n\t\n\tpublic String toString(){\n\t\tint range= this.to - this.from + 1;\n\t\treturn this.chrom + \":\" + this.from + \"-\" + this.to + \"; \" + NumberFormat.getNumberInstance(Locale.UK).format(range) + \" bp\";\n\t}\n\t\n\t/** Return current position in the form chrom:start-end */\n\tpublic String toStringRegion(){\n\t\treturn this.getChrom() + \":\" + this.getFrom() + \"-\" + this.getTo();\n\t}\n\n\t/** Get midpoint of genomic interval \n\t * */\n\tprivate int getMidpoint(){\n\t\tint range= this.to - this.from + 1;\n\t\tif(range % 2 == 1){\n\t\t\trange--;\n\t\t}\n\t\tint midpoint= range / 2 + this.from;\n\t\treturn midpoint;\n\t}\n\t\n\t/**\n\t * Rescale coords to extend them as in zooming-in/-out\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\tpublic void zoomOut() throws IOException, InvalidGenomicCoordsException{\n\t\t// If window size is 1 you need to extend it otherwise zoom will have no effect!\n\t\tif((this.to - this.from) == 0){\n\t\t\tif((this.from - 1) > 0){\n\t\t\t\t// Try to extend left by 1 bp:\n\t\t\t\tthis.from -= 1;\n\t\t\t} else {\n\t\t\t\t// Else extend right\n\t\t\t\tthis.to += 1; // But what if you have a chrom of 1bp?!\n\t\t\t}\n\t\t}\n\t\t\n\t\tint zoom= 1;\n\t\t// * Get size of window (to - from + 1)\n\t\tint range= this.to - this.from + 1;\n\t\tif(range % 2 == 1){\n\t\t\trange--;\n\t\t}\n\t\tint midpoint= this.getMidpoint();\n\n\t\t// Extend midpoint right\t\t\n\t\tlong zoomTo= midpoint + ((long)range * (long)zoom);\n\t\t\n\t\tif(zoomTo >= Integer.MAX_VALUE){\n\t\t\tSystem.err.println(\"Invalid 'to' coordinate to fetch \" + zoomTo + \" (integer overflow?)\");\n\t\t\tzoomTo= Integer.MAX_VALUE;\n\t\t}\n\t\tthis.to= (int)zoomTo;\n\t\t\n\t\t// * Extend midpoint left by window size x2 and check coords\n\t\tthis.from= midpoint - (range * zoom);\n\t\tthis.from= (this.from <= 0) ? 1 : this.from; \n\t\tif(this.samSeqDict != null && this.samSeqDict.size() > 0){\n\t\t\tif(this.samSeqDict.getSequence(this.chrom).getSequenceLength() > 0){\n\t\t\t\tthis.to= (this.to > this.samSeqDict.getSequence(this.chrom).getSequenceLength()) ? \n\t\t\t\t\t\tthis.samSeqDict.getSequence(this.chrom).getSequenceLength() : this.to;\n\t\t\t}\n\t\t}\n\t\tthis.update();\n\t}\n\n\t/**\n\t * Zoom into range. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\tpublic void zoomIn() throws IOException, InvalidGenomicCoordsException{\n\t\tfloat zoom= (float) (1/4.0);\n\t\t// * Get size of window (to - from + 1)\n\t\tint range= this.to - this.from + 1;\n\t\tif(range % 2 == 1){\n\t\t\trange--;\n\t\t}\n\t\t// * Get midpoint of range\n\t\tint midpoint= this.getMidpoint();\n\t\tint extendBy= (int) Math.rint(range * zoom);\n\t\tint newFrom= midpoint - extendBy;\n\t\tint newTo= midpoint + extendBy;\n\t\tif((newTo - newFrom + 1) < this.getUserWindowSize()){ // Reset new coords to be at least windowSize in span\n\t\t\tint diff= this.getUserWindowSize() - (newTo - newFrom + 1);\n\t\t\tif(diff % 2 == 0){\n\t\t\t\tnewFrom -= diff/2;\n\t\t\t\tnewTo += diff/2;\n\t\t\t} else {\n\t\t\t\tnewFrom -= diff/2+1;\n\t\t\t\tnewTo += diff/2;\n\t\t\t}\n\t\t\t// Check new coords are no larger then starting values\n\t\t\tnewFrom= (newFrom < this.from) ? this.from : newFrom;\n\t\t\tnewTo= (newTo > this.to) ? this.to : newTo;\n\t\t}\n\t\tthis.from= newFrom;\n\t\tthis.to= newTo;\n\t\tif(this.from > this.to){ // Not sure this can happen.\n\t\t\tthis.to= this.from;\n\t\t}\n\t\tthis.update();\n\t}\n\t\n\t/** Move coordinates to the left hand side of the current window\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tpublic void left() throws InvalidGenomicCoordsException, IOException{\n\t\tint w= this.getUserWindowSize();\n\t\tthis.to= this.getMidpoint();\n\t\tif((this.to - this.from) < w){\n\t\t\tthis.to += (w - (this.to - this.from) - 1); \n\t\t}\n\t\tthis.update();\n\t}\n\t\n\t/** Move coordinates to the right hand side of the current window\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tpublic void right() throws InvalidGenomicCoordsException, IOException{\n\t\tint w= this.getUserWindowSize();\n\t\tthis.from= this.getMidpoint();\n\t\tif((this.to - this.from) < w){\n\t\t\tthis.from -= (w - (this.to - this.from) - 1); \n\t\t}\n\t\tthis.update();\n\t}\n\t\n\t/**\n\t * Same as R seq(from to, length.out). See also func in Utils\n\t * @return\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\t//private List<Double> seqFromToLenOut() throws InvalidGenomicCoordsException, IOException {\n\t//\treturn seqFromToLenOut(this.getUserWindowSize());\n\t//}\n\t\n\t/**\n\t * Same as R seq(from to, length.out). See also func in Utils\n\t * @return\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t */\n\tprivate List<Double> seqFromToLenOut(int size) throws InvalidGenomicCoordsException, IOException {\n\t\t\n\t\tif(this.getFrom() == null || this.getTo() == null){\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tList<Double> mapping= new ArrayList<Double>();\n\t\t\n\t\tif(this.from < 1 || this.from > this.to){\n\t\t\tSystem.err.println(\"Invalid genome coordinates: from \" + this.from + \" to \" + this.to);\n\t\t\ttry {\n\t\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t\t} catch (InvalidGenomicCoordsException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\tSystem.exit(1);\n\t\t\t}\n\t\t}\n\t\tint span= this.to - this.from + 1;\n\t\t// If the genomic span is less then screen size, reduce screen size to.\n\t\t// If genomic span == screenSize then you have a mapping one to one.\n\t\tif(span <= size){ \n\t\t\tfor(int i= this.from; i <= this.to; i++){\n\t\t\t\tmapping.add((double)i);\n\t\t\t}\n\t\t\treturn mapping;\n\t\t}\n\t\t\n\t\tdouble step= ((double)span - 1)/(size - 1);\n\t\tmapping.add((double)this.from);\n\t\tfor(int i= 1; i < size; i++){\n\t\t\tmapping.add((double)mapping.get(i-1)+step);\n\t\t}\n\t\t\n\t\t// First check last point is close enough to expectation. If so, replace last point with\n\t\t// exact desired.\n\t\tdouble diffTo= Math.abs(mapping.get(mapping.size() - 1) - this.to);\n\t\tif(diffTo > ((float)this.to * 0.001)){\n\t\t\tSystem.err.println(\"Error generating sequence:\");\n\t\t\tSystem.err.println(\"Last point: \" + mapping.get(mapping.size() - 1));\n\t\t\tSystem.err.println(\"To diff: \" + diffTo);\n\t\t\tSystem.err.println(\"Step: \" + step);\n\t\t} else {\n\t\t\tmapping.set(mapping.size()-1, (double)this.to);\n\t\t}\n\t\t\n\t\tdouble diffFrom= Math.abs(mapping.get(0) - this.from);\t\t\n\t\tif(diffFrom > 0.01 || mapping.size() != size){\n\t\t\tSystem.err.println(\"Error generating sequence:\");\n\t\t\tSystem.err.println(\"Expected size: \" + size + \"; Effective: \" + mapping.size());\n\t\t\tSystem.err.println(\"From diff: \" + diffFrom);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\treturn mapping;\n\t}\t\n\t\n\t/**Take of care you are working with double precision here. Do not use this method to \n\t * for exact calculations. \n\t * */\n\tpublic double getBpPerScreenColumn() throws InvalidGenomicCoordsException, IOException{\n\t\tList<Double> mapping = seqFromToLenOut(this.getUserWindowSize());\n\t\tdouble bpPerScreenColumn= (to - from + 1) / (double)mapping.size();\n\t\treturn bpPerScreenColumn;\n\t}\n\t\n\t/**\n\t * Produce a string representation of the current position on the chromosome\n\t * @param nDist: Distance between labels \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * @throws InvalidColourException \n\t * */\n\tpublic String getChromIdeogram(int nDist, boolean noFormat) throws InvalidGenomicCoordsException, IOException, InvalidColourException {\n\t\t\n\t\tif(this.samSeqDict == null || this.samSeqDict.size() == 0){\n\t\t\treturn null;\n\t\t}\n\t\tList<Double> positionMap = null;\n\t\ttry{\n\t\t\tpositionMap = Utils.seqFromToLenOut(1, this.samSeqDict.getSequence(this.chrom).getSequenceLength(), \n\t\t\t\t\tthis.getUserWindowSize());\n\t\t} catch (NullPointerException e){\n\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t}\n\t\t// This code taken from printableRuler() above.\n\t\tString numberLine= \"\";\n \tint prevLen= 0;\n \tint j= 0;\n\t\twhile(j < positionMap.size()){\n\t\t\tint num= (int)Math.rint(Utils.roundToSignificantFigures(positionMap.get(j), 2));\n\t\t\tString posMark= Utils.parseIntToMetricSuffix(num); // String.valueOf(num);\n\t\t\tif(j == 0){\n\t\t\t\tnumberLine= posMark;\n\t\t\t\tj += posMark.length();\n\t\t\t} else if((numberLine.length() - prevLen) >= nDist){\n\t\t\t\tprevLen= numberLine.length();\n\t\t\t\tnumberLine= numberLine + posMark;\n\t\t\t\tj += posMark.length();\n\t\t\t} else {\n\t\t\t\tnumberLine= numberLine + SPACER;\n\t\t\t\tj++;\n\t\t\t}\n\t\t}\n\t\tList<String> map= new ArrayList<String>();\n\t\tfor(int i= 0; i < numberLine.length(); i++){\n\t\t\tmap.add(numberLine.charAt(i) +\"\");\n\t\t}\n\t\t\n\t\t// ------------------\n\t\t\n\t\tint fromTextPos= Utils.getIndexOfclosestValue(this.from, positionMap);\n\t\tint toTextPos= Utils.getIndexOfclosestValue(this.to, positionMap);\n\n\t\tboolean isFirst= true;\n\t\tint lastTick= -1;\n\t\tfor(int i= fromTextPos; i <= toTextPos; i++){\n\t\t\tif(isFirst || map.get(i).equals(SPACER)){\n\t\t\t\tmap.set(i, TICKED);\n\t\t\t\tisFirst= false;\n\t\t\t}\n\t\t\tlastTick= i;\n\t\t}\n\t\tmap.set(lastTick, TICKED);\n\t\tString ideogram= StringUtils.join(map, \"\");\n\t\tif(ideogram.length() > this.getUserWindowSize()){\n\t\t\tideogram= ideogram.substring(0, this.getUserWindowSize());\n\t\t}\n\t\tif(!noFormat){\n\t\t\tideogram= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \";38;5;\" + Config.get256Color(ConfigKey.chrom_ideogram) + \"m\" + ideogram;\n\t\t}\n\t\treturn ideogram;\n\t}\n\t\n\t/** For debugging only \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic String toStringVerbose(int windowSize) throws InvalidGenomicCoordsException, IOException{\n\t\tList<Double> mapping = seqFromToLenOut(this.getUserWindowSize());\n\t\tString str= \"Genome coords: \" + from + \"-\" + to \n\t\t\t\t+ \"; screen width: \" + mapping.size()\n\t\t\t\t+ \"; scale: \" + this.getBpPerScreenColumn() + \" bp/column\" \n\t\t\t\t+ \"; Mapping: \" + mapping;\n\t\tstr += \"\\n\";\n\t\tstr += this.toString();\n\t\treturn str;\n\t}\n\t\n\tpublic String printableGenomicRuler(int markDist, boolean noFormat) throws InvalidGenomicCoordsException, IOException, InvalidColourException{\n\t\tList<Double> mapping = this.seqFromToLenOut(this.getUserWindowSize());\n\t\tString numberLine= this.printRulerFromList(mapping, markDist, 0);\n\t\tnumberLine= numberLine.replaceFirst(\"^0 \", \"1 \"); // Force to start from 1\n\t\tnumberLine= numberLine.substring(0, this.getUserWindowSize());\n\t\tif(!noFormat){\n\t\t\tnumberLine= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \n\t\t\t\t\t\";38;5;\" + Config.get256Color(ConfigKey.ruler) +\n\t\t\t\t\t\"m\" + numberLine;\n\t\t}\n \treturn numberLine;\n }\n\n\tpublic String printablePercentRuler(int markDist, boolean noFormat) throws InvalidGenomicCoordsException, IOException, InvalidColourException{\n\t\t// List<Double> mapping = Utils.seqFromToLenOut(1, this.getUserWindowSize(), this.getUserWindowSize());\n\t\tList<Double> mapping = Utils.seqFromToLenOut(0, 1, this.getUserWindowSize());\n\t\tString numberLine= this.printRulerFromList(mapping, markDist, 2);\n\t\tnumberLine= numberLine.substring(0, this.getUserWindowSize());\n\t\tif(!noFormat){\n\t\t\tnumberLine= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \n\t\t\t\t\t\";38;5;\" + Config.get256Color(ConfigKey.ruler) +\n\t\t\t\t\t\"m\" + numberLine;\n\t\t}\n \treturn numberLine;\n }\n\t\t\n\tprivate String printRulerFromList(List<Double> marks, int markDist, int digits) throws InvalidGenomicCoordsException, IOException {\n\t\tint prevLen= 0;\n \tint i= 0;\n \t// First round numbers and see if we can round digits\n \tList<String>rMarks= new ArrayList<String>();\n \tmarkLoop:\n \tfor(int sfx : new int[]{1000000, 100000, 10000, 1000, 100, 10, 5, 1}){\n \t\trMarks.clear();\n\t \tfor(Double mark : marks){\n\t \t\tdouble n = Utils.round(mark/sfx, digits) * sfx;\n\t \t\tString str= String.format(\"%.\" + digits + \"f\", n);\n\t \t\tstr= str.replaceAll(\"^0\\\\.00\", \"0\"); // Strip leading zero if any.\n\t \t\tstr= str.replaceAll(\"^0\\\\.\", \".\"); \n\t \t\tstr= str.replaceAll(\"\\\\.00$\", \"\"); // Change x.00 to x. E.g. 1.00 -> 1\n\t \t\trMarks.add(str);\n\t \t}\n\t \tSet<String> uniq= new HashSet<String>(rMarks);\n\t \tif(uniq.size() == marks.size()){\n\t \t\t// No duplicates after rounding\n\t \t\tbreak markLoop;\n\t \t}\n \t}\n\n \tStringBuilder numberLine= new StringBuilder();\n\t\twhile(i < rMarks.size()){\n\t\t\tString label= rMarks.get(i);\n\t\t\t\n\t\t\tif(label.length() >= markDist){\n\t\t\t\t// Increase markDist if the number is bigger than the space itself\n\t\t\t\tmarkDist= label.length() + 1;\n\t\t\t}\n\t\t\tif(i == 0){\n\t\t\t\tnumberLine.append(label);\n\t\t\t\ti += label.length();\n\t\t\t} else if((numberLine.length() - prevLen) >= markDist){\n\t\t\t\tprevLen= numberLine.length();\n\t\t\t\tnumberLine.append(label);\n\t\t\t\ti += label.length();\n\t\t\t} else {\n\t\t\t\tnumberLine.append(\" \");\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\treturn numberLine.toString();\n\t}\n\t\n\t/** Ref sequence usable for print on screen. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * @throws InvalidColourException */\n\tpublic String printableRefSeq(boolean noFormat) throws IOException, InvalidGenomicCoordsException, InvalidColourException{\n\n\t\tbyte[] refSeq= this.getRefSeq();\n\t\tif(refSeq == null){\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tif(noFormat){\n\t\t\treturn new String(refSeq) + \"\\n\";\n\t\t} else {\n\t\t\tString faSeqStr= \"\";\n\t\t\tfor(byte c : refSeq){\n\t\t\t\t// For colour scheme see http://www.umass.edu/molvis/tutorials/dna/atgc.htm\n\t\t\t\tchar base= (char) c;\n\t\t\t\tString prefix= \"\\033[48;5;\" + Config.get256Color(ConfigKey.background) + \";38;5;\";\n\t\t\t\tif(base == 'A' || base == 'a'){\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_a) + \"m\" + base;\n\t\t\t\t} else if(base == 'C' || base == 'c') {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_c) + \"m\" + base;\n\t\t\t\t} else if(base == 'G' || base == 'g') {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_g) + \"m\" + base;\n\t\t\t\t} else if(base == 'T' || base == 't') {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_t) + \"m\" + base;\n\t\t\t\t} else {\n\t\t\t\t\tfaSeqStr += prefix + Config.get256Color(ConfigKey.seq_other) + \"m\" + base;\n\t\t\t\t} \n\t\t\t}\n\t\t\treturn faSeqStr + \"\\n\";\n\t\t}\n\t}\n\n\t/**\n\t * Get a SAMSequenceDictionary by querying the input files, if there is any bam, or from the indexed fasta file or from genome files.\n\t * @param testfiles List of input files\n\t * @param fasta Reference sequence\n\t * @param genome \n\t * @return\n\t * @throws IOException \n\t */\n\tprivate boolean setSamSeqDictFromAnySource(List<String> testfiles, boolean includeGenomeFile) throws IOException{\n\n\t\tboolean isSet= false;\n\t\tfor(String testfile : testfiles){ // Get sequence dict from bam, if any\t\t\t\t\n\t\t\ttry{\n\t\t\t\tisSet= this.setSamSeqDictFromBam(testfile);\n\t\t\t\tif(isSet){\n\t\t\t\t\treturn isSet;\n\t\t\t\t}\n\t\t\t} catch(Exception e){\n\t\t\t\t//\n\t\t\t}\n\t\t\ttry{\n\t\t\t\tisSet= this.setSamSeqDictFromFasta(testfile);\n\t\t\t\tif(isSet){\n\t\t\t\t\treturn isSet;\n\t\t\t\t}\n\t\t\t} catch(Exception e){\n\t\t\t\t//\n\t\t\t}\n\t\t\tif(includeGenomeFile){\n\t\t\t\ttry{\n\t\t\t\t\tisSet= this.setSamSeqDictFromGenomeFile(testfile);\n\t\t\t\t\tif(isSet){\n\t\t\t\t\t\treturn isSet;\n\t\t\t\t\t}\n\t\t\t\t} catch(Exception e){\n\t\t\t\t\t//\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// If we still haven't found a sequence dict, try looking for a VCF file.\n\t\tfor(String testfile : testfiles){ \n\t\t\ttry{\n\t\t\t\tisSet= this.setSamSeqDictFromVCF(testfile);\n\t\t\t\tif(isSet){\n\t\t\t\t\treturn isSet;\n\t\t\t\t}\n\t\t\t} catch(Exception e){\n\t\t\t\t//\n\t\t\t}\n\t\t}\n\t\treturn isSet;\n\t}\n\n\tprivate boolean setSamSeqDictFromVCF(String vcf) throws MalformedURLException {\n\n\t\tSAMSequenceDictionary samSeqDict= Utils.getVCFHeader(vcf).getSequenceDictionary();\n\t\tif(samSeqDict != null){\n\t\t\tthis.setSamSeqDictSource(new File(vcf).getAbsolutePath());\n\t\t\tthis.setSamSeqDict(samSeqDict);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\n\t}\n\n\t\n\tprivate boolean setSamSeqDictFromFasta(String fasta) throws IOException{\n\t\t\n\t\t// IndexedFastaSequenceFile fa= null;\n\t\t\n\t\ttry{\n\t\t\tif(new File(fasta + \".fai\").exists() && ! new File(fasta + \".fai\").isDirectory()){\n\t\t\t\t//\n\t\t\t} else {\n\t\t\t\tthrow new FileNotFoundException(); \n\t\t\t}\n\t\t\t// fa= new IndexedFastaSequenceFile(new File(fasta));\n\t\t} catch(FileNotFoundException e){\n\t\t\ttry {\n\t\t\t\tnew Faidx(new File(fasta));\n\t\t\t\t(new File(fasta + \".fai\")).deleteOnExit();\n\t\t\t} catch (Exception e1) {\n\t\t\t\t//\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\tBufferedReader br= new BufferedReader(new FileReader(new File(fasta + \".fai\")));\n\t\tSAMSequenceDictionary seqDict= new SAMSequenceDictionary(); // null;\n\t\twhile(true){\n\t\t\tString line= br.readLine();\n\t\t\tif(line == null){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tSAMSequenceRecord ssqRec= new SAMSequenceRecord(\n\t\t\t\t\tline.split(\"\\t\")[0], \n\t\t\t\t\tInteger.parseInt(line.split(\"\\t\")[1]));\n\t\t\tseqDict.addSequence(ssqRec);\n\t\t}\n\t\tbr.close();\n//\t\t\tfa.close();\n\t\tthis.setSamSeqDictSource(new File(fasta).getAbsolutePath());\n\t\tthis.setSamSeqDict(seqDict);\n\t\treturn true;\n//\t\t}\n//\t\tfa.close();\n//\t\treturn false;\n\t}\n\t\n\tprivate boolean setSamSeqDictFromBam(String bamfile) {\n\n\t\t/* ------------------------------------------------------ */\n\t\t/* This chunk prepares SamReader from local bam */\n\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\tSamReader samReader;\n\t\tsamReader= srf.open(new File(bamfile));\n\t\t/* ------------------------------------------------------ */\n\t\t\n\t\tSAMSequenceDictionary seqDict = samReader.getFileHeader().getSequenceDictionary();\n\t\tif(seqDict != null && !seqDict.isEmpty()){\n\t\t\tthis.setSamSeqDictSource(new File(bamfile).getAbsolutePath());\n\t\t\tthis.setSamSeqDict(seqDict);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/** Get SamSequenceDictionary either from local file or from built-in resources.\n\t * If reading from resources, \"genome\" is the tag before '.genome'. E.g. \n\t * 'hg19' will read file hg19.genome \n\t * */\n\tprivate boolean setSamSeqDictFromGenomeFile(String genome) throws IOException {\n\n\t\tSAMSequenceDictionary samSeqDict= new SAMSequenceDictionary();\n\n\t\tBufferedReader reader=null;\n\t\ttry{\n\t\t\t// Attempt to read from resource\n\t\t\tInputStream res= Main.class.getResourceAsStream(\"/genomes/\" + genome + \".genome\");\n\t\t\treader= new BufferedReader(new InputStreamReader(res));\n\t\t} catch (NullPointerException e){\n\t\t\ttry{\n\t\t\t\t// Read from local file\n\t\t\t\treader= new BufferedReader(new FileReader(new File(genome)));\n\t\t\t} catch (FileNotFoundException ex){\n\t\t\t\treturn false; \n\t\t\t}\n\t\t}\n\t\t\n\t\tString line = null;\n\t\twhile ((line = reader.readLine()) != null) {\n\t\t\tif(line.trim().isEmpty() || line.trim().startsWith(\"#\")){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] chromLine= line.split(\"\\t\");\n\t\t\tSAMSequenceRecord sequenceRecord = new SAMSequenceRecord(chromLine[0], Integer.parseInt(chromLine[1]));\n\t\t\tsamSeqDict.addSequence(sequenceRecord);\n\t\t}\n\t\treader.close();\n\t\tthis.setSamSeqDictSource(genome);\n\t\tthis.setSamSeqDict(samSeqDict);\n\t\treturn true;\n\t}\n\n\tpublic boolean equalCoords(GenomicCoords other){\n\t\treturn this.chrom.equals(other.chrom) && this.from.equals(other.from) && this.to.equals(other.to); \n\t}\n\t\n\t/** True if all fileds in this object equla those in the other\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic boolean equalCoordsAndWindowSize(GenomicCoords other) throws InvalidGenomicCoordsException, IOException{\n\t\treturn this.equalCoords(other) && \n\t\t\t\tthis.getUserWindowSize() == other.getUserWindowSize();\n\t}\n\t\n\tpublic Object clone() {\n\t//shallow copy\n\t\ttry {\n\t\t\treturn super.clone();\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic void centerAndExtendGenomicCoords(GenomicCoords gc, int size, double slop) throws InvalidGenomicCoordsException, IOException {\n\t\t\n\t\tif(size <= 0){\n\t\t\tSystem.err.println(\"Invalid feature size. Must be > 0, got \" + size);\n\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t}\n\n\t\tif(slop > 0){\n\t\t\tdouble center= (size/2.0) + gc.getFrom();\n\t\t\tgc.from= (int)Math.rint(center - (size * slop));\n\t\t\tgc.to= (int)Math.rint(center + (size * slop));\n\t\t}\n\t\tif(slop == 0){\n\t\t\t// Decrease gc.from so that the start of the feature is in the middle of the screen\n\t\t\tint newFrom= gc.from - this.getTerminalWidth() / 2;\n\t\t\tnewFrom= newFrom < 1 ? 1 : newFrom;\n\t\t\tint newTo= newFrom + this.getTerminalWidth() - 1;\n\t\t\tgc.from= newFrom;\n\t\t\tgc.to= newTo;\n\t\t}\n\t\tif(((gc.to - gc.from)+1) < gc.getUserWindowSize()){\n\t\t\tint span= (gc.to - gc.from);\n\t\t\tint extendBy= (int)Math.rint((gc.getUserWindowSize() / 2.0) - (span / 2.0));\n\t\t\tgc.from -= extendBy;\n\t\t\tgc.to += extendBy;\n\t\t}\n\t\tgc.correctCoordsAgainstSeqDict(samSeqDict);\n\t\tthis.update();\n\t}\n\n\t/** Reset window size according to current terminal screen. \n\t * If the user reshapes the terminal window size or the font size, \n\t * detect the new size and add it to the history. \n\t * */\n\tprivate int getTerminalWidth() {\n\t\treturn this.terminalWidth;\n\t}\t\n\t\n\t/* Getters and setters */\n\n\tpublic List<Double> getMapping() {\n\t\treturn this.mapping;\n\t}\n\t\n\t/** Map using this.getUserWindowSize() as window size. Consider using \n\t * getMapping(int size) to avoid computing the terminal width for each call. */\n\t//public List<Double> getMapping() throws InvalidGenomicCoordsException, IOException {\n\t//\treturn seqFromToLenOut(this.getUserWindowSize());\n\t//}\t\n\t\n\tpublic String getChrom() {\n\t\treturn chrom;\n\t}\n\n\tpublic Integer getFrom() {\n\t\treturn from;\n\t}\n\n\tpublic Integer getTo() {\n\t\treturn to;\n\t}\n\t\n\t/** Width of the terminal screen window in number of characters. \n\t * Not to be confused with the genomic window size (as in bp) \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic int getUserWindowSize() throws InvalidGenomicCoordsException, IOException{\n\n\t\tint userWindowSize= this.getTerminalWidth();\n\t\tif(userWindowSize > this.getGenomicWindowSize()){\n\t\t\treturn this.getGenomicWindowSize();\n\t\t} else {\n\t\t\treturn userWindowSize;\n\t\t}\n\t}\n\t\n\t/** Size of genomic interval. Can be smaller than windowSize set by user. \n\t * Not to be confused with userWindowSize. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException */\n\tpublic Integer getGenomicWindowSize() throws InvalidGenomicCoordsException {\n\t\tif(this.getTo() == null || this.getFrom() == null){\n\t\t\treturn null;\n\t\t}\n\t\treturn this.to - this.from + 1;\n\t}\n\n\tpublic SAMSequenceDictionary getSamSeqDict(){\n\t\treturn this.samSeqDict;\n\t}\n\t\n\tpublic void setSamSeqDict(SAMSequenceDictionary samSeqDict){\n\t\tthis.samSeqDict= samSeqDict;\n\t}\n\t\n\tpublic String getFastaFile(){\n\t\treturn this.fastaFile;\n\t}\n\n\tprotected void setFastaFile(String fastaFile) {\n\t\tthis.fastaFile = fastaFile;\n\t}\n\n\tpublic String getSamSeqDictSource() {\n\t\tif(this.getFastaFile() != null){\n\t\t\treturn this.getFastaFile();\n\t\t}\n\t\treturn samSeqDictSource;\n\t}\n\n\tpublic void setSamSeqDictSource(String samSeqDictSource) {\n\t\tthis.samSeqDictSource = samSeqDictSource;\n\t}\n\n\t/** Extend genomic coordinates left and right by given bases. \n\t * refpoint= \"mid\": The new coordinates are given by the midpoint of the current one +/- left and right.\n\t * refpoint= \"window\": The new coordinates are the given by the current window extended left and right. \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tprivate void extend(int left, int right, String refpoint) throws InvalidGenomicCoordsException, IOException {\n\t\tint newFrom= 0;\n\t\tint newTo= 0;\n\t\tif(refpoint.equals(\"mid\")){\n\t\t\tint mid= this.getMidpoint();\n\t\t\tnewFrom= mid - left;\n\t\t\tnewTo= mid + right - 1; // -1 so the window size becomes exactly right-left\n\t\t}\n\t\tif(refpoint.equals(\"window\")){\n\t\t\tnewFrom= this.getFrom() - left;\n\t\t\tnewTo= this.getTo() + right;\n\t\t}\n\t\tif(newFrom > newTo){\n\t\t\tint tmp= newFrom;\n\t\t\tnewFrom= newTo;\n\t\t\tnewTo= tmp;\n\t\t}\n\t\tthis.from= newFrom;\n\t\tthis.to= newTo;\n\t\tthis.correctCoordsAgainstSeqDict(this.getSamSeqDict());\n\t\tthis.update();\n\t}\n\t\n\t/** Apply this.extend() after having parsed cmd line args. \n\t * @throws InvalidCommandLineException \n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tpublic void cmdInputExtend(List<String> cmdInput) throws InvalidCommandLineException, InvalidGenomicCoordsException, IOException{\n\t\tList<String> args= new ArrayList<String>(cmdInput);\n\t\targs.remove(0); // Remove cmd name\n\t\t\n\t\tString refpoint= \"window\";\n\t\tif(args.contains(\"window\")){\n\t\t\targs.remove(\"window\");\n\t\t}\n\t\tif(args.contains(\"mid\")){\n\t\t\trefpoint= \"mid\";\n\t\t\targs.remove(\"mid\");\n\t\t} \n\t\tif(args.size() == 0){\n\t\t\tthrow new InvalidCommandLineException();\n\t\t}\n\t\tint left= Integer.parseInt(args.get(0));\n\t\tint right= left;\n\t\tif(args.size() > 1){\n\t\t\tright= Integer.parseInt(args.get(1));\n\t\t}\n\t\tthis.extend(left, right, refpoint);\n\t}\n\n\tpublic void setTerminalWidth(int terminalWidth) throws InvalidGenomicCoordsException, IOException {\n\t\tthis.terminalWidth= terminalWidth;\n\t\tthis.update();\n\t}\n\n\tprotected void setSingleBaseResolution() throws InvalidGenomicCoordsException, IOException {\n\t\tif(this.getGenomicWindowSize() == null){\n\t\t\tthis.isSingleBaseResolution= false;\n\t\t\treturn;\n\t\t}\n\t\tif(this.getUserWindowSize() == this.getGenomicWindowSize()){\n\t\t\tthis.isSingleBaseResolution= true;\n\t\t} else {\n\t\t\tthis.isSingleBaseResolution= false;\n\t\t}\t\t\n\t}\n\n}", "public class Utils {\n\t\n\tpublic static double round(double value, int places) {\n\t if (places < 0) throw new IllegalArgumentException();\n\t \n\t BigDecimal bd = new BigDecimal(Double.toString(value));\n\t bd = bd.setScale(places, RoundingMode.HALF_EVEN);\n\t return bd.doubleValue();\n\t}\n\t\n\t/**Create temp file in the current working directory or in the system's\n\t * tmp dir if failing to create in cwd.*/\n\tpublic static File createTempFile(String prefix, String suffix, boolean deleteOnExit){\n\t\tFile tmp = null;\n\t\ttry{\n\t\t\ttmp= File.createTempFile(prefix, suffix, new File(System.getProperty(\"user.dir\")));\n\t\t} catch(IOException e){\n\t\t\ttry {\n\t\t\t\ttmp= File.createTempFile(prefix, suffix);\n\t\t\t} catch (IOException e1) {\n\t\t\t\te1.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tif(deleteOnExit) {\n\t\t\ttmp.deleteOnExit();\t\n\t\t}\n\t\treturn tmp;\n\t}\n\t\n\t/**Return a buffered reader which iterate through the file or URL. Input may be\n\t * compressed. \n\t * */\n\tpublic static BufferedReader reader(String fileOrUrl) throws MalformedURLException, IOException{\n\t\t\n\t\tBufferedReader br= null;\n\t\tInputStream gzipStream= null;\n\t\tUrlValidator urlValidator = new UrlValidator();\n\t\tif(fileOrUrl.endsWith(\".gz\") || fileOrUrl.endsWith(\".bgz\")){\n\t\t\tif(urlValidator.isValid(fileOrUrl)) {\n\t\t\t\tgzipStream = new GZIPInputStream(new URL(fileOrUrl).openStream());\n\t\t\t} else {\n\t\t\t\tgzipStream = new GZIPInputStream(new FileInputStream(fileOrUrl));\n\t\t\t}\n\t\t\tReader decoder = new InputStreamReader(gzipStream, \"UTF-8\");\n\t\t\tbr = new BufferedReader(decoder);\n\t\t} else if(urlValidator.isValid(fileOrUrl)) {\n\t\t\tInputStream instream= new URL(fileOrUrl).openStream();\n\t\t\tReader decoder = new InputStreamReader(instream, \"UTF-8\");\n\t\t\tbr = new BufferedReader(decoder);\n\t\t} else {\n\t\t\tbr = new BufferedReader(new FileReader(fileOrUrl));\n\t\t}\n\t\treturn br;\n\t}\n\t\n\t/**Extract template name from sam record read name. I.e. remove\n\t * everything after first backspace and possible /1 /2 suffixes.\n\t * Avoid using replaceAll() for this as it is much slower. \n\t * */\n\tpublic static String templateNameFromSamReadName(String readName){\n\t\tif(readName.contains(\" \")){\n\t\t\treadName= readName.substring(0, readName.indexOf(\" \"));\n\t\t}\n\t\tif(readName.endsWith(\"/1\") || readName.endsWith(\"/2\")){\n\t\t\treadName= readName.substring(0, readName.length() - 2);\n\t\t}\n\t\treturn readName;\n\t}\n\t\n\t/** Returns true of the list of arguments argList contains the given flag\n\t * IMPORTANT SIDE EFFECT: If found, the argument flag is removed from the list. \n\t * */\n\tpublic static boolean argListContainsFlag(List<String> argList, String flag){\n\t\tboolean hasFlag= false;\n\t\tif(argList.contains(flag)){\n\t\t\targList.remove(flag);\n\t\t\thasFlag= true;\n\t\t}\n\t\treturn hasFlag;\n\t}\n\n\t/** Check if the list of arguments contains \"param\" and if so return nargs argument after it. \n\t * Returns null if arglist does not contain the parameter.\n\t * IMPORTANT SIDE EFFECT: If found, the parameter and its arguments are removed from input list. \n\t * @throws InvalidCommandLineException \n\t * */\n\tpublic static List<String> getNArgsForParam(List<String> argList, String param, int nargs) throws InvalidCommandLineException {\n\t\tif(nargs < 1){\n\t\t\tSystem.err.println(\"narg must be >= 1. Got \" + nargs);\n\t\t\tthrow new InvalidCommandLineException(); \n\t\t}\n//\t\tList<String> args= new ArrayList<String>();\n\t\t\n\t\tint idx= argList.indexOf(param);\n\t\tif(idx == -1){\n\t\t\treturn null;\n\t\t}\n\t\tif(idx == (argList.size() - 1)){\n\t\t\t// If param is the last item in the list you cannot get its argument!\n\t\t\tthrow new InvalidCommandLineException();\n\t\t}\n\t\tif(idx+1+nargs > argList.size()){\n\t\t\tSystem.err.println(\"Not enough arguments passed to parameter \" + param);\n\t\t\tthrow new InvalidCommandLineException();\n\t\t}\n\t\t\n\t\tList<String> args= new ArrayList<String>();\n\t\tfor(int i= idx+1; i < idx+1+nargs; i++){\n\t\t\t// Do not use List.subList() because you get a view of the input, not a copy.\n\t\t\targs.add(argList.get(i));\n\t\t}\n\t\t// Remove param and args from list\n\t\targList.remove(idx);\n\t\twhile(nargs > 0){\n\t\t\targList.remove(idx);\n\t\t\tnargs--;\n\t\t}\n\t\treturn args;\n\t}\n\n\t\n\t/** Check if the list of arguments contains \"param\" and if so return the argument. \n\t * Returns null if arglist does not contain the parameter\n\t * IMPORTANT SIDE EFFECT: If found, the parameter and its argument are removed from argList. \n\t * @throws InvalidCommandLineException \n\t * */\n\tpublic static String getArgForParam(List<String> argList, String param, String defArg) throws InvalidCommandLineException{\n\t\t\n\t\tint idx= argList.indexOf(param);\n\t\tif(idx == -1){\n\t\t\treturn defArg;\n\t\t}\n\t\tif(idx == (argList.size() - 1)){\n\t\t\t// If param is the last item in the list you cannot get its argument!\n\t\t\tthrow new InvalidCommandLineException();\n\t\t}\n\t\tString arg= argList.get(idx+1);\n\t\t\n\t\t// Remove param and arg\n\t\targList.remove(idx);\n\t\targList.remove(idx);\n\t\t\n\t\treturn arg;\n\n\t}\n\n\tpublic static void checkFasta(String fasta, int debug) throws IOException, UnindexableFastaFileException {\n\t\tif(fasta == null){\n\t\t\treturn;\n\t\t}\n\t\tFile fafile= new File(fasta);\n\t\tif(!fafile.isFile()){\n\t\t\tSystem.err.println(\"Fasta file '\" + fasta + \"' not found.\");\n\t\t\tif(debug == 0 || debug == 1){\n\t\t\t\tSystem.exit(1);\n\t\t\t} else if (debug == 2){\n\t\t\t\tthrow new IOException();\n\t\t\t}\n\t\t} \n\t\tif(!fafile.canRead()){\n\t\t\tSystem.err.println(\"Fasta file '\" + fasta + \"' is not readable.\");\n\t\t\tif(debug == 0 || debug == 1){\n\t\t\t\tSystem.exit(1);\n\t\t\t} else if (debug == 2){\n\t\t\t\tthrow new IOException();\n\t\t\t}\n\t\t}\n\t\t\n\t\tIndexedFastaSequenceFile faSeqFile = null;\n\t\ttry {\n\t\t\tfaSeqFile= new IndexedFastaSequenceFile(fafile);\n\t\t\tfaSeqFile.close();\n\t\t} catch (FileNotFoundException e) {\n\t\t\tSystem.err.println(\"\\nIndexing '\" + fasta + \"'.\");\n\t\t\tnew Faidx(new File(fasta));\n\t\t\t(new File(fasta + \".fai\")).deleteOnExit();\n\t\t}\n\t}\n\t\n public static long getAlignedReadCount(String bam) throws IOException{\n\n\t\t/* ------------------------------------------------------ */\n\t\t/* This chunk prepares SamReader from local bam or URL bam */\n\t\tUrlValidator urlValidator = new UrlValidator();\n\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\tSamReader samReader;\n\t\tif(urlValidator.isValid(bam)){\n\t\t\tsamReader = SamReaderFactory.makeDefault().open(\n\t\t\t\t\tSamInputResource.of(new URL(bam)).index(new URL(bam + \".bai\"))\n\t\t\t);\n\t\t} else {\n\t\t\tsamReader= srf.open(new File(bam));\n\t\t}\n\t\t/* ------------------------------------------------------ */\n\n\t\tList<SAMSequenceRecord> sequences = samReader.getFileHeader().getSequenceDictionary().getSequences();\n\t\tlong alnCount= 0;\n\t\tfor(SAMSequenceRecord x : sequences){\n\t\t\talnCount += samReader.indexing().getIndex().getMetaData(x.getSequenceIndex()).getAlignedRecordCount();\n\t\t}\n\t\tsamReader.close();\n\t\treturn alnCount;\n }\n\n\t/** Merge overlapping features. If screenCoords is true, merge is based on the screen coordinates. Otherwise use\n\t * genomic coordinates. \n\t * @throws InvalidColourException \n\t * */\n\tpublic static List<IntervalFeature> mergeIntervalFeatures(List<IntervalFeature> intervalList, boolean screenCoords) throws InvalidGenomicCoordsException, InvalidColourException{\n\t\tList<IntervalFeature> mergedList= new ArrayList<IntervalFeature>();\t\t \n\t\tif(intervalList.size() == 0){\n\t\t\treturn mergedList;\n\t\t}\n\t\t\n\t\tString mergedChrom = null;\n\t\tint mergedFrom= -1;\n\t\tint mergedTo= -1;\n\t\tint mergedScreenFrom= -1;\n\t\tint mergedScreenTo= -1;\n\t\tint numMrgIntv= 1; // Number of intervals in the merged one. \n\t\tSet<Character> strand= new HashSet<Character>(); // Put here all the different strands found in the merged features.\t\t\n\n\t\tfor(int i= 0; i < (intervalList.size()+1); i++){\n\t\t\t// We do an additional loop to add to the mergedList the last interval.\n\t\t\t// The last loop has interval == null so below you need to account for it\n\t\t\tIntervalFeature interval= null;\n\t\t\tif(i < intervalList.size()){\n\t\t\t\tinterval= intervalList.get(i); \n\t\t\t}\n\t\t\t\n\t\t\tif(mergedFrom < 0){ // Init interval\n\t\t\t\tmergedChrom= interval.getChrom(); \n\t\t\t\tmergedFrom= interval.getFrom();\n\t\t\t\tmergedTo= interval.getTo();\n\t\t\t\tmergedScreenFrom= interval.getScreenFrom();\n\t\t\t\tmergedScreenTo= interval.getScreenTo();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Sanity check: The list to be merged is on the same chrom and sorted by start pos.\n\t\t\tif(i < intervalList.size() && (!mergedChrom.equals(interval.getChrom()) || mergedFrom > interval.getFrom() || mergedFrom > mergedTo)){\n\t\t\t\tSystem.err.println(mergedChrom + \" \" + mergedFrom + \" \" + mergedTo);\n\t\t\t\tthrow new RuntimeException();\n\t\t\t} \n\t\t\t\n\t\t\tboolean overlap= false; \n\t\t\tif( screenCoords && i < intervalList.size() && (mergedScreenFrom <= interval.getScreenTo() && mergedScreenTo >= (interval.getScreenFrom()-1)) ){ \n\t\t\t\t// Overlap: Extend <to> coordinate. See also http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap\n\t\t\t\toverlap= true;\n\t\t\t} else if(i < intervalList.size() && (mergedFrom <= interval.getTo() && mergedTo >= (interval.getFrom()-1) )){ \n\t\t\t\t// Overlap on genomic coordinates\n\t\t\t\toverlap= true;\n\t\t\t}\n\t\t\tif(overlap){ // Overlap found in screen or genomic coords. \n\t\t\t mergedTo= Math.max(interval.getTo(), mergedTo);\n\t\t\t mergedScreenTo= Math.max(interval.getScreenTo(), mergedScreenTo);\n\t\t\t\tstrand.add(interval.getStrand());\n\t\t\t\tnumMrgIntv++;\n\t\t\t\toverlap= false;\n\t\t\t} \n\t\t\telse {\n\t\t\t\t// No overlap add merged interval to list and reset new merged interval\n\t\t\t\tIntervalFeature x= new IntervalFeature(mergedChrom + \"\\t\" + (mergedFrom-1) + \"\\t\" + mergedTo, TrackFormat.BED, null);\n\t\t\t\tx.setScreenFrom(mergedScreenFrom);\n\t\t\t\tx.setScreenTo(mergedScreenTo);\n\t\t\t\tif(strand.size() == 1){\n\t\t\t\t\tx.setStrand(strand.iterator().next());\n\t\t\t\t} \n\t\t\t\tstrand.clear();\n\n\t\t\t\tif(x.equals(intervalList.get(i-1)) && numMrgIntv == 1){\n\t\t\t\t\tmergedList.add(intervalList.get(i-1));\n\t\t\t\t} else {\n\t\t\t\t\tmergedList.add(x);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(i < intervalList.size()){\n\t\t\t\t\t// Do not reset from/to if you are in extra loop.\n\t\t\t\t\tmergedFrom= interval.getFrom();\n\t\t\t\t\tmergedTo= interval.getTo();\n\t\t\t\t\tmergedScreenFrom= interval.getScreenFrom();\n\t\t\t\t\tmergedScreenTo= interval.getScreenTo();\n\t\t\t\t\tstrand.add(interval.getStrand());\n\t\t\t\t\tnumMrgIntv= 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor(IntervalFeature x : mergedList){\n\t\t\tx.getIdeogram(true, true);\n\t\t}\n\t\treturn mergedList;\n\t}\n\t\n//\tpublic static LinkedHashMap<String, Integer> xterm256ColorCodes(){\n//\t\t// See http://misc.flogisoft.com/bash/tip_colors_and_formatting\n//\t\t// From http://jonasjacek.github.io/colors/\n//\t\tLinkedHashMap<String, Integer> colourCodes= new LinkedHashMap<String, Integer>();\n//\t\tcolourCodes.put(\"default\", 39);\n//\t\tcolourCodes.put(\"black\", 30);\n//\t\tcolourCodes.put(\"red\", 31);\n//\t\tcolourCodes.put(\"green\", 32);\n//\t\tcolourCodes.put(\"yellow\", 33);\n//\t\tcolourCodes.put(\"blue\", 34);\n//\t\tcolourCodes.put(\"magenta\", 35);\n//\t\tcolourCodes.put(\"cyan\", 36);\n//\t\tcolourCodes.put(\"light_grey\", 37);\n//\t\tcolourCodes.put(\"grey\", 90);\n//\t\tcolourCodes.put(\"light_red\", 91);\n//\t\tcolourCodes.put(\"light_green\", 92);\n//\t\tcolourCodes.put(\"light_yellow\", 93);\n//\t\tcolourCodes.put(\"light_blue\", 94);\n//\t\tcolourCodes.put(\"light_magenta\", 95);\n//\t\tcolourCodes.put(\"light_cyan\", 96);\n//\t\tcolourCodes.put(\"white\", 97);\n//\t\t// To be continued\n//\t\treturn colourCodes;\n//\t}\n\t\n//\tpublic static Color ansiColourToGraphicsColor(int ansiColor) throws InvalidColourException{\n//\t\t\n//\t\tif(!xterm256ColorCodes().entrySet().contains(ansiColor)){\n//\t\t\tthrow new InvalidColourException();\n//\t\t}\n//\t\tif(ansiColor == 30){ return Color.BLACK; }\n//\t\tif(ansiColor == 31 || ansiColor == 91){ return Color.RED; }\n//\t\tif(ansiColor == 32 || ansiColor == 92){ return Color.GREEN; }\n//\t\tif(ansiColor == 33 || ansiColor == 93){ return Color.YELLOW; }\n//\t\tif(ansiColor == 34 || ansiColor == 94){ return Color.BLUE; }\n//\t\tif(ansiColor == 35 || ansiColor == 95){ return Color.MAGENTA; }\n//\t\tif(ansiColor == 36 || ansiColor == 96){ return Color.CYAN; }\n//\t\tif(ansiColor == 37){ return Color.LIGHT_GRAY; }\n//\t\tif(ansiColor == 90){ return Color.DARK_GRAY; }\n//\t\tif(ansiColor == 97){ return Color.WHITE; }\n//\t\treturn Color.BLACK;\n//\t}\n\t\n\t/** Return true if fileName has a valid tabix index. \n\t * @throws IOException \n\t * */\n\tpublic static boolean hasTabixIndex(String fileName) throws IOException{\n\t\t\n\t\tif((new UrlValidator()).isValid(fileName) && fileName.startsWith(\"ftp\")){\n\t\t\t// Because of issue #51\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\ttry{\n\t\t\tTabixReader tabixReader= new TabixReader(fileName);\n\t\t\ttabixReader.readLine();\n\t\t\ttabixReader.close();\n\t\t\treturn true;\n\t\t} catch (Exception e){\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t/** Get the first chrom string from first line of input file. As you add support for more filetypes you should update \n\t * this function. This method is very dirty and shouldn't be trusted 100% \n\t * @throws InvalidGenomicCoordsException \n\t * @throws SQLException \n\t * @throws InvalidRecordException \n\t * @throws InvalidCommandLineException \n\t * @throws ClassNotFoundException */\n\t@SuppressWarnings(\"unused\")\n\tpublic static String initRegionFromFile(String x) throws IOException, InvalidGenomicCoordsException, ClassNotFoundException, InvalidCommandLineException, InvalidRecordException, SQLException{\n\t\tUrlValidator urlValidator = new UrlValidator();\n\t\tString region= \"\";\n\t\tTrackFormat fmt= Utils.getFileTypeFromName(x); \n\t\t\n\t\tif(fmt.equals(TrackFormat.BAM)){\n\t\t\t\n\t\t\tSamReader samReader;\n\t\t\tif(urlValidator.isValid(x)){\n\t\t\t\tsamReader = SamReaderFactory.makeDefault().open(SamInputResource.of(new URL(x)));\n\t\t\t} else {\n\t\t\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\t\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\t\t\tsamReader = srf.open(new File(x));\n\t\t\t}\n\t\t\t// Default: Start from the first contig in dictionary\n\t\t\tregion= samReader.getFileHeader().getSequence(0).getSequenceName();\n\t\t\tSAMRecordIterator iter = samReader.iterator();\n\t\t\tif(iter.hasNext()){\n\t\t\t\t// If there are records in this BAM, init from first record\n\t\t\t\tSAMRecord rec = iter.next();\n\t\t\t\tif(rec.getContig() != null){\n\t\t\t\t\t// See issue#86 for why we need to check null\n\t\t\t\t\tregion= rec.getContig() + \":\" + rec.getAlignmentStart();\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tsamReader.close();\n\t\t\t}\n\t\t\treturn region;\n\t\t\n\t\t} else if(fmt.equals(TrackFormat.BIGWIG) && !urlValidator.isValid(x)){\n\t\t\t// Loading from URL is painfully slow so do not initialize from URL\n\t\t\treturn initRegionFromBigWig(x);\n\t\t\t\n\t\t} else if(fmt.equals(TrackFormat.BIGBED) && !urlValidator.isValid(x)){\n\t\t\t// Loading from URL is painfully slow so do not initialize from URL\n\t\t\treturn initRegionFromBigBed(x);\n\n\t\t} else if(urlValidator.isValid(x) && (fmt.equals(TrackFormat.BIGWIG) || fmt.equals(TrackFormat.BIGBED))){\n\t\t\tSystem.err.println(\"Refusing to initialize from URL\");\n\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t\t\n\t\t} else if(fmt.equals(TrackFormat.TDF)){\n\t\t\tIterator<String> iter = TDFReader.getReader(x).getChromosomeNames().iterator();\n\t\t\twhile(iter.hasNext()){\n\t\t\t\tregion= iter.next();\n\t\t\t\tif(!region.equals(\"All\")){\n\t\t\t\t\treturn region;\n\t\t\t\t}\n\t\t\t} \n\t\t\tSystem.err.println(\"Cannot initialize from \" + x);\n\t\t\tthrow new RuntimeException();\n\t\t\n\t\t} else {\n\t\t\t// Input file appears to be a generic interval file. We expect chrom to be in column 1\n\t\t\t// VCF files are also included here since they are either gzip or plain ASCII.\n\t\t\tBufferedReader br;\n\t\t\tGZIPInputStream gzipStream;\n\t\t\tif(x.toLowerCase().endsWith(\".gz\") || x.toLowerCase().endsWith(\".bgz\")){\n\t\t\t\tif(urlValidator.isValid(x)) {\n\t\t\t\t\tgzipStream = new GZIPInputStream(new URL(x).openStream());\n\t\t\t\t} else {\n\t\t\t\t\tInputStream fileStream = new FileInputStream(x);\n\t\t\t\t\tgzipStream = new GZIPInputStream(fileStream);\n\t\t\t\t}\n\t\t\t\tReader decoder = new InputStreamReader(gzipStream, \"UTF-8\");\n\t\t\t\tbr = new BufferedReader(decoder);\n\t\t\t} else {\n\t\t\t\tif(urlValidator.isValid(x)) {\n\t\t\t\t\tInputStream instream= new URL(x).openStream();\n\t\t\t\t\tReader decoder = new InputStreamReader(instream, \"UTF-8\");\n\t\t\t\t\tbr = new BufferedReader(decoder);\n\t\t\t\t} else {\n\t\t\t\t\tbr = new BufferedReader(new FileReader(x));\n\t\t\t\t}\n\t\t\t}\n\t\t\tString line;\n\t\t\twhile ((line = br.readLine()) != null){\n\t\t\t\tline= line.trim();\n\t\t\t\tif(line.startsWith(\"#\") || line.isEmpty() || line.startsWith(\"track \")){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(fmt.equals(TrackFormat.VCF)){\n\t\t\t\t\tregion= line.split(\"\\t\")[0] + \":\" + line.split(\"\\t\")[1]; \n\t\t\t\t} else {\n\t\t\t\t\tIntervalFeature feature= new IntervalFeature(line, fmt, null);\n\t\t\t\t\tregion= feature.getChrom() + \":\" + feature.getFrom();\n\t\t\t\t}\n\t\t\t\tbr.close();\n\t\t\t\treturn region;\n\t\t\t}\n\t\t\tif(line == null){ // This means the input has no records\n\t\t\t\tregion= \"Undefined_contig\";\n\t\t\t\tif(fmt.equals(TrackFormat.VCF)){\n\t\t\t\t\tSAMSequenceDictionary seqdict = getVCFHeader(x).getSequenceDictionary();\n\t\t\t\t\tif(seqdict != null){\n\t\t\t\t\t\tIterator<SAMSequenceRecord> iter = seqdict.getSequences().iterator();\n\t\t\t\t\t\tif(iter.hasNext()){\n\t\t\t\t\t\t\tregion= iter.next().getSequenceName();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn region;\n\t\t\t}\n\t\t} \n\t\tSystem.err.println(\"Cannot initialize from \" + x);\n\t\tthrow new RuntimeException();\n\t}\n\t\n\tprivate static String initRegionFromBigBed(String bigBedFile) throws IOException{\n\t\t\n\t\tBBFileReader reader= new BBFileReader(bigBedFile);\n\t\tif(! reader.isBigBedFile()){\n\t\t\tSystem.err.println(\"File \" + bigBedFile + \" is not bigBed.\");\n\t\t\tthrow new RuntimeException();\n\t\t}\n\t\tString region= reader.getChromosomeNames().get(0); // Just get chrom to start with\n\t\t\n\t\tfor(String chrom : reader.getChromosomeNames()){\n\t\t\tBigBedIterator iter = reader.getBigBedIterator(chrom, 0, chrom, Integer.MAX_VALUE, false);\n\t\t\tif(iter.hasNext()){\n\t\t\t\tBedFeature x= (BedFeature) iter.next();\n\t\t\t\tregion= x.getChromosome() + \":\" + (x.getStartBase() + 1);\n\t\t\t\treader.close();\n\t\t\t\treturn region;\n\t\t\t}\n\t\t}\n\t\treader.close();\n\t\treturn region;\n\t}\n\t\n\tprivate static String initRegionFromBigWig(String bigWigFile) throws IOException{\n\t\t\n\t\tBBFileReader reader= new BBFileReader(bigWigFile);\n\t\tif(! reader.isBigWigFile()){\n\t\t\tSystem.err.println(\"File \" + bigWigFile + \" is not bigWig.\");\n\t\t\tthrow new RuntimeException();\n\t\t}\n\t\tString region= reader.getChromosomeNames().get(0); // Just get chrom to start with\n\t\t\n\t\tfor(String chrom : reader.getChromosomeNames()){\n\t\t\tBigWigIterator iter = reader.getBigWigIterator(chrom, 0, chrom, Integer.MAX_VALUE, false);\n\t\t\tif(iter.hasNext()){\n\t\t\t\tWigItem x = iter.next();\n\t\t\t\tregion= x.getChromosome() + \":\" + (x.getStartBase() + 1);\n\t\t\t\treader.close();\n\t\t\t\treturn region;\n\t\t\t}\n\t\t}\n\t\treader.close();\n\t\treturn region;\n\t}\n\t\n\tpublic static boolean bamHasIndex(String bam) throws IOException{\n\n\t\t/* ------------------------------------------------------ */\n\t\t/* This chunk prepares SamReader from local bam or URL bam */\n\t\tUrlValidator urlValidator = new UrlValidator();\n\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\tSamReader samReader;\n\t\tif(urlValidator.isValid(bam)){\n\t\t\tsamReader = SamReaderFactory.makeDefault().open(\n\t\t\t\t\tSamInputResource.of(new URL(bam)).index(new URL(bam + \".bai\"))\n\t\t\t);\n\t\t} else {\n\t\t\tsamReader= srf.open(new File(bam));\n\t\t}\n\t\t/* ------------------------------------------------------ */\n\n\t\t// SamReaderFactory srf=SamReaderFactory.make();\n\t\t// srf.validationStringency(ValidationStringency.SILENT);\n\t\t// SamReader samReader = srf.open(new File(bam));\n\t\tboolean hasIndex= samReader.hasIndex();\n\t\tsamReader.close();\n\t\treturn hasIndex;\n\t\t\n\t}\n\t\n\t/*public static GenomicCoords findNextStringOnFile(String string, String filename, GenomicCoords curGc,\n\t\t\tMap<String, IntervalFeatureSet> intervalFiles ) throws InvalidGenomicCoordsException, IOException{\n\n\t\tString chosenFn= \"\";\n\t\tif(filename.isEmpty() && intervalFiles.size() == 1){ // Only one file to chose from: Get that one\n\t\t\tchosenFn= new ArrayList<String>(intervalFiles.keySet()).get(0);\n\t\t} else {\n\t\t\t// Try to match file perfectly as it was added from cli, including path if any\n\t\t\tfor(String fn : intervalFiles.keySet()){\n\t\t\t\tif(fn.equals(filename)){\n\t\t\t\t\tchosenFn = fn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(chosenFn.isEmpty()){\n\t\t\t\t// Or try to match only file name.\n\t\t\t\tfor(String fn : intervalFiles.keySet()){ // Do not look for a perfect match since the original input might contain path. \n\t\t\t\t\tString onlyName= new File(fn).getName();\n\t\t\t\t\tif(onlyName.equals(filename)){\n\t\t\t\t\t\tchosenFn = fn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(chosenFn.isEmpty()){\n\t\t\tSystem.err.println(\"File \" + filename + \" not found in file set\\n\" + intervalFiles.keySet());\n\t\t\treturn curGc;\n\t\t}\n\t\treturn intervalFiles.get(chosenFn).findNextString(curGc, string);\n\t} */\n\t\n\tpublic static TrackFormat getFileTypeFromName(String fileName){\n\t\tfileName= fileName.toLowerCase();\n\t\t\n\t\tif( fileName.endsWith(\".bed\") \n\t\t || fileName.endsWith(\".bed.gz\") \n\t\t || fileName.endsWith(\".bed.gz.tbi\")\n\t\t || fileName.endsWith(\".bed.bgz\")\n\t\t || fileName.endsWith(\".bed.bgz.tbi\")){\n\t\t\treturn TrackFormat.BED;\n\t\t\n\t\t} else if( fileName.endsWith(\".gtf\") \n\t\t\t\t|| fileName.endsWith(\".gtf.gz\")\n\t\t\t\t|| fileName.endsWith(\".gtf.gz.tbi\")\n\t\t\t\t|| fileName.endsWith(\".gtf.bgz\")\n\t\t\t\t|| fileName.endsWith(\".gtf.bgz.tbi\")){\n\t\t\treturn TrackFormat.GTF;\n\t\t\t\n\t } else if(\n\t\t\t\tfileName.endsWith(\".gff\") \n\t\t\t\t|| fileName.endsWith(\".gff.gz\") \n\t\t\t\t|| fileName.endsWith(\".gff.gz.tbi\")\n\t\t\t\t|| fileName.endsWith(\".gff.bgz\") \n\t\t\t\t|| fileName.endsWith(\".gff.bgz.tbi\")\n\t\t\t\t|| fileName.endsWith(\".gff3\")\n\t\t\t\t|| fileName.endsWith(\".gff3.gz\") \n\t\t\t\t|| fileName.endsWith(\".gff3.gz.tbi\")\n\t\t\t\t|| fileName.endsWith(\".gff3.bgz\") \n\t\t\t\t|| fileName.endsWith(\".gff3.bgz.tbi\")){\n\t\t\treturn TrackFormat.GFF;\n\t\t\t\n\t\t} else if(fileName.endsWith(\".bam\") || fileName.endsWith(\".sam\") || fileName.endsWith(\".sam.gz\") || fileName.endsWith(\".cram\")){\n\t\t\treturn TrackFormat.BAM;\n\t\t\t\n\t\t} else if(fileName.endsWith(\".bigwig\") || fileName.endsWith(\".bw\")) {\n\t\t\treturn TrackFormat.BIGWIG;\n\t\t} else if(fileName.endsWith(\".bigbed\") || fileName.endsWith(\".bb\")) {\n\t\t\treturn TrackFormat.BIGBED;\n\t\t} else if(fileName.endsWith(\".tdf\")) {\n\t\t\treturn TrackFormat.TDF;\n\t\t} else if(fileName.endsWith(\".bedgraph.gz\") || fileName.endsWith(\".bedgraph\")) {\n\t\t\treturn TrackFormat.BEDGRAPH;\n\t\t} else if(fileName.endsWith(\".vcf.gz\") \n\t\t\t\t|| fileName.endsWith(\".vcf\")\n\t\t\t\t|| fileName.endsWith(\".vcf.bgz\")){\n\t\t\treturn TrackFormat.VCF;\n\t\t} else {\n\t\t\t// System.err.println(\"Unsopported file: \" + fileName);\n\t\t\treturn TrackFormat.BED;\n\t\t}\n\t}\n\t\n//\tpublic static LinkedHashMap<String, IntervalFeatureSet> createIntervalFeatureSets(List<String> fileNames) throws IOException, InvalidGenomicCoordsException, ClassNotFoundException, InvalidRecordException, SQLException{\n//\t\tLinkedHashMap<String, IntervalFeatureSet> ifsets= new LinkedHashMap<String, IntervalFeatureSet>();\n//\t\tfor(String x : fileNames){\n//\t\t\tString f= x;\n//\t\t\tif(getFileTypeFromName(x).equals(TrackFormat.BED) || getFileTypeFromName(x).equals(TrackFormat.GFF)){\n//\t\t\t\tif(!ifsets.containsKey(x)){ // If the input has duplicates, do not reload duplicates!\n//\t\t\t\t\tIntervalFeatureSet ifs= new IntervalFeatureSet(f);\n//\t\t\t\t\tifsets.put(x, ifs);\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\treturn ifsets;\n//\t}\n\t\n /** \n * Transpose list of list as if they were a table. No empty cells should be present. \n * See http://stackoverflow.com/questions/2941997/how-to-transpose-listlist\n * FROM\n * [[a, b, c, d], [a, b, c, d], [a, b, c, d]] \n * TO\n * [[a, a, a, a],\n * [b, b, b, b],\n * [c, c, c, c]]\n * @param table Table like list of lists, no empty cells.\n * @return\n */\n public static <T> List<List<T>> transpose(List<List<T>> table) {\n \tList<List<T>> ret = new ArrayList<List<T>>();\n final int N = table.get(0).size();\n for (int i = 0; i < N; i++) {\n List<T> col = new ArrayList<T>();\n for (List<T> row : table) {\n col.add(row.get(i));\n }\n ret.add(col);\n }\n return ret;\n }\n\t\n /**\n * Map list of values mapping top genomic positions to a smaller list of positions by averaging \n * values mapped to the same reference position. These averages are the values that will be used on the \n * y-axis.\n * @param values Values to collapse\n * @param valuePositions Genomic position of the values\n * @param referencePositions Arrival positions. I.e. where the valuePositions should be mapped to. \n * Typically this is obtained from GenomicCoords.getMapping(); \n * @return\n */\n public static List<Double> collapseValues(List<Double> values, List<Integer> valuePositions, \n \t\tList<Double> referencePositions){\n\n \t// First store here all the values mapping to each reference position, then take the average.\n \tLinkedHashMap<Integer, List<Double>> zlist= new LinkedHashMap<Integer, List<Double>>();\n \tfor(int i= 0; i < referencePositions.size(); i++){\n \t\tzlist.put(i, new ArrayList<Double>());\n \t} \n \t\n \tfor(int i= 0; i < valuePositions.size(); i++){\n \t\tif(values.get(i) == null){\n \t\t\tcontinue;\n \t\t}\n \t\tint pos= valuePositions.get(i);\n \t\tif(pos >= referencePositions.get(0) && pos <= referencePositions.get(referencePositions.size()-1)){\n\t \t// Do not consider data points outside screenMap.\n \t\t\tint j= Utils.getIndexOfclosestValue(pos, referencePositions);\n \t\t\tzlist.get(j).add((double)values.get(i));\n \t\t}\n \t}\n \t\n \tList<Double> compressed= new ArrayList<Double>();\n \tfor(int i= 0; i < referencePositions.size(); i++){\n \t\tcompressed.add(Utils.calculateAverage(zlist.get(i)));\n \t}\n \treturn compressed;\n }\n\n\t/**\n\t * Get sequence as byte[] for the given genomic coords.\n\t * @param fasta\n\t * @param gc\n\t * @return\n\t * @throws IOException\n\t */\n\tpublic static byte[] prepareRefSeq(String fasta, GenomicCoords gc) throws IOException{\n\n\t\tbyte[] faSeq= null;\n\t\tif(fasta != null){\n\t\t\tIndexedFastaSequenceFile faSeqFile = null;\n\t\t\ttry {\n\t\t\t\tfaSeqFile = new IndexedFastaSequenceFile(new File(fasta));\n\t\t\t\ttry{\n\t\t\t\t\tfaSeq= faSeqFile.getSubsequenceAt(gc.getChrom(), gc.getFrom(), gc.getTo()).getBases();\n\t\t\t\t} catch (NullPointerException e){\n\t\t\t\t\tSystem.err.println(\"Cannot fetch sequence \" + gc.toString());\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tfaSeqFile.close();\n\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn faSeq;\n\t} \n\t\n\tprivate static int parseStringToIntWithUnits(String x){\n\t\tx= x.trim();\n\t\tint multiplier= 0;\n\t\tif(x.endsWith(\"k\") || x.endsWith(\"K\")){\n\t\t\tmultiplier= 1000;\n\t\t\tx= x.substring(0, x.length()-1).trim();\n\t\t} else if(x.endsWith(\"m\") || x.endsWith(\"M\")){\n\t\t\tmultiplier= 1000000;\n\t\t\tx= x.substring(0, x.length()-1).trim();\n\t\t} else if(x.matches(\"^\\\\-{0,1}\\\\d+$\") || x.matches(\"^\\\\+{0,1}\\\\d+$\")){\n\t\t\tmultiplier= 1;\n\t\t} else {\n\t\t\tthrow new RuntimeException(\"Invalid string to convert to int: \" + x);\n\t\t}\n\t\tlong pos= (long) (Double.parseDouble(x) * multiplier);\n\t\tif( pos >= Integer.MAX_VALUE ){\n\t\t\tSystem.err.println(\"Invalid end coordinate: \" + pos);\n\t\t\tpos= Integer.MAX_VALUE;\n\t\t}\n\t\treturn (int)pos;\n\t}\n\t\n\t/**\n\t * Parse user to modify the current genomics coordinates in input to new ones\n\t * to move.\n\t * @param bam \n\t * @return\n\t * @throws IOException \n\t * @throws InvalidGenomicCoordsException \n\t * @throws InvalidCommandLineException \n\t */\n\tpublic static String parseConsoleInput(List<String> tokens, GenomicCoords gc) throws InvalidGenomicCoordsException, IOException, InvalidCommandLineException{\n\t\t\n//\t\tString region= \"\";\n\t\tString chrom= gc.getChrom();\n\t\tInteger from= gc.getFrom();\n\t\tInteger to= gc.getTo();\n\t\t\n\t\tint windowSize= to - from + 1;\n\t\tint halfWindow= (int)Math.rint(windowSize / 2d);\n\t\tif(tokens.get(0).equals(\"ff\")){\t\t\t\t\n\t\t\tfrom += halfWindow; \n\t\t\tto += halfWindow;\n\t\t\tif(gc.getSamSeqDict() != null && !gc.getSamSeqDict().isEmpty()){\n\t\t\t\tint chromLen= gc.getSamSeqDict().getSequence(chrom).getSequenceLength();\n\t\t\t\tif(to > chromLen){\n\t\t\t\t\tto= chromLen;\n\t\t\t\t\tfrom= to - gc.getUserWindowSize() + 1;\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\treturn chrom + \":\" + from + \"-\" + to;\n\t\t} else if(tokens.get(0).equals(\"bb\")) {\n\t\t\tfrom -= halfWindow;\n\t\t\tto -= halfWindow; \n\t\t\tif(from < 1){\n\t\t\t\tfrom= 1;\n\t\t\t\tto= from + gc.getUserWindowSize() - 1;\n\t\t\t}\n\t\t\treturn chrom + \":\" + from + \"-\" + to;\n\t\t} else if(tokens.get(0).equals(\"f\")){\n\t\t\tint step= (int)Math.rint(windowSize / 10d);\n\t\t\tif(tokens.size() > 1){\n\t\t\t\ttry{\n\t\t\t\t\tstep= (int)Math.rint(windowSize * Double.parseDouble(tokens.get(1)));\n\t\t\t\t} catch(NumberFormatException e){\n\t\t\t\t\tSystem.err.println(\"Cannot parse \" + tokens.get(1) + \" to numeric.\");\n\t\t\t\t\tthrow new InvalidCommandLineException();\n\t\t\t\t} \n\t\t\t}\t\t\t\n\t\t\tfrom += step; \n\t\t\tto += step;\n\t\t\tif(gc.getSamSeqDict() != null && !gc.getSamSeqDict().isEmpty()){\n\t\t\t\tint chromLen= gc.getSamSeqDict().getSequence(chrom).getSequenceLength();\n\t\t\t\tif(to > chromLen){\n\t\t\t\t\tto= chromLen;\n\t\t\t\t\tfrom= to - gc.getUserWindowSize() + 1;\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\treturn chrom + \":\" + from + \"-\" + to;\n\t\t\t\n\t\t} else if(tokens.get(0).equals(\"b\")){\n\t\t\tint step= (int)Math.rint(windowSize / 10d);\n\t\t\tif(tokens.size() > 1){\n\t\t\t\ttry{\n\t\t\t\t\tstep= (int)Math.rint(windowSize * Double.parseDouble(tokens.get(1)));\n\t\t\t\t} catch(NumberFormatException e){\n\t\t\t\t\tSystem.err.println(\"Cannot parse \" + tokens.get(1) + \" to numeric.\");\n\t\t\t\t\tthrow new InvalidCommandLineException();\n\t\t\t\t} \n\t\t\t}\t\t\t\t\t\t\n\t\t\tfrom -= step;\n\t\t\tto -= step; \n\t\t\tif(from < 1){\n\t\t\t\tfrom= 1;\n\t\t\t\tto= from + gc.getUserWindowSize() - 1;\n\t\t\t}\n\t\t\treturn chrom + \":\" + from + \"-\" + to;\n\t\t\n\t\t} else if(tokens.get(0).startsWith(\"+\") \n\t\t\t\t|| tokens.get(0).startsWith(\"-\")){\n\t\t\tint offset= parseStringToIntWithUnits(tokens.get(0));\n\t\t\tfrom += offset;\n\t\t\tif(from <= 0){\n\t\t\t\tfrom= 1;\n\t\t\t\tto= gc.getGenomicWindowSize();\n\t\t\t} else {\n\t\t\t\tto += offset;\n\t\t\t}\n\t\t\treturn chrom + \":\" + from + \"-\" + to;\n\t\t} \n//\t\telse if (tokens.get(0).equals(\"q\")) {\n//\t\t\tSystem.exit(0);\t\n//\t\t} \n\t\telse {\n\t\t\tthrow new RuntimeException(\"Invalid input for \" + tokens);\n\t\t}\n//\t\treturn region;\n\t}\n\t\n\t/**Parse the rawInput string in the form ':123-456' to return either\n\t * the first int or both ints. \n\t * */\n\tprotected static String parseGoToRegion(String rawInput){\n\t\t\n\t\tString[] fromToRaw= rawInput.trim().\n\t\t\t\treplaceAll(\",\", \"\"). // Remove thousands sep if any\n\t\t\t\treplace(GenomicCoords.TICKED, \" \"). // From chrom ideogram \n\t\t\t\treplaceAll(\"-\", \" \"). // Replace - with space for splitting \n\t\t\t\tsplit(\" +\");\n\t\t\n\t\tList<String> fromTo= new ArrayList<String>();\n\t\tfor(String x : fromToRaw){\n\t\t\tif(!x.trim().isEmpty()){\t\n\t\t\t\tfromTo.add(x);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(fromTo.size() == 1){\n\t\t\treturn String.valueOf(Utils.parseStringToIntWithUnits(fromTo.get(0)));\n\t\t\t// Integer.parseInt(fromTo[0].trim()); // Check you actually got an int.\n\t\t\t// return fromTo[0].trim();\n\t\t} else {\n\t\t\tString xfrom= String.valueOf(Utils.parseStringToIntWithUnits(fromTo.get(0)));\n\t\t\tString xto= String.valueOf(Utils.parseStringToIntWithUnits(fromTo.get(fromTo.size()-1)));\n\t\t\treturn xfrom + \"-\" + xto;\n\t\t\t// Integer.parseInt(fromTo[0].trim()); // Check you actually got an int.\n\t\t\t// Integer.parseInt(fromTo[fromTo.length - 1].trim());\n\t\t\t// return fromTo[0].trim() + \"-\" + fromTo[fromTo.length - 1].trim();\n\t\t}\n\t}\n\t\n\tpublic static boolean isInteger(String s) {\n\t \n\t\ts= s.replaceFirst(\"\\\\+\", \"\"); // Allow first char to be +\n\t\t\n\t\ttry { \n\t Integer.parseInt(s); \n\t } catch(NumberFormatException e) { \n\t return false; \n\t } catch(NullPointerException e) {\n\t return false;\n\t }\n\t // only got here if we didn't return false\n\t return true;\n\t}\n\n\t/**\n\t * Average of ints in array x. Adapted from:\n\t * http://stackoverflow.com/questions/10791568/calculating-average-of-an-array-list\n\t * null values are ignored, like R mean(..., na.rm= TRUE). \n\t * Returns Float.NaN if input list is empty or only nulls. You can check for Float.NaN\n\t * with Float.isNaN(x); \n\t * @param marks\n\t * @return\n\t */\n\tpublic static Double calculateAverage(List<Double> list) {\n\t\tdouble sum = 0;\n\t\tlong N= 0; \n\t\tif(!list.isEmpty()) {\n\t\t\tfor (Double z : list) {\n\t\t\t\tif(z != null && !Double.isNaN(z)){\n\t\t\t\t\tsum += z;\n\t\t\t\t\tN++;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn (double)sum / N;\n\t\t}\n\t\treturn Double.NaN;\n\t}\n\n\t/**\n\t * Binary search to get the index position of the value in list closest to a given value.\n\t * The searched list is expected to be sorted, there is no check whether this is the case.\n\t * @param genomePos\n\t * @param mapping\n\t * @return\n\t */\n\tpublic static int getIndexOfclosestValue(double genomePos, List<Double> mapping){\n\n\t\t// Position is before or after the extremes of the list.\n\t\tif(genomePos <= mapping.get(0)){\n\t\t\treturn 0;\n\t\t}\n\t\tif(genomePos >= mapping.get(mapping.size()-1)){\n\t\t\treturn mapping.size()-1;\n\t\t}\n\t\t\n\t\tint closest= Arrays.binarySearch(mapping.toArray(new Double[mapping.size()]), (double)genomePos);\n\t\tif(closest < 0){\n\t\t\t// If < 0 the value is not found in the list and binarySearch returns the insertion point.\n\t\t\t// See binarySearch docs. We need to convert the insertion point to the closest value.\n\t\t\tint insertionPoint= -(closest + 1);\n\t\t\tdouble leftDiff= genomePos - mapping.get(insertionPoint - 1);\n\t\t\tdouble rightDiff= mapping.get(insertionPoint) - genomePos;\n\t\t\tif(leftDiff < rightDiff){\n\t\t\t\treturn insertionPoint - 1;\n\t\t\t} else {\n\t\t\t\treturn insertionPoint;\n\t\t\t}\n\t\t}\n\t\treturn closest;\n\t\t\n//\t\tdouble bestDiff= Integer.MAX_VALUE;\n//\t\tint closest= -1;\n//\t\tfor(int idx= 0; idx < mapping.size(); idx++){ \n//\t\t\t// Iterate through entire list to find closest position on screen, it's a bit wasteful since\n//\t\t\t// the list is ordered, but it's ok.\n//\t\t\tdouble candidate= mapping.get(idx);\n//\t\t\tdouble diff= Math.abs(genomePos - candidate);\n//\t\t\tif(diff < bestDiff){\n//\t\t\t\tclosest= idx;\n//\t\t\t\tbestDiff= diff;\n//\t\t\t}\n//\t\t}\n//\t\tif(closest < 0){\n//\t\t\tthrow new RuntimeException(\"Invalid index position: \" + closest);\n//\t\t}\n//\t\treturn closest;\n\t}\n\t\n\t/** Return true */\n\tpublic static boolean allIsNaN(Iterable<Double> x){\n\t\tfor(Double y : x){\n\t\t\tif(!y.isNaN()){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t\n\tpublic static List<Double> seqFromToLenOut(double from, double to, int lengthOut){\n\t\t\n\t\tif(lengthOut < 0){\n\t\t\tString msg= \"Sequence from \" + from + \" to \" + to + \". Invalid lenght of sequence: Cannot be < 1. Got \" + lengthOut;\n\t\t\tthrow new RuntimeException(msg);\n\t\t} \n\t\tif(lengthOut == 0){ // Consistent with R seq(): return 0-length vector\n\t\t\treturn new ArrayList<Double>();\n\t\t}\t\t\n\t\t\n\t\tList<Double> mapping= new ArrayList<Double>();\n\t\tdouble span= to - from + 1;\n\t\tdouble step= ((double)span - 1)/(lengthOut - 1);\n\t\tmapping.add((double)from);\n\t\tfor(int i= 1; i < lengthOut; i++){\n\t\t\tmapping.add((double)mapping.get(i-1)+step);\n\t\t}\n\n\t\tif(lengthOut == 1){ // Consistent with R seq(from, to, length.out= 1) -> from\n\t\t//\tmapping.add((double)from);\n\t\t\treturn mapping;\n\t\t}\n\t\t\n\t\tdouble diffTo= Math.abs(mapping.get(mapping.size() - 1) - to);\n\t\tif(diffTo > Math.abs((to + 1e-9))){\n\t\t\tString msg= \"Error generating sequence from \" + from + \" to \" + to + \" length \" + lengthOut + \"\\n\" +\n\t\t\t\t\t \"Last point: \" + mapping.get(mapping.size() - 1) + \"\\n\" +\n\t\t\t\t\t \"To diff: \" + diffTo + \"\\n\" +\n\t\t\t\t\t \"Step: \" + step;\n\t\t\tthrow new RuntimeException(msg);\n\t\t} else {\n\t\t\tmapping.set(mapping.size()-1, (double)to);\n\t\t}\n\t\t\n\t\tdouble diffFrom= Math.abs(mapping.get(0) - from);\t\t\n\t\tif(diffFrom > 0.01 || mapping.size() != lengthOut){\n\t\t\tString msg= \"Error generating sequence:\\n\" +\n\t\t\t\t\t \"Expected size: \" + lengthOut + \"; Effective: \" + mapping.size() + \"\\n\" + \n\t\t\t\t\t \"From diff: \" + diffFrom;\n\t\t\tthrow new RuntimeException(msg);\n\t\t}\n\t\treturn mapping;\n\t}\n\n\t/** Nicely tabulate list of rows. Each row is tab separated \n\t * The terminalWidth param is used to decide whether rows should be flushed left instead of\n\t * being nicely tabulated. If the amount of white space in a cell is too much relative to \n\t * terminalWidth, then flush left. With special value: -1 never flush left, with 0 always flush.\n\t */\n\tpublic static List<String> tabulateList(List<String> rawList, int terminalWidth) {\n\t\t// This method could be streamlined to be more efficient. There are quite a few\n\t\t// Lists moved around that could be avoided. However, the size of the table is\n\t\t// typically small enough that we prefer a clearer layout over efficiency.\n\t\t\n\t\t// * Split each row in a list of strings. I.e. make list of lists\n\t\tList<ArrayList<String>> rawTable= new ArrayList<ArrayList<String>>();\n\t\tint ncol= 0;\n\t\tfor(String x : rawList){\n\t\t\tList<String> row = new ArrayList<String>();\n\t\t\tfor(String item : x.split(\"\\t\")){\n\t\t\t\trow.add(item);\n\t\t\t}\n\t\t\trawTable.add((ArrayList<String>) row);\n\t\t\t// * Get max number of columns (max list length)\n\t\t\tif(row.size() > ncol){\n\t\t\t\tncol= row.size(); \n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\t// * Iterate through each column \n\t\tList<List<String>> paddedTable= new ArrayList<List<String>>();\n\t\t\n\t\tfor(int i= 0; i < ncol; i++){\n\t\t\t// Collect all items in column i in a list. I.e. select column i\n\t\t\tList<String> col= new ArrayList<String>();\n\t\t\tfor(ArrayList<String> row : rawTable){\n\t\t\t\tif(row.size() > i){\n\t\t\t\t\tcol.add(row.get(i));\n\t\t\t\t} else { // If a row doesn't have enough columns add a dummy field \n\t\t\t\t\tcol.add(\"\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Get the longest string in this column\n\t\t\tint maxStr= 1;\n\t\t\tfor(String x : col){\n\t\t\t\tx= Utils.stripAnsiCodes(x);\n\t\t\t\tif(x.length() > maxStr){\n\t\t\t\t\tmaxStr= x.length();\n\t\t\t\t}\n\t\t\t}\n\t\t\t// ** Pass through the column again and pad with spaces to match length of longest string\n\t\t\tfor(int j= 0; j < col.size(); j++){\n\t\t\t\tint nblanks= maxStr - Utils.stripAnsiCodes(col.get(j)).length();\n\t\t\t\tString padded= col.get(j) + StringUtils.repeat(\" \", nblanks); // String.format(\"%-\" + maxStr + \"s\", col.get(j));\n\t\t\t\tcol.set(j, padded);\n\t\t\t}\n\t\t\tpaddedTable.add((List<String>) col);\n\t\t}\n\n\t\t// In paddedTable each inner list is a column. Transpose to have\n\t\t// inner list as row as it is more convenient from now on.\n\t\tList<List<String>> tTable= new ArrayList<List<String>>();\n\t\tfor(int r= 0; r < rawList.size(); r++){\n\t\t\tList<String> row= new ArrayList<String>();\n\t\t\tfor(int c= 0; c < paddedTable.size(); c++){\n\t\t\t\trow.add(paddedTable.get(c).get(r));\n\t\t\t}\n\t\t\ttTable.add(row);\n\t\t}\n\t\t\n\t\t// If a cell (String) has too many spaces to the right, flush left, i.e. trim(),\n\t\t// that cell and all the cells to right on that row. This is to prevent odd\n\t\t// formatting where a long string in one cell makes all the other cells look very empty.\n\t\tterminalWidth= terminalWidth < 0 ? Integer.MAX_VALUE : terminalWidth;\n\t\tfor(List<String> row : tTable){\n\t\t\tboolean flush= false;\n\t\t\tfor(int i= 0; i < row.size(); i++){\n\t\t\t\tif(! flush){\n\t\t\t\t\tint whiteSize= Utils.stripAnsiCodes(row.get(i)).length() - Utils.stripAnsiCodes(row.get(i)).trim().length();\n\t\t\t\t\tif(whiteSize > terminalWidth/4.0){\n\t\t\t\t\t\t// The rest of this row will be flushed\n\t\t\t\t\t\tflush= true;\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(flush){\n\t\t\t\t\trow.set(i, row.get(i).replaceAll(\"^ +| +$\", \"\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Finally, join row into a list of single, printable strings:\t\t\n\t\tList<String> outputTable= new ArrayList<String>();\n\t\tfor(List<String> lstRow : tTable){\n\t\t\tString row= Joiner.on(\" \").join(lstRow); // Here you decide what separates columns.\n\t\t\toutputTable.add(row.toString()); // Do not use .trim() here otherwise you could strip ANSI formatting\n\t\t}\n\t\treturn outputTable;\n\t}\n\n\t/** Function to round x and y to a number of digits enough to show the difference in range\n\t * This is for pretty printing only.\n\t * */\n\tpublic static String[] roundToSignificantDigits(double x, double y, int nSignif) {\n\n\t\tDouble[] rounded= new Double[2];\n\t\t\n\t double diff= Math.abs(x - y);\n\t if (diff < 1e-16){\n\t \trounded[0]= x;\n\t \trounded[1]= y;\n\t }\n\t else if(diff > 1){\n\t \t// Round to 2 digits regardless of how large is the diff\n\t \trounded[0]= Math.rint(x * Math.pow(10.0, nSignif))/Math.pow(10.0, nSignif);\n\t \trounded[1]= Math.rint(y * Math.pow(10.0, nSignif))/Math.pow(10.0, nSignif);\n\t\t} else {\n\t \t// Diff is small, < 1. See how many digits you need to approximate\n\t \t// Get number of leading zeros\n\t \tint nzeros= (int) (Math.ceil(Math.abs(Math.log10(diff))) + nSignif);\n\t \trounded[0]= Math.rint(x * Math.pow(10.0, nzeros))/Math.pow(10.0, nzeros);\n\t \trounded[1]= Math.rint(y * Math.pow(10.0, nzeros))/Math.pow(10.0, nzeros);\n\t }\n\t String[] out= new String[2];\n\t out[0]= rounded[0].toString();\n\t out[1]= rounded[1].toString();\n\t return out;\n\t}\n\t\n\t/** From http://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits */\n\tpublic static double roundToSignificantFigures(double num, int n) {\n\t if(num == 0) {\n\t return 0;\n\t }\n\n\t final double d = Math.ceil(Math.log10(num < 0 ? -num: num));\n\t final int power = n - (int) d;\n\n\t final double magnitude = Math.pow(10, power);\n\t final long shifted = Math.round(num*magnitude);\n\t return shifted/magnitude;\n\t}\n\t\n\t/** Convert 000 and 000,000 to k and M suffix. E.g. 1000 -> \"1k\"; 123000000 -> 123M\n\t * See also roundToSignificantFigures() to round numbers. \n\t * */\n\tpublic static String parseIntToMetricSuffix(int x){\n\t\tString xint= String.valueOf(x);\n\t\tif(xint.endsWith(\"000000\")){\n\t\t\txint= xint.replaceAll(\"000000$\", \"M\");\n\t\t} else if(xint.endsWith(\"000\")){\n\t\t\txint= xint.replaceAll(\"000$\", \"k\");\n\t\t}\n\t\treturn xint;\n\t}\n\n\t\n\t/** Returns true if URL file exists. \n\t * NB: Returns true also if the url path exists but it's just a directory and not a file! \n\t * From http://stackoverflow.com/questions/4596447/check-if-file-exists-on-remote-server-using-its-url\n\t * */\n\tpublic static boolean urlFileExists(String URLName){\n\n\t\ttry{ // For ftp files\n\t\t\tInputStream ftp = new URL(URLName).openStream();\n\t\t\tftp.close();\n\t\t\treturn true;\n\t\t} catch(Exception e){\n\t\t\t//\n\t\t}\n\t\t\n\t try {\n\t HttpURLConnection.setFollowRedirects(false);\n\t // note : you may also need\n\t // HttpURLConnection.setInstanceFollowRedirects(false)\n\t HttpURLConnection con =\n\t (HttpURLConnection) new URL(URLName).openConnection();\n\t con.setRequestMethod(\"HEAD\");\n\t return (con.getResponseCode() == HttpURLConnection.HTTP_OK);\n\t }\n\t catch (Exception e) {\n\t return false;\n\t }\n\t}\n\t\n\t/** Add track(s) to list of input files \n\t * @param inputFileList Existing list of files to be extended\n\t * @param newFileNames List of files to append\n\t * @throws InvalidCommandLineException \n\t * @throws IOException \n\t */\n\tpublic static void addSourceName(List<String> inputFileList, List<String> newFileNames, int debug) throws InvalidCommandLineException, IOException {\n\n\t\tList<String> dropMe= new ArrayList<String>();\n\t\tList<String> addMe= new ArrayList<String>();\n\t\tfor(int i= 0; i < newFileNames.size(); i++){\n\t\t\tString x= newFileNames.get(i).trim();\n\t\t\tif(!new File(x).isFile() && !Utils.urlFileExists(x)){\n\t\t\t\tdropMe.add(x);\n\t\t\t\tSystem.err.println(\"Unable to add \" + x);\n\t\t\t\tthrow new InvalidCommandLineException();\n\t\t\t} \n\t\t}\n\t\tfor(String x : dropMe){\n\t\t\t//System.err.println(\"\\nWarning: File \" + x + \" is not a local file.\\n\");\n\t\t\tnewFileNames.remove(x);\n\t\t}\n\t\tfor(String x : addMe){\n\t\t\tnewFileNames.add(x);\n\t\t}\n\t\tinputFileList.addAll(newFileNames);\t\t\n\t}\n\n\t/** Read a sample of file x and return its track format. \n\t * This method is not generic so keep it private. Input file must be uncompressed,\n\t * must have header if SAM or VCF.\n\t * @throws IOException \n\t * */\n\tpublic static TrackFormat sniffFile(File x) throws IOException{\n\n\t\ttry{\n\t\t\tVCFFileReader vcf= new VCFFileReader(x, false);\n\t\t\tfor(@SuppressWarnings(\"unused\") VariantContext rec : vcf){\n\t\t\t\t//\n\t\t\t}\n\t\t\tvcf.close();\n\t\t\treturn TrackFormat.VCF;\n\t\t} catch(Exception e){\n\t\t\t//\n\t\t}\n\t\t\n\t\ttry{\n\t\t\tSamReader sam = SamReaderFactory.make().open(x);\n\t\t\tfor(@SuppressWarnings(\"unused\") SAMRecord rec : sam){\n\t\t\t\t//\n\t\t\t}\n\t\t\tsam.close();\n\t\t\treturn TrackFormat.BAM;\n\t\t} catch(Exception e){\n\t\t\t//\n\t\t}\n\n\t\tBufferedReader br= new BufferedReader(new FileReader(x));\n\t\tint maxLines= 100000;\n\t\tboolean firstLine= true;\n\t\tString line= null;\n\t\tList<String[]> sample= new ArrayList<String[]>();\n\t\twhile((line= br.readLine()) != null){\n\t\t\tline= line.trim();\n\t\t\tif(line.isEmpty()){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif(firstLine && line.startsWith(\"##\") && line.contains(\"gff-version\")){\n\t\t\t\tbr.close();\n\t\t\t\treturn TrackFormat.GFF;\n\t\t\t}\n\t\t\tfirstLine= false;\n\t\t\tif(line.startsWith(\"#\")){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsample.add(line.split(\"\\t\"));\n\t\t\tmaxLines--;\n\t\t\tif(maxLines == 0){\n\t\t\t\tbr.close();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tbr.close();\n\t\t// Try GTF format. We don't distiguish here between GTF and GFF.\n\t\tboolean isGtf= true;\n\t\tfor(String[] s : sample){\n\t\t\tif(s.length < 8){\n\t\t\t\tisGtf= false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttry{\n\t\t\t\tint start= Integer.valueOf(s[3]);\n\t\t\t\tint end= Integer.valueOf(s[4]);\n\t\t\t\tif(start > end || start < 1 || end < 1){\n\t\t\t\t\tisGtf= false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} catch(NumberFormatException e){\n\t\t\t\tisGtf= false;\n\t\t\t\tbreak;\t\t\t\t\n\t\t\t}\n\t\t\tif( ! (s[6].equals(\"+\") || s[6].equals(\"-\") || s[6].equals(\".\"))){\n\t\t\t\tisGtf= false;\n\t\t\t\tbreak;\t\t\t\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\tif(isGtf){\n\t\t\treturn TrackFormat.GTF;\n\t\t}\n\t\t\n\t\t// Try bedgraph\n\t\tboolean isBedgraph= true;\n\t\tfor(String[] bdg : sample){\n\t\t\tif(bdg.length < 4){\n\t\t\t\tisBedgraph= false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\ttry{\n\t\t\t\tInteger.valueOf(bdg[1]);\n\t\t\t\tInteger.valueOf(bdg[2]);\n\t\t\t\tDouble.valueOf(bdg[3]);\n\t\t\t} catch(NumberFormatException e){\n\t\t\t\tisBedgraph= false;\n\t\t\t\tbreak;\t\t\t\t\n\t\t\t}\n\t\t\tif(Integer.valueOf(bdg[1]) < 0 || Integer.valueOf(bdg[2]) < 0 || Integer.valueOf(bdg[1]) > Integer.valueOf(bdg[2])){\n\t\t\t\tisBedgraph= false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(isBedgraph){\n\t\t\treturn TrackFormat.BEDGRAPH;\n\t\t}\n\t\t\n\t\t// Last option: BED\n\t\tboolean isBed= true;\n\t\tfor(String[] bed : sample){\n\t\t\tif(bed.length < 3){\n\t\t\t\tisBed= false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tint start;\n\t\t\tint end;\n\t\t\ttry{\n\t\t\t\tstart= Integer.valueOf(bed[1]);\n\t\t\t\tend= Integer.valueOf(bed[2]);\n\t\t\t} catch(NumberFormatException e){\n\t\t\t\tisBed= false;\n\t\t\t\tbreak;\t\t\t\t\n\t\t\t}\n\t\t\tif(start < 0 || end < 0 || start > end){\n\t\t\t\tisBed= false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(isBed){\n\t\t\treturn TrackFormat.BED;\t\n\t\t} else {\n\t\t\tthrow new IOException(\"Input format cannot be determined.\");\n\t\t}\n\t}\n\t\n\tpublic static String printSamSeqDict(SAMSequenceDictionary samSeqDict, int graphSize){\n\t\t\n\t\tif(samSeqDict == null || samSeqDict.isEmpty()){\n\t\t\tSystem.err.println(\"Sequence dictionary not available.\");\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\t// Prepare a list of strings. Each string is a row tab separated\n\t\tList<String> tabList= new ArrayList<String>();\n\t\tint maxChromLen= -1;\n\t\tfor(SAMSequenceRecord x : samSeqDict.getSequences()){\n\t\t\tString row= x.getSequenceName() + \"\\t\" + x.getSequenceLength();\t\t\t\n\t\t\ttabList.add(row);\n\t\t\tif(x.getSequenceLength() > maxChromLen){\n\t\t\t\tmaxChromLen= x.getSequenceLength(); \n\t\t\t}\n\t\t}\n\t\tdouble bpPerChar= (double)maxChromLen / (double)graphSize;\n\t\tfor(int i= 0; i < samSeqDict.getSequences().size(); i++){\n\t\t\tSAMSequenceRecord x= samSeqDict.getSequences().get(i);\n\t\t\tint n= (int)Math.rint(x.getSequenceLength()/bpPerChar);\n\t\t\tString bar= StringUtils.join(Collections.nCopies(n, \"|\"), \"\"); // String.join(\"\", Collections.nCopies(n, \"|\"));\n\t\t\tString row= tabList.get(i) + \"\\t\" + bar;\n\t\t\ttabList.set(i, row);\n\t\t}\n\t\tList<String> table= Utils.tabulateList(tabList, -1);\n\t\tStringBuilder out= new StringBuilder();\n\t\tfor(String x : table){\n\t\t\tout.append(x).append(\"\\n\");\n\t\t}\n\t\treturn out.toString().trim();\n\t}\n\t\n\t/** Parse cmdInput to extract the integer after the arg. (see tests)\n\t * @param defaultInt Default value if parsing returns nonsense\n\t * @throws InvalidCommandLineException \n\t * */\n\tpublic static int parseZoom(String cmdInput, int defaultInt) throws InvalidCommandLineException {\n\t\tString[] zz= cmdInput.trim().split(\" +\");\n\t\tint nz= defaultInt;\n\t\tif(zz.length >= 2){\n\t\t\tnz= Integer.parseInt(zz[1]);\n\t\t} \n\t\tif(nz < 0){\n\t\t\tthrow new InvalidCommandLineException();\n\t\t}\n\t\treturn nz;\n\t}\n\n\t/** Split string x in tokens. Effectively just a friendly wrapper around StrTokenizer.\n\t * Use *single* quotes for avoiding splitting. \n\t */\n\tpublic static ArrayList<String> tokenize(String x, String delimiterString){\n\t\t\n\t\tif(x == null){\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\t// This is a hack to allow empty tokens to be passed at the command line. \n\t\t// An empty \n\t\tx= x.replace(\"''\", \"' '\");\n\t\t\n\t\t// See also http://stackoverflow.com/questions/38161437/inconsistent-behaviour-of-strtokenizer-to-split-string\n\t\tStrTokenizer str= new StrTokenizer(x);\n \tstr.setTrimmerMatcher(StrMatcher.spaceMatcher());\n\t\tstr.setDelimiterString(delimiterString);\n\t\tstr.setQuoteChar('\\'');\n\t\t// str.setIgnoreEmptyTokens(false);\n\t\tArrayList<String> tokens= (ArrayList<String>) str.getTokenList();\n\t\tfor(int i= 0; i < tokens.size(); i++){\n\t\t\tString tok= tokens.get(i).trim();\n\t\t\ttokens.set(i, tok);\n\t\t}\n\t\treturn tokens;\n\t\n\t}\n\t\n\tpublic static String stripAnsiCodes(String x){\n\t\treturn x.replaceAll(\"\\\\033\\\\[[;\\\\d]*m\", \"\");\n\t}\n\t\n\t/** Get a filaname to write to. GenomicCoords obj is used to get current position and \n\t * create a suitable filename from it, provided a filename is not given.\n\t * The string '%r' in the file name, is replaced with the current position. Useful to construct\n\t * file names like myPeaks.%r.pdf -> myPeaks.chr1_1234-5000.pdf.\n\t * */\n\tpublic static String parseCmdinputToGetSnapshotFile(String cmdInput, GenomicCoords gc) throws IOException{\n\t\t\n\t\tfinal String REGVAR= \"%r\";\n\t\t\n\t\tString snapshotFile= cmdInput.trim().replaceAll(\"^save\", \"\").trim();\n\t\t\n\t\tString region= gc.getChrom() + \"_\" + gc.getFrom() + \"_\" + gc.getTo();\n\t\t\n\t\tif(snapshotFile.isEmpty()){\n\t\t\tsnapshotFile= REGVAR + \".txt\"; \n\t\t} else if(snapshotFile.equals(\".pdf\")){\n\t\t\tsnapshotFile= REGVAR + \".pdf\";\n\t\t} \n\t\tsnapshotFile= snapshotFile.replace(REGVAR, region); // Special string '%r' is replaced with the region \n\t\tsnapshotFile= Utils.tildeToHomeDir(snapshotFile);\n\t\t\n\t\tFile file = new File(snapshotFile);\n\t\tif(file.exists() && !file.canWrite()){\n\t\t\tSystem.err.println(\"Cannot write to \" + snapshotFile);\n\t\t\tsnapshotFile= null;\n\t\t\treturn snapshotFile;\n\t\t}\n\t\tif(!file.exists()){\n\t\t\ttry{\n\t\t\t\tfile.createNewFile();\n\t\t\t\tfile.delete();\n\t\t\t} catch(IOException e) {\n\t\t\t\tSystem.err.println(\"Cannot create file \" + snapshotFile);\n\t\t\t\tsnapshotFile= null;\n\t\t\t\treturn snapshotFile;\n\t\t\t}\n\t\t}\n\t\treturn snapshotFile;\n\t}\n\t\n\t/** Expand ~/ to user's home dir in file path name. See tests for behaviour\n\t * */\n\tpublic static String tildeToHomeDir(String path){\n\t\treturn path.replaceAll(\"^~\" + Pattern.quote(File.separator), System.getProperty(\"user.home\") + File.separator);\n\t}\n\t\n\t/**\n\t * Count reads in interval using the given filters.\n\t * @param bam\n\t * @param gc\n\t * @param filters List of filters to apply\n\t * @return\n\t * @throws MalformedURLException \n\t */\n\tpublic static long countReadsInWindow(String bam, GenomicCoords gc, List<SamRecordFilter> filters) throws MalformedURLException {\n\n\t\t/* ------------------------------------------------------ */\n\t\t/* This chunk prepares SamReader from local bam or URL bam */\n\t\tUrlValidator urlValidator = new UrlValidator();\n\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\tSamReader samReader;\n\t\tif(urlValidator.isValid(bam)){\n\t\t\tsamReader = srf.open(SamInputResource.of(new URL(bam)).index(new URL(bam + \".bai\")));\n\t\t} else {\n\t\t\tsamReader= srf.open(new File(bam));\n\t\t}\n\t\t/* ------------------------------------------------------ */\n\t\t\n\t\tlong cnt= 0;\n\t\t\n\t\tIterator<SAMRecord> sam= samReader.query(gc.getChrom(), gc.getFrom(), gc.getTo(), false);\n\t\tAggregateFilter aggregateFilter= new AggregateFilter(filters);\n\t\twhile(sam.hasNext()){\n\t\t\tSAMRecord rec= sam.next();\n\t\t\tif( !aggregateFilter.filterOut(rec) ){\n\t\t\t\tcnt++;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tsamReader.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn cnt;\n\t}\n\n\t/** Sort Map by value in descending order. See\n\t * http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java\n\t * */\n\tpublic static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ){\n\t List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() );\n\t Collections.sort( list, new Comparator<Map.Entry<K, V>>() {\n\t @Override\n\t public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ){\n\t return -( o1.getValue() ).compareTo( o2.getValue() );\n\t }\n\t });\n\t \n\t Map<K, V> result = new LinkedHashMap<>();\n\t for (Map.Entry<K, V> entry : list){\n\t result.put( entry.getKey(), entry.getValue() );\n\t }\n\t return result;\n\t}\n\n//\tpublic static List<SamRecordFilter> cleanInappropriateCallIfNotPairedRead(List<SamRecordFilter> filter){\n//\t\tList<SamRecordFilter> cleanfilter= new ArrayList<SamRecordFilter>(); \n//\t\tfor(SamRecordFilter x : filter){\n//\t\t\tif(x.equals(new FirstOfPairFilter(true)) ||\n//\t\t\t x.equals(new FirstOfPairFilter(false))){\n//\t\t\t //\n//\t\t\t} else {\n//\t\t\t\tcleanfilter.add(x);\n//\t\t\t}\n//\t\t}\n//\t\treturn cleanfilter;\n//\t} \n\t\n\tpublic static TabixFormat trackFormatToTabixFormat(TrackFormat fmt){\n\t\t\n\t\tTabixFormat tbx= null;\n\t\tif(fmt.equals(TrackFormat.BAM)){\n\t\t\ttbx= TabixFormat.SAM; \n\t\t} else if (fmt.equals(TrackFormat.BED) || fmt.equals(TrackFormat.BEDGRAPH)){\n\t\t\ttbx= TabixFormat.BED; \n\t\t} else if (fmt.equals(TrackFormat.GFF) || fmt.equals(TrackFormat.GTF)){\n\t\t\ttbx= TabixFormat.GFF;\n\t\t} else if (fmt.equals(TrackFormat.VCF)){\n\t\t\ttbx= TabixFormat.VCF;\n\t\t} else {\n\t\t\tthrow new RuntimeException();\n\t\t}\n\t\treturn tbx;\n\t\t\n\t}\n\t\n\t/** Same as R range(..., na.rm= TRUE) function: Return min and max of \n\t * list of values ignoring NaNs.\n\t * */\n\tpublic static Float[] range(List<Float> y){\n\t\tFloat[] range= new Float[2];\n\t\t\n\t\tFloat ymin= Float.NaN;\n\t\tFloat ymax= Float.NaN;\n\t\tfor(Float x : y){\n\t\t\tif(!x.isNaN()){\n\t\t\t\tif(x > ymax || ymax.isNaN()){\n\t\t\t\t\tymax= x;\n\t\t\t\t} \n\t\t\t\tif(x < ymin || ymin.isNaN()){\n\t\t\t\t\tymin= x;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\trange[0]= ymin;\n\t\trange[1]= ymax;\n\t\treturn range;\n\t}\n\t\n\t/** Convert coordinates to string suitable for initializing GenomicCoords object.\n\t * See tests for handling odd cases.\n\t * */\n\tpublic static String coordinatesToString(String chrom, Integer from, Integer to){\n\t\t\n\t\tif(from == null){\n\t\t\tfrom = -1;\n\t\t}\n\t\tif(to == null){\n\t\t\tto = -1;\n\t\t}\n\t\t\n\t\tString xfrom;\n\t\tif(from <= 0){\n\t\t\txfrom= \"1\";\n\t\t} else {\n\t\t\txfrom= from.toString();\n\t\t}\n\t\tString xto;\n\t\tif(to <= 0 || to < from){\n\t\t\txto= \"\";\n\t\t} else {\n\t\t\txto= \"-\" + to.toString();\n\t\t}\n\t\treturn chrom + \":\" + xfrom + xto;\n\t} \n\t\n\t/** Return list of files matching the list of glob expressions. This method should behave\n\t * similarly to GNU `ls` command. \n\t * \n\t * * Directories are not returned \n\t * \n\t * Files are returned as they are matched, \n\t * so not necessarily in alphabetical order.\n\t * \n\t * */\n\tpublic static List<String> globFiles(List<String> cmdInput) throws IOException {\n\t\t\n\t\tList<String> globbed= new ArrayList<String>();\n\t\t\n\t\tfor(String x : cmdInput){\n\t\t\t\n\t\t\tif(Utils.urlFileExists(x)){\n\t\t\t\tglobbed.add(x);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tx= Utils.tildeToHomeDir(x);\n\t\t\tx= x.replaceAll(Pattern.quote(File.separator) + \"+$\", \"\"); // Remove trailing dir sep\n\t\t\tx= x.replaceAll(Pattern.quote(File.separator) + \"+\", File.separator); // Remove double dir sep like \"/foo//bar\" -> /foo/bar \n\n\t\t\tString location;\n\t\t\tif(new File(x).isDirectory()){\n\t\t\t\tlocation= x;\n\t\t\t\tx= x + File.separator + \"*\"; // From \"my_dir\" to \"my_dir/*\" \n\t\t\t} else {\n\t\t\t\tlocation= new File(x).getParent();\n\t\t\t\tif(location == null){\n\t\t\t\t\tlocation= \"\";\n\t\t\t\t}\n\t\t\t} \n\t\t\tfor(Path p : match(x, location)){\n\t\t\t\tglobbed.add(p.toString());\n\t\t\t}\n\t\t}\t\t\n\t\treturn globbed;\n\t}\n\n\t/** Search for a glob pattern in a given directory and its sub directories\n\t * See http://javapapers.com/java/glob-with-java-nio/\n\t * */\n\tprivate static List<Path> match(String glob, String location) throws IOException {\n\t\t\n\t\tfinal List<Path> globbed= new ArrayList<Path>();\n\t\t\n\t\tfinal PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(\"glob:\" + glob);\n\t\t\n\t\tFiles.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {\n\t\t\t\tif (pathMatcher.matches(path)) {\n\t\t\t\t\tglobbed.add(path);\n\t\t\t\t}\n\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic FileVisitResult visitFileFailed(Path file, IOException exc)\n\t\t\t\t\tthrows IOException {\n\t\t\t\treturn FileVisitResult.CONTINUE;\n\t\t\t}\n\t\t});\n\t\treturn globbed;\n\t}\n\n\t/** Query github repo to check if a version newer then this one is available.\n\t * Returns list of length 2: [\"this version\", \"latest version on github\"]\n\t * @param timeout Return if no response is received after so many milliseconds.\n\t * @throws IOException \n\t * */\n\tprotected static List<String> checkUpdates(long timeout) throws IOException {\n\t\t\n\t\tList<String> thisAndGitVersion= new ArrayList<String>();\n\t\t\n\t\t// Get version of this ASCIIGenome\n\t\tthisAndGitVersion.add(ArgParse.VERSION);\n\t\t\n\t\tBufferedReader br= null;\n\t\ttimeout= timeout + System.currentTimeMillis();\n\t\t// Get github versions\n\t\tURL url = new URL(\"https://api.github.com/repos/dariober/ASCIIGenome/tags\");\n\t\tbr = new BufferedReader(new InputStreamReader(url.openStream()));\n\n\t\tString line;\n StringBuilder sb= new StringBuilder();\n while ((line = br.readLine()) != null) {\n \tsb.append(line + '\\n');\n }\n\n JsonElement jelement = new JsonParser().parse(sb.toString());\n JsonArray jarr = jelement.getAsJsonArray();\n Iterator<JsonElement> iter = jarr.iterator();\n\n List<String> tag= new ArrayList<String>();\n while(iter.hasNext()){\n \t// Get all tags\n JsonObject jobj = (JsonObject) iter.next();\n tag.add(jobj.get(\"name\").getAsString().replaceAll(\"^[^0-9]*\", \"\").trim());\n }\n if(tag.size() == 0){\n \tthisAndGitVersion.add(\"0\");\n } else {\n \tthisAndGitVersion.add(tag.get(0));\n }\n return thisAndGitVersion;\n\t}\n\t\n\t/**\n\t * Compares two version strings. \n\t * \n\t * Use this instead of String.compareTo() for a non-lexicographical \n\t * comparison that works for version strings. e.g. \"1.10\".compareTo(\"1.6\").\n\t * \n\t * From \n\t * http://stackoverflow.com/questions/6701948/efficient-way-to-compare-version-strings-in-java\n\t * \n\t * @note It does not work if \"1.10\" is supposed to be equal to \"1.10.0\".\n\t * \n\t * @param str1 a string of ordinal numbers separated by decimal points. \n\t * @param str2 a string of ordinal numbers separated by decimal points.\n\t * @return The result is a negative integer if str1 is _numerically_ less than str2. \n\t * The result is a positive integer if str1 is _numerically_ greater than str2. \n\t * The result is zero if the strings are _numerically_ equal.\n\t * \n\t */\n\tpublic static int versionCompare(String str1, String str2) {\n\t String[] vals1 = str1.split(\"\\\\.\");\n\t String[] vals2 = str2.split(\"\\\\.\");\n\t int i = 0;\n\t // set index to first non-equal ordinal or length of shortest version string\n\t while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {\n\t i++;\n\t }\n\t // compare first non-equal ordinal number\n\t if (i < vals1.length && i < vals2.length) {\n\t int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));\n\t return Integer.signum(diff);\n\t }\n\t // the strings are equal or one string is a substring of the other\n\t // e.g. \"1.2.3\" = \"1.2.3\" or \"1.2.3\" < \"1.2.3.4\"\n\t return Integer.signum(vals1.length - vals2.length);\n\t}\n\n\t/** Stream the raw line through awk and return true if the output of awk is the same as the input\n\t * line. If awk returns empty output then the line didn't pass the awk filter.\n\t * If output is not empty and not equal to input, return null.\n\t * See tests for behaviour. \n\t * */\n//\tpublic static Boolean passAwkFilter(String rawLine, String awkScript) throws IOException {\n//\t\t\n//\t\tawkScript= awkScript.trim();\n//\t\t\n//\t\tif(awkScript.isEmpty()){\n//\t\t\treturn true;\n//\t\t}\n//\t\t\n//\t\t// We need to separate the awk script from the arguments. The arguments could contain single quotes:\n//\t\t// -v var=foo '$1 == var && $2 == baz'\n//\t\t// For this, reverse the string and look for the first occurrence of \"' \" which corresponds to \n//\t\t// the opening of the awk script.\n//\t\tint scriptStartsAt= awkScript.length() - new StringBuilder(awkScript).reverse().toString().indexOf(\"' \");\n//\t\tif(scriptStartsAt == awkScript.length() + 1){\n//\t\t\tscriptStartsAt= 1;\n//\t\t}\n//\t\t// Now add the functions to the script right at the start of the script, after the command args\n//\t\tawkScript= awkScript.substring(0, scriptStartsAt) + Track.awkFunc + awkScript.substring(scriptStartsAt);\n//\t\t\t\t\n//\t\tInputStream is= new ByteArrayInputStream(rawLine.getBytes(StandardCharsets.US_ASCII));\n//\t\t//String[] args= Utils.tokenize(awkScript, \" \").toArray(new String[0]);\n//\t\tString[] args= new Tokenizer(awkScript).tokenize().toArray(new String[0]);\n//\t\t\n//\t\tPrintStream stdout = System.out;\n//\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n//\t\ttry{\n//\t\t\tPrintStream os= new PrintStream(baos);\n//\t\t\tnew org.jawk.Main(args, is, os, System.err);\n//\t\t} catch(Exception e){\n//\t\t\tthrow new IOException();\n//\t\t} finally{\n//\t\t\tSystem.setOut(stdout);\n//\t\t\tis.close();\n//\t\t}\n//\t\tString output = new String(baos.toByteArray(), StandardCharsets.UTF_8);\n//\t\tif(output.trim().isEmpty()){\n//\t\t\treturn false;\n//\t\t} else if(output.trim().equals(rawLine.trim())){\n//\t\t\treturn true;\n//\t\t} else {\n//\t\t\t// Awk output is not empty or equal to input line. Reset awk script and return null\n//\t\t\t// to signal this condition.\n//\t\t\tSystem.err.println(output);\n//\t\t\treturn null;\n//\t\t}\n//\t\t\n//\t}\n\n\t/** Stream the raw line through awk and return true if the output of awk is the same as the input\n\t * line. If awk returns empty output then the line didn't pass the awk filter.\n\t * If output is not empty and not equal to input, return null.\n\t * See tests for behaviour. \n\t * */\n\tpublic static boolean[] passAwkFilter(String[] rawLines, String awkScript) throws IOException {\n\t\t\n\t\tboolean[] results= new boolean[rawLines.length];\n\n\t\tawkScript= awkScript.trim();\n\n\t\tif(awkScript.isEmpty()){\n\t\t\tfor(int i= 0; i < rawLines.length; i++){\n\t\t\t\tresults[i]= true;\n\t\t\t}\n\t\t\treturn results;\n\t\t}\n\n\t\t// * Parse command string into arguments and awk script\n\t\tList<String> args= new Tokenizer(awkScript).tokenize();\n\t\t\n\t\tString script= args.remove(args.size()-1); // 'remove' returns the element removed\n\t\tFile awkFile= Utils.createTempFile(\".asciigenome.\", \".awk\", true);\n\n\t\tBufferedWriter wr= new BufferedWriter(new FileWriter(awkFile));\n\t\twr.write(Track.awkFunc);\n\t\twr.write(script);\n\t\twr.close();\n\t\targs.add(\"-f\");\n\t\targs.add(awkFile.getAbsolutePath());\n\n\t\tByteArrayOutputStream baosIn = new ByteArrayOutputStream();\n\t\tfor (String line : rawLines) {\n\t\t\tbaosIn.write((line+\"\\n\").getBytes());\n\t\t}\n\t\tInputStream is= new ByteArrayInputStream(baosIn.toByteArray());\n\t\tPrintStream stdout = System.out;\n\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n\t\ttry{\n\t\t\tPrintStream os= new PrintStream(baos);\n\t\t\tnew org.jawk.Main(args.toArray(new String[0]), is, os, System.err);\n\t\t} catch(Exception e){\n\t\t\te.printStackTrace();\n\t\t\tthrow new IOException();\n\t\t} finally{\n\t\t\tSystem.setOut(stdout);\n\t\t\tis.close();\n\t\t\tawkFile.delete();\n\t\t}\n\t\t\n\t\tString output[] = new String(baos.toByteArray(), StandardCharsets.US_ASCII).split(\"\\n\");\n\t\tint j= 0;\n\t\tfor(int i=0; i < rawLines.length; i++){\n\t\t\tString inLine= rawLines[i];\n\t\t\tif(output.length > j){\n\t\t\t\tString outLine= output[j];\t\t\t\t\n\t\t\t\tif(inLine.equals(outLine)){\n\t\t\t\t\tresults[i]= true;\n\t\t\t\t\tj++;\n\t\t\t\t} else {\n\t\t\t\t\tresults[i]= false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresults[i]= false;\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\t\n\t/** Right-pad each line in string x with whitespaces. Each line is \n\t * defined by the newline. Each line is padded to become at leas of length size. \n\t * */\n\tpublic static String padEndMultiLine(String x, int size) {\n\n\t\tif(x.isEmpty()){\n\t\t\treturn x;\n\t\t}\n\t\t\n\t\tList<String> split= Splitter.on(\"\\n\").splitToList(x);\n\t\tList<String> mline= new ArrayList<String>(split);\n\t\t\n\t\tfor(int i= 0; i < mline.size(); i++){\n\t\t\tmline.set(i, Strings.padEnd(mline.get(i), size, ' '));\n\t\t}\n\t\treturn Joiner.on(\"\\n\").join(mline);\n\t}\n\n\t/**Parse string region in the form <chrom>:[start[-end]] to a list containing the\n\t * the three elements. See tests for behavior.\n\t * <start> and <end> if present are guaranteed to be parsable to positive int.\n\t * @throws InvalidGenomicCoordsException \n\t * */\n\tpublic static List<String> parseStringCoordsToList(String region) throws InvalidGenomicCoordsException {\n\t\t\n\t\tList<String> coords= new ArrayList<String>(3);\n\t\tcoords.add(null);\n\t\tcoords.add(\"1\");\n\t\tcoords.add(\"536870912\"); // Max size of binning index for tabix is 2^29. See also https://github.com/samtools/htslib/issues/435\n\n\t\tString chrom= StringUtils.substringBeforeLast(region, \":\").trim();\n\t\tcoords.set(0, chrom);\n\t\t\n\t\tString fromTo= StringUtils.substringAfterLast(region, \":\").replaceAll(\",\", \"\").replaceAll(\"\\\\s\", \"\");\n\t\tif(fromTo.isEmpty()){\n\t\t\t// Only chrom given\n\t\t\treturn coords;\n\t\t}\n\t\t\n\t\tif( ! fromTo.replaceFirst(\"-\", \"\").matches(\"[0-9]+\")){\n\t\t\t// If the from-to part does not contain only digits with the exception of the - separator,\n\t\t\t// we assume this is a chrom name containing : and missing the from-to part.\n\t\t\tcoords.set(0, region);\n\t\t\treturn coords;\n\t\t}\n\n\t\tint nsep= StringUtils.countMatches(fromTo, \"-\");\n\t\tInteger from= null;\n\t\tInteger to= null;\n\t\tif(nsep == 0){ \n\t\t\t// Only start position given\n\t\t\tfrom= Integer.parseInt(StringUtils.substringBefore(fromTo, \"-\").trim());\n\t\t\tto= from;\n\t\t} else if(nsep == 1){ // From and To positions given.\n\t\t\tfrom= Integer.parseInt(StringUtils.substringBefore(fromTo, \"-\").trim());\n\t\t\tto= Integer.parseInt(StringUtils.substringAfter(fromTo, \"-\").trim());\n\t\t\tif(from > to || from <= 0 || to <= 0 || (to-from+1) > 536870912){\n\t\t\t\tthrow new InvalidGenomicCoordsException();\t\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new InvalidGenomicCoordsException();\n\t\t}\n\t\tcoords.set(1, from.toString());\n\t\tcoords.set(2, to.toString());\n\n\t\treturn coords;\n\t}\n\n\t/** Prepare SamReader from local bam or URL bam */\n\tpublic static SamReader getSamReader(String workFilename) throws MalformedURLException {\n\t\tUrlValidator urlValidator = new UrlValidator();\n\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\tSamReader samReader;\n\t\tif(urlValidator.isValid(workFilename)){\n\t\t\tsamReader = srf.open(SamInputResource.of(new URL(workFilename)).index(new URL(workFilename + \".bai\")));\n\t\t} else {\n\t\t\tsamReader= srf.open(new File(workFilename));\n\t\t}\n\t\treturn samReader;\n\t}\n\n\t/**Return the indexes of the printable characters interspersed in ansi formatting \n\t * MEMO: The sequence \\033 is NOT four characters. It's just one!\n\t * */\n\tpublic static List<Integer> indexOfCharsOnFormattedLine(String fmtString) {\n\n\t\tList<Integer> idx= new ArrayList<Integer>();\n\t\t// Start assuming that each char in input string is a printable char, not part of ANSI code.\n\t\tfor(int i= 0; i < fmtString.length(); i++){\n\t\t\tidx.add(i);\n\t\t}\n\t\t\n\t\tMatcher m= Pattern.compile(\"\\\\033\\\\[[;\\\\d]*m\").matcher(fmtString);\n\t\twhile(m.find()){\n\t\t\t// Now remove from the index list the characters that are part of the escape\n\t\t\tfor(int i= m.start(); i < m.end(); i++){\n\t\t\t\tint del= idx.indexOf(i);\n\t\t\t\tidx.remove(del);\n\t\t\t}\n\t\t}\n\t\treturn idx;\n\t}\n\n\t/**Get terminal width. \n\t * */\n\tpublic static int getTerminalWidth() throws IOException {\n\t\tint terminalWidth= jline.TerminalFactory.get().getWidth(); \n\t\tif(terminalWidth <= 0){\n\t\t\tterminalWidth= 80;\n\t\t}\n\t\treturn terminalWidth;\n\t}\n\n\t/**Get VCFHeader from the given source which could be URL or local file.*/\n\tpublic static VCFHeader getVCFHeader(String source) throws MalformedURLException{\n\t\tVCFHeader vcfHeader;\n\t\tif( Utils.urlFileExists(source) ){\n\t\t\tURL url= new URL(source);\n\t\t\tAbstractFeatureReader<VariantContext, LineIterator> reader = AbstractFeatureReader.getFeatureReader(url.toExternalForm(), new VCFCodec(), false);\n\t\t\tvcfHeader = (VCFHeader) reader.getHeader();\n\t\t} else {\n\t\t\tVCFFileReader reader = new VCFFileReader(new File(source), false); // Set requiredIndex false!\n\t\t\tvcfHeader= reader.getFileHeader();\n\t\t\treader.close();\n\t\t}\n\t\treturn vcfHeader;\n\t}\n\t\n\tpublic static VCFHeaderVersion getVCFHeaderVersion(VCFHeader vcfHeader){\n\t\tIterator<VCFHeaderLine> iter = vcfHeader.getMetaDataInInputOrder().iterator();\n\t\twhile(iter.hasNext()){\n\t\t\tVCFHeaderLine hl = iter.next();\n\t\t\tif(hl.getKey().equals(\"fileformat\")){\n\t\t\t\treturn VCFHeaderVersion.toHeaderVersion(hl.getValue());\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Sort and index input sam or bam.\n\t * @throws IOException \n\t * */\n\tpublic static void sortAndIndexSamOrBam(String inSamOrBam, String sortedBam, boolean deleteOnExit) throws IOException {\n\n\t\t/* ------------------------------------------------------ */\n\t\t/* This chunk prepares SamReader from local bam or URL bam */\n\t\tUrlValidator urlValidator = new UrlValidator();\n\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\tSamReader samReader;\n\t\tif(urlValidator.isValid(inSamOrBam)){\n\t\t\tsamReader = SamReaderFactory.makeDefault().open(SamInputResource.of(new URL(inSamOrBam)));\n\t\t} else {\n\t\t\tsamReader= srf.open(new File(inSamOrBam));\n\t\t}\n\t\t/* ------------------------------------------------------ */\n\t\t\n\t\tsamReader.getFileHeader().setSortOrder(SortOrder.coordinate);\n\t\t\n\t\tFile out= new File(sortedBam);\n\t\tif(deleteOnExit){\n\t\t\tout.deleteOnExit();\n\t\t\tFile idx= new File(out.getAbsolutePath().replaceAll(\"\\\\.bam$\", \"\") + \".bai\");\n\t\t\tidx.deleteOnExit();\n\t\t}\n\t\t\n\t\tSAMFileWriter outputSam= new SAMFileWriterFactory()\n\t\t\t\t.setCreateIndex(true)\n\t\t\t\t.makeSAMOrBAMWriter(samReader.getFileHeader(), false, out);\n\n\t\tfor (final SAMRecord samRecord : samReader) {\n\t\t\toutputSam.addAlignment(samRecord);\n }\n\t\tsamReader.close();\n\t\toutputSam.close();\n\t}\n\n\t/**True if SAM read names are equal. Read name strings are parsed to remove\n\t * parts that are not part of the name. \n\t * */\n\tpublic static boolean equalReadNames(String readName, String readName2) {\n\t\treturn cleanSamReadName(readName).equals(cleanSamReadName(readName2));\n\t}\n\tprivate static String cleanSamReadName(String readName){\n\t\tint blank= readName.indexOf(\" \");\n\t\tif(blank >= 0){\n\t\t\treadName= readName.substring(0, blank);\n\t\t}\n\t\tif(readName.length() > 2 && (readName.endsWith(\"/1\") || readName.endsWith(\"/2\"))){\n\t\t\treadName= readName.substring(0, readName.length()-2);\n\t\t}\n\t\treturn readName;\n\t}\n\n\tpublic static List<String> vcfHeaderToStrings(VCFHeader header) {\n\n\t File fakeVCFFile;\n\t List<String> str= new ArrayList<String>();\n\t try {\n\t \tfakeVCFFile = Utils.createTempFile(\".vcfheader\", \".vcf\", true);\n\t\t final VariantContextWriter writer = new VariantContextWriterBuilder()\n\t\t .setOutputFile(fakeVCFFile)\n\t\t .setReferenceDictionary(header.getSequenceDictionary())\n\t\t .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.WRITE_FULL_FORMAT_FIELD))\n\t\t .build();\n\t\t writer.writeHeader(header);\n\t\t writer.close();\n\t\t BufferedReader br= new BufferedReader(new FileReader(fakeVCFFile));\n\t\t String line= br.readLine();\n\t\t while(line != null){\n\t\t \tstr.add(line);\n\t\t \tline= br.readLine();\n\t\t }\n\t\t br.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn str;\n\t}\n\n\t/**Parse string x and round the numbers it contains to d decimal places.\n\t * Typically, x is a raw line read from BED, GFF whatever. What makes a number\n\t * is guessed from context without too much sophistication.\n\t * With d < 0, do nothing and return x as it is. \n\t * */\n\tpublic static String roundNumbers(final String x, int d, TrackFormat trackFormat) {\n\t\tif(d < 0){\n\t\t\treturn x;\n\t\t}\n\t\t// Capture any substring that looks like a number with decimals. Integers are left untouched.\n\t\tPattern p = Pattern.compile(\"-?\\\\d+\\\\.\\\\d+\"); \n\t\tString xm= x;\n\t\tif(trackFormat.equals(TrackFormat.GTF)){\n\t\t\t// We consider \"123.123\" in double quotes as a number to comply with cufflinks/StringTie. \n\t\t\txm= xm.replaceAll(\"\\\"\", \" \");\n\t\t}\n\t\t\n\t\tMatcher m = p.matcher(xm);\n\t\tList<Integer> starts= new ArrayList<Integer>();\n\t\tList<Integer> ends= new ArrayList<Integer>();\n\t\tList<String> repls= new ArrayList<String>();\n\t\twhile (m.find()) {\n\t\t\tif(m.group().replace(\"-\", \"\").startsWith(\"00\")){\n\t\t\t\t// We treat something like \"000.123\" as NaN. \n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// If these chars precede the captured string, then the string may be an actual number \n\t\t\tif(m.start() == 0 || xm.charAt(m.start()-1) == '=' \n\t\t\t\t\t || xm.charAt(m.start()-1) == ' '\n\t\t\t\t\t || xm.charAt(m.start()-1) == ','\n\t\t\t\t\t || xm.charAt(m.start()-1) == '\\t'){\n\t\t\t\t// If these chars follow the captured string, then the string is an actual number\n\t\t\t\tif(m.end() == xm.length() || xm.charAt(m.end()) == ';'\n\t\t\t\t\t\t\t|| xm.charAt(m.end()) == ' ' \n\t\t\t\t\t\t\t|| xm.charAt(m.end()) == ','\n\t\t\t\t\t\t\t|| xm.charAt(m.end()) == '\\t'){\n\t\t\t\t\tDecimalFormat format;\n\t\t\t\t\tif(d == 0){\n\t\t\t\t\t\tformat = new DecimalFormat(\"0\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tformat = new DecimalFormat(\"0.\" + StringUtils.repeat(\"#\", d));\n\t\t\t\t\t}\n\t\t\t\t\tString newval= format.format(Double.valueOf(m.group()));\n\t\t\t\t\tstarts.add(m.start());\n\t\t\t\t\tends.add(m.end());\n\t\t\t\t\trepls.add(newval);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(starts.size() == 0){\n\t\t\treturn x;\n\t\t}\n\t\tStringBuilder formattedX= new StringBuilder();\n\t\tfor(int i= 0; i < starts.size(); i++){\n\t\t\tif(i == 0){\n\t\t\t\tformattedX.append(x.substring(0, starts.get(i)));\t\n\t\t\t} else {\n\t\t\t\tformattedX.append(x.substring(ends.get(i-1), starts.get(i)));\n\t\t\t}\n\t\t\tformattedX.append(repls.get(i));\n\t\t}\n\t\tformattedX.append(x.substring(ends.get(ends.size()-1)));\n\t\treturn formattedX.toString();\n\t}\n\n\t/**Winsorise vector x. Adapted from https://www.r-bloggers.com/winsorization/.\n\t * */\n\tpublic static List<Float> winsor2(List<Float> x, double multiple) {\n\t\t\t\t/*\n\t\t\t\twinsor2<- function (x, multiple=3)\n\t\t\t\t{\n\t\t\t\t med <- median(x)\n\t\t\t\t y <- x - med\n\t\t\t\t sc <- mad(y, center=0) * multiple\n\t\t\t\t y[ y > sc ] <- sc\n\t\t\t\t y[ y < -sc ] <- -sc\n\t\t\t\t y + med\n\t\t\t\t}\n\t\t\t\t*/\n\t\tif(multiple <= 0){\n\t\t\tthrow new ArithmeticException(); \n\t\t}\n\t\tDescriptiveStatistics stats = new DescriptiveStatistics();\n\t\tfor(float z : x){\n\t\t\tstats.addValue(z);\n\t\t}\n\t\tfloat median = (float)stats.getPercentile(50);\n\t\tList<Float> y= new ArrayList<Float>(x);\n\t\tfor(int i= 0; i < x.size(); i++){\n\t\t\ty.set(i, x.get(i) - median);\n\t\t}\n\t\tfloat sc= (float) (Utils.medianAbsoluteDeviation(y, 0) * multiple);\n\t\tfor(int i= 0; i < y.size(); i++){\n\t\t\tif(y.get(i) > sc){\n\t\t\t\ty.set(i, sc);\n\t\t\t}\n\t\t\telse if(y.get(i) < -sc){\n\t\t\t\ty.set(i, -sc);\n\t\t\t}\n\t\t\ty.set(i, y.get(i) + median);\n\t\t}\n\t\treturn y;\n\t}\n\t/** Translated from R function mad(x, center, constant= 1.4826, na.rm= FALSE, low= FALSE, high= FALSE). \n\t * */\n\tprivate static float medianAbsoluteDeviation(List<Float> x, float center) {\n\t\tDescriptiveStatistics stats = new DescriptiveStatistics();\n\t\tfor(int i= 0; i < x.size(); i++){\n\t\t\tstats.addValue(Math.abs(x.get(i) - center));\n\t\t}\n\t\tfloat median= (float)stats.getPercentile(50);\n\t\treturn (float)1.4826 * median;\n\t}\n\n\t/**Interpret x to return boolean. Similar to Boolean.valueOf() but more\n\t * flexible. See code and tests for exact behaviour. Case insensitive. \n\t * Throw exception otherwise.\n\t * See tests. \n\t * */\n\tpublic static Boolean asBoolean(String x) {\n\n\t\tif(x == null || x.trim().isEmpty()){\n\t\t\tthrow new IllegalArgumentException();\n\t\t}\n\n\t\tx= x.trim().toLowerCase();\n\t\tif(\"true\".matches(\"^\" + x + \".*\") || \"yes\".matches(\"^\" + x + \".*\") || x.equals(\"on\")){\n\t\t\treturn true;\n\t\t}\n\t\tif(\"false\".matches(\"^\" + x + \".*\") || \"no\".matches(\"^\" + x + \".*\") || x.equals(\"off\")){\n\t\t\treturn false;\n\t\t}\n\t\tthrow new IllegalArgumentException();\n\t}\n\t\n\tpublic static List<String> suggestCommand(String hint, List<String> options){\n\t\tif(hint.length() < 3){\n\t\t\treturn new ArrayList<>();\n\t\t}\n\t\thint= hint.toLowerCase();\n\n\t\tMap<Integer, List<String>> candidates= new TreeMap<Integer, List<String>>();\n\t\t\n\t\tfor(String candidate : options){\n\t\t\tif(candidate.length() < 3){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString x= candidate.toLowerCase();\n\t\t\tint nm;\n\t\t\tif(x.length() >= 3 && hint.length() >= 3 && (x.contains(hint) || hint.contains(x))){\n\t\t\t\tnm= 0;\n\t\t\t} else {\n\t\t\t\tnm= levenshtein(hint, candidate.toLowerCase());\n\t\t\t}\n\t\t\tif(candidates.containsKey(nm)){\n\t\t\t\tcandidates.get(nm).add(candidate);\n\t\t\t} else {\n\t\t\t\tList<String> tier= new ArrayList<String>();\n\t\t\t\ttier.add(candidate);\n\t\t\t\tcandidates.put(nm, tier);\n\t\t\t}\n\t\t}\n\t\t\n\t\tjava.util.Map.Entry<Integer, List<String>> out = candidates.entrySet().iterator().next();\n\t\treturn out.getValue();\n\t}\n\t\n /**\n * Calculates Damerau–Levenshtein distance between string {@code a} and\n * {@code b} with given costs.\n * \n * @param a\n * String\n * @param b\n * String\n * @return Damerau–Levenshtein distance between {@code a} and {@code b}\n * \n * Method from argparse4j\n */\n private static int levenshtein(String a, String b) {\n \t\n \t final int SUBSTITUTION_COST = 2;\n \t final int SWAP_COST = 0;\n \t final int DELETION_COST = 4;\n \t final int ADDITION_COST = 1;\n \t\n int aLen = a.length();\n int bLen = b.length();\n int[][] dp = new int[3][bLen + 1];\n for (int i = 0; i <= bLen; ++i) {\n dp[1][i] = i;\n }\n for (int i = 1; i <= aLen; ++i) {\n dp[0][0] = i;\n for (int j = 1; j <= bLen; ++j) {\n dp[0][j] = dp[1][j - 1]\n + (a.charAt(i - 1) == b.charAt(j - 1) ? 0 : SUBSTITUTION_COST);\n if (i >= 2 && j >= 2 && a.charAt(i - 1) != b.charAt(j - 1)\n && a.charAt(i - 2) == b.charAt(j - 1)\n && a.charAt(i - 1) == b.charAt(j - 2)) {\n dp[0][j] = Math.min(dp[0][j], dp[2][j - 2] + SWAP_COST);\n }\n dp[0][j] = Math.min(dp[0][j],\n Math.min(dp[1][j] + DELETION_COST, dp[0][j - 1] + ADDITION_COST));\n }\n int[] temp = dp[2];\n dp[2] = dp[1];\n dp[1] = dp[0];\n dp[0] = temp;\n }\n return dp[1][bLen];\n }\n\n\tpublic static boolean isOverlapping(int xStart, int xEnd, int yStart, int yEnd) {\n\t\tif(xStart > xEnd || yStart > yEnd){\n\t\t\tthrow new ArithmeticException();\n\t\t}\n\t\tif(xEnd < yStart || yEnd < xStart){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic static String reformatFileName(String filename, boolean absolute) {\n\t\tUrlValidator urlValidator= new UrlValidator();\n\t\tif(urlValidator.isValid(filename)){\n\t\t\treturn filename;\n\t\t}\n\t\tPath absfilename= Paths.get(filename).toAbsolutePath();\n\t\tif(absolute) {\n\t\t\treturn absfilename.toString();\n\t\t}\n\t\tPath cwd= Paths.get(System.getProperty(\"user.dir\"));\n\t\tPath relative= cwd.relativize(absfilename);\n\t\treturn relative.toString();\n\t}\n\n\t/**rawrecs is an array of raw records and regex is either a regex or \n\t * an awk script (autodetermined). Return an array of booleans for whether \n\t * each record is matched by regex.\n\t * @throws IOException \n\t * */\n\tpublic static boolean[] matchByAwkOrRegex(String[] rawLines, String regex) throws IOException {\n\t\tboolean isAwk= false;\n\t\tif(Pattern.compile(\"\\\\$\\\\d|\\\\$[A-Z]\").matcher(regex).find()) {\n\t\t\t// We assume that if regex contains a '$' followed by digit or letter\n\t\t\t// we have an awk script since that would be a very unlikely regex.\n\t\t\t// Could we have an awk script not containing '$'? Unlikely but maybe possible\n\t\t\tisAwk= true;\n\t\t}\n\n\t\tboolean[] matched= new boolean[rawLines.length];\n\t\tif(isAwk) {\n\t\t\tregex= quote(regex);\n//\t\t\tif(! regex.trim().startsWith(\"'\") && ! regex.trim().endsWith(\"'\")) {\n//\t\t\t\tregex= \"'\" + regex + \"'\";\n//\t\t\t}\n\t\t\tmatched= Utils.passAwkFilter(rawLines, regex);\n\t\t}\n\t\telse {\n\t\t\tfor(int i= 0; i < matched.length; i++) {\n\t\t\t\tmatched[i]= Pattern.compile(regex).matcher(rawLines[i]).find();\n\t\t\t}\n\t\t}\n\t\treturn matched;\n\t}\n\t\n\t/**Add quotes around x, if necessary, so that it gets tokenized in a single string*/\n\tpublic static String quote(String x) {\n\t\tif((x.startsWith(\"'\") && x.endsWith(\"'\")) || (x.startsWith(\"\\\"\") && x.endsWith(\"\\\"\"))) {\n\t\t\t// No need to quote\n\t\t\treturn x;\n\t\t}\n\t\t// We need to quote the awk script using a quoting string not used inside the script itself.\n\t\t// This is a pretty bad hack. You should store the awk command as a list rather than a string\n\t\t// split and joined multiple times!\n\t\tString q= \"\";\n\t\tif( ! x.contains(\"'\")) {\n\t\t\tq= \"'\";\n\t\t}\n\t\telse if(! x.contains(\"\\\"\")) {\n\t\t\tq= \"\\\"\";\n\t\t}\n\t\telse if(! x.contains(\"'''\")) {\n\t\t\tq= \"'''\";\n\t\t}\n\t\telse if(! x.contains(\"\\\"\\\"\\\"\")) {\n\t\t\tq= \"\\\"\\\"\\\"\";\n\t\t}\n\t\telse {\n\t\t\tthrow new RuntimeException();\n\t\t}\n\t\treturn q + x + q;\n\t}\n\n\tpublic static TrackFormat guessTrackType(String file) {\n\t\t\n\t\ttry {\n\t\t\tSamReaderFactory srf=SamReaderFactory.make();\n\t\t\tsrf.validationStringency(ValidationStringency.SILENT);\n\t\t\tSamReader samReader = srf.open(new File(file));\n\t\t\tSAMRecordIterator iter = samReader.iterator();\n\t\t\tint n= 0;\n\t\t\twhile(iter.hasNext() && n < 1000) {\n\t\t\t\titer.next();\n\t\t\t\tn++;\n\t\t\t}\n\t\t\treturn TrackFormat.BAM;\n\t\t} catch(Exception e) {\n\t\t\t// e.printStackTrace();\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tFeatureList gff = GFF3Reader.read(file);\n\t\t\tIterator<FeatureI> iter = gff.iterator();\n\t\t\tint n= 0;\n\t\t\twhile(iter.hasNext() && n < 1000) {\n\t\t\t\titer.next();\n\t\t\t\tn++;\n\t\t\t}\n\t\t\treturn TrackFormat.GFF;\n\t\t} catch(Exception e) {\n\t\t\t// e.printStackTrace();\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tVCFFileReader reader = new VCFFileReader(new File(file), false);\n\t\t\tCloseableIterator<VariantContext> iter = reader.iterator();\n\t\t\tint n= 0;\n\t\t\twhile(iter.hasNext() && n < 1000) {\n\t\t\t\ttry {\n\t\t\t\t\titer.next();\n\t\t\t\t} catch(IllegalArgumentException e) {\n\t\t\t\t\t// Forgive \"-\" as an allele\n\t\t\t\t}\n\t\t\t\tn++;\n\t\t\t}\n\t\t\treader.close();\n\t\t\treturn TrackFormat.VCF;\n\t\t} catch(Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t} \n}", "public class MakeTabixIndex {\n\n\tprivate File sqliteFile;\n\t\n\t/** Sort, block compress and index the input with format fmt to the given output file.\n\t * Input is either a local file, possibly compressed, or a URL.\n\t * @throws InvalidRecordException \n\t * @throws IOException \n\t * @throws SQLException \n\t * @throws ClassNotFoundException \n\t * */\n\tpublic MakeTabixIndex(String intab, File bgzfOut, TabixFormat fmt) throws IOException, InvalidRecordException, ClassNotFoundException, SQLException{\n\t\t\n\t\tFile tmp = Utils.createTempFile(\".asciigenome\", \"makeTabixIndex.tmp.gz\", true);\n\t\tFile tmpTbi= new File(tmp.getAbsolutePath() + FileExtensions.TABIX_INDEX);\n\t\ttmpTbi.deleteOnExit();\n\t\t\n\t\ttry{\n\t\t\t// Try to block compress and create index assuming the file is sorted\n\t\t\tblockCompressAndIndex(intab, tmp, fmt);\n\t\t} catch(Exception e){\n\t\t\t// If intab is not sorted, sort it first.\n\t\t\tFile sorted= Utils.createTempFile(\".asciigenome.\", \".sorted.tmp\", true);\n\t\t\tsortByChromThenPos(intab, sorted, fmt);\n\t\t\tblockCompressAndIndex(sorted.getAbsolutePath(), tmp, fmt);\n\t\t\tFiles.delete(Paths.get(sorted.getAbsolutePath()));\n\t\t}\n\t\t\n\t\t// This renaming and the use of File tmp allows to block compress and index an input file in place.\n\t\t// Original intab file is overwritten of course!\n\t\tif(bgzfOut.exists()){\n\t\t\tFiles.delete(Paths.get(bgzfOut.getAbsolutePath()));\n\t\t}\n\t\tFiles.move(Paths.get(tmp.getAbsolutePath()), Paths.get(bgzfOut.getAbsolutePath()));\n\n\t\tFile bgzfOutTbi= new File(bgzfOut.getAbsolutePath() + FileExtensions.TABIX_INDEX);\n\t\tif(bgzfOutTbi.exists()){\n\t\t\tFiles.delete(Paths.get(bgzfOutTbi.getAbsolutePath()));\n\t\t}\n\t\tFiles.move(Paths.get(tmpTbi.getAbsolutePath()), Paths.get(bgzfOutTbi.getAbsolutePath()));\n\t\t\n\t}\n\n\t/**\n\t * Block compress input file and create associated tabix index. \n\t * @throws IOException \n\t * @throws InvalidRecordException \n\t * */\n\tprivate void blockCompressAndIndex(String intab, File bgzfOut, TabixFormat fmt) throws IOException, InvalidRecordException {\n\t\t\t\t\n\t\tBlockCompressedOutputStream writer = new BlockCompressedOutputStream(bgzfOut);\n\t\tlong filePosition= writer.getFilePointer();\n\t\t\t\n\t\tTabixIndexCreator indexCreator=new TabixIndexCreator(fmt);\n\t\t\n\t\t// boolean first= true;\n\t\t\n\t\t// This is relevant to vcf files only: Prepare header and codec\n\t\t// ------------------------------------------------------------\n\t\tVCFHeader vcfHeader= null;\n\t\tVCFCodec vcfCodec= null;\n\t\tif(fmt.equals(TabixFormat.VCF)){\n\t\t\ttry{\n\t\t\t\tVCFFileReader vcfr= new VCFFileReader(new File(intab), false);\n\t\t\t vcfHeader= vcfr.getFileHeader();\n\t\t\t vcfr.close();\n\t\t\t} catch(MalformedFeatureFile e){\n\t\t\t\tvcfHeader= new VCFHeader();\n\t\t\t}\n\t\t\tvcfCodec= new VCFCodec();\n\t\t\tvcfCodec.setVCFHeader(vcfHeader, Utils.getVCFHeaderVersion(vcfHeader));\n\t\t}\n\t\t// ------------------------------------------------------------\n\n\t\tint nWarnings= 10;\n\t\tLineIterator lin= utils.IOUtils.openURIForLineIterator(intab);\n\t\twhile(lin.hasNext()){\n\t\t\t\n\t\t\tString line = lin.next().trim();\n\t\t\t\n\t\t\ttry{\n\t\t\t\tif(line.isEmpty() || line.startsWith(\"track \")){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(line.startsWith(\"#\")){\n\t\t\t\t\twriter.write((line + \"\\n\").getBytes());\n\t\t\t\t\tfilePosition = writer.getFilePointer();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif(line.startsWith(\"##FASTA\")){\n\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\n\n\t\t\t\taddLineToIndex(line, indexCreator, filePosition, fmt, vcfHeader, vcfCodec);\n\t\t\t\t\n\t\t\t\twriter.write(line.getBytes());\n\t\t\t\twriter.write('\\n');\n\t\t\t\tfilePosition = writer.getFilePointer();\n\t\t\t} catch(Exception e){\n\t\t\t\tif(e.getMessage().contains(\"added out sequence of order\") || e.getMessage().contains(\"Features added out of order\")){\n\t\t\t\t\t// Get a string marker for out-of-order from htsjdk/tribble/index/tabix/TabixIndexCreator.java \n\t\t\t\t\twriter.close();\n\t\t\t\t\tthrow new InvalidRecordException();\n\t\t\t\t}\n\t\t\t\tif(nWarnings >= 0){\n\t\t\t\t\tSystem.err.println(\"Warning: \" + e.getMessage() + \". Skipping:\\n\" + line);\n\t\t\t\t}\n\t\t\t\tif(nWarnings == 0){\n\t\t\t\t\tSystem.err.println(\"Additional warnings will not be show.\");\n\t\t\t\t}\n\t\t\t\tnWarnings--;\n\t\t\t}\n\t\t}\n\n\t\twriter.flush();\n\t\t\n\t\tIndex index = indexCreator.finalizeIndex(writer.getFilePointer());\n\t\tindex.writeBasedOnFeatureFile(bgzfOut);\n\t\twriter.close();\n\t\tCloserUtil.close(lin);\n\t}\n\n\t/** Set vcfHeader and vcfCodec to null if reading non-vcf line.\n\t * */\n\tprivate void addLineToIndex(String line, TabixIndexCreator indexCreator, long filePosition, TabixFormat fmt, VCFHeader vcfHeader, VCFCodec vcfCodec) throws InvalidRecordException {\n\n\t\tif(fmt.equals(TabixFormat.BED)){\n\t\t\t\n\t\t\tBedLineCodec bedCodec= new BedLineCodec();\n\t\t\tBedLine bed = bedCodec.decode(line);\n\t\t\tindexCreator.addFeature(bed, filePosition);\n\t\t\n\t\t} else if(fmt.equals(TabixFormat.GFF)){\n\t\t\tGtfLine gtf= new GtfLine(line.split(\"\\t\"));\n\t\t\tindexCreator.addFeature(gtf, filePosition);\n\t\t\n\t\t} else if(fmt.equals(TabixFormat.VCF)) {\n\n\t\t\tVariantContext vcf = vcfCodec.decode(line);\n\t\t\tindexCreator.addFeature(vcf, filePosition);\n\t\t\t\n\t\t} else {\n\t\t\tSystem.err.println(\"Unexpected TabixFormat: \" + fmt.sequenceColumn + \" \" + fmt.startPositionColumn);\n\t\t\tthrow new InvalidRecordException();\n\t\t}\t\n\t}\n\t\n\t/** Sort file by columns chrom (text) and pos (int). chromIdx and posIdx are 1-based \n\t * indexes for the chrom and pos column. For bed use 1 and 2 respectively. For use GTF/GFF 1 and 4.\n\t * Comment lines, starting with #, are returned as they are. Reading stops if the line ##FASTA is found.\n\t * */\n\tprivate void sortByChromThenPos(String unsorted, File sorted, TabixFormat fmt) throws SQLException, InvalidRecordException, IOException, ClassNotFoundException{\n\n\t\tint chromIdx= 1;\n\t\tint posIdx= 2;\n\t\tif(fmt.equals(TabixFormat.BED)){\n\t\t\t//\n\t\t} else if(fmt.equals(TabixFormat.GFF)){\n\t\t\tposIdx= 4;\n\t\t} else if(fmt.equals(TabixFormat.VCF)){\n\t\t\tposIdx= 2;\n\t\t} else {\n\t\t\tSystem.err.println(\"Invalid format found\");\n\t\t\tthrow new InvalidRecordException();\n\t\t}\n\t\t\n\t\tConnection conn= null;\n\t\ttry{\n\t\t\tthis.sqliteFile= Utils.createTempFile(\".asciigenome.\", \".tmp.sqlite\", true);\n\t\t\tconn= this.createSQLiteDb(this.sqliteFile, \"data\");\n\t\t} catch(SQLiteException e){\n\t\t\tthis.sqliteFile= File.createTempFile(\".asciigenome.\", \".tmp.sqlite\");\n\t\t\tthis.sqliteFile.deleteOnExit();\n\t\t\tconn= this.createSQLiteDb(this.sqliteFile, \"data\");\n\t\t}\n\t\tPreparedStatement stmtInsert= conn.prepareStatement(\"INSERT INTO data (contig, pos, posEnd, line) VALUES (?, ?, ?, ?)\");\n\t\n\t\tBufferedReader br= Utils.reader(unsorted);\n\t\tBufferedWriter wr= new BufferedWriter(new FileWriter(sorted));\n\t\tString line;\n\t\twhile((line = br.readLine()) != null){\n\t\t\tif(line.trim().startsWith(\"##FASTA\")){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif(line.trim().startsWith(\"#\")){\n\t\t\t\twr.write(line + \"\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tString[] tabs= line.split(\"\\t\"); \n\t\t\tstmtInsert.setString(1, tabs[chromIdx-1]);\n\t\t\tstmtInsert.setInt(2, Integer.parseInt(tabs[posIdx-1]));\n\t\t\tif(fmt.equals(TabixFormat.VCF)){\n\t\t\t\tstmtInsert.setInt(3, 0);\n\t\t\t} else {\n\t\t\t\tstmtInsert.setInt(3, Integer.parseInt(tabs[posIdx]));\n\t\t\t}\n\t\t\tstmtInsert.setString(4, line.replaceAll(\"\\n$\", \"\"));\n\t\t\tstmtInsert.executeUpdate();\n\t\t}\n\t\tstmtInsert.close();\n\t\tbr.close();\n\n\t\tPreparedStatement stmtSelect= conn.prepareStatement(\"SELECT * FROM data ORDER BY contig, pos, posEnd\");\n\t\t\n\t\tResultSet rs= stmtSelect.executeQuery();\n\t\t\n\t\twhile(rs.next()){\n\t\t\twr.write(rs.getString(\"line\") + \"\\n\");\n\t\t}\n\t\tconn.commit();\n\t\tstmtSelect.close();\n\t\twr.close();\n\t\tconn.close();\n\t\tFiles.delete(Paths.get(this.sqliteFile.getAbsolutePath()));\n\t\t\n\t}\n\n\t/** Create a tmp sqlite db and return the connection to it. \n\t * @throws SQLException \n\t */\n\tprivate Connection createSQLiteDb(File sqliteFile, String tablename) throws SQLException {\n\t\t// this.sqliteFile= Utils.createTempFile(\".asciigenome.\", \".tmp.sqlite\");\n\t \n\t try {\n\t\t\tClass.forName(\"org.sqlite.JDBC\");\n\t\t} catch (ClassNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tConnection conn = DriverManager.getConnection(\"jdbc:sqlite:\" + this.sqliteFile);\n Statement stmt = conn.createStatement();\n String sql = \"CREATE TABLE \" + tablename + \n \t\t \" (\" +\n \"contig text, \" +\n \t\t \"pos int,\" +\n \t\t \"posEnd int,\" +\n \"line text\" + // This is the row line as read from input file\n \")\"; \n stmt.executeUpdate(sql);\n stmt= conn.createStatement();\n\n // http://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite\n stmt.execute(\"PRAGMA journal_mode = OFF\"); // This is not to leave tmp journal file o disk\n\t\tconn.setAutoCommit(false); // This is important: By default each insert is committed \n\t\t\t\t\t \t\t // as it is executed, which is slow. Let's commit in bulk at the end instead.\n\t\tstmt.close();\n return conn;\n\t}\n}" ]
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.SQLException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import exceptions.InvalidColourException; import exceptions.InvalidGenomicCoordsException; import exceptions.InvalidRecordException; import htsjdk.samtools.util.SequenceUtil; import htsjdk.tribble.index.tabix.TabixFormat; import samTextViewer.GenomicCoords; import samTextViewer.Utils; import sortBgzipIndex.MakeTabixIndex;
package tracks; public class TrackSeqRegex extends TrackIntervalFeature { private String seqRegex= "a^"; // Match nothing final private String noRe= "a^"; private boolean isCaseSensitive= false; private boolean isIupac= false; public TrackSeqRegex(GenomicCoords gc) throws ClassNotFoundException, IOException, InvalidGenomicCoordsException, InvalidRecordException, SQLException{ super(gc); this.setGc(gc); this.setFilename(new File(gc.getFastaFile()).getAbsolutePath()); this.setWorkFilename(new File(gc.getFastaFile()).getAbsolutePath()); this.setTrackTag(new File(gc.getFastaFile()).getName()); this.setHideTrack(true); this.setTrackFormat(TrackFormat.BED); } @Override /** Find regex matches and update the screen map. See alos parent method. * */ public void update() throws ClassNotFoundException, IOException, InvalidGenomicCoordsException, InvalidRecordException, SQLException{ this.findRegex(); for(IntervalFeature ift : this.getIntervalFeatureList()){ ift.mapToScreen(this.getGc().getMapping()); } } /** * Find regex matches in current genomic interval and update the IntervalFeature set and list. * */ private void findRegex() throws IOException, InvalidGenomicCoordsException, ClassNotFoundException, InvalidRecordException, SQLException{ // Find matches // ============ Pattern pattern= Pattern.compile(this.seqRegex, Pattern.CASE_INSENSITIVE); if(this.isCaseSensitive){ pattern= Pattern.compile(this.seqRegex); } byte[] seq= this.getGc().getSequenceFromFasta(); Matcher matcher = pattern.matcher(new String(seq)); // One list for matches on forward, one for reverse, one for palindromic Set<String> regionListPos= new HashSet<String>(); Set<String> regionListNeg= new HashSet<String>(); Set<String> regionListPalind= new HashSet<String>(); // Forward match while (matcher.find()) { int matchStart= this.getGc().getFrom() + matcher.start() - 1; int matchEnd= this.getGc().getFrom() + matcher.end() - 1; String reg= this.getGc().getChrom() + "\t" + matchStart + "\t" + matchEnd + "\t" + this.trimMatch(matcher.group(), 100); regionListPos.add(reg); } // Reverse comp match SequenceUtil.reverseComplement(seq); matcher = pattern.matcher(new String(seq)); while (matcher.find()) { int matchStart= this.getGc().getTo() - matcher.end(); int matchEnd= this.getGc().getTo() - matcher.start(); String reg= this.getGc().getChrom() + "\t" + matchStart + "\t" + matchEnd + "\t" + this.trimMatch(matcher.group(), 100); if(regionListPos.contains(reg)){ regionListPos.remove(reg); regionListPalind.add(reg); } else { regionListNeg.add(reg); } } // Prepare tmp file // ================ String tmpname= Utils.createTempFile(".asciigenome.regexMatchTrack", ".tmp.bed", true).getAbsolutePath(); // This is a hack: Copy the newly created tmp file to another file. This overcomes some // permission (?) problems later with the tabix indexing. String regexMatchFile= tmpname.replaceAll("\\.tmp\\.bed$", ".bed"); FileUtils.copyFile(new File(tmpname), new File(regexMatchFile)); new File(tmpname).delete(); new File(regexMatchFile).deleteOnExit(); BufferedWriter wr= new BufferedWriter(new FileWriter(new File(regexMatchFile))); // Write sets of matches to file // ============================= for(String reg : regionListPos){ reg += "\t.\t+\n"; if(this.featureIsVisible(reg)){ wr.write(reg); } } for(String reg : regionListNeg){ reg += "\t.\t-\n"; if(this.featureIsVisible(reg)){ wr.write(reg); } } for(String reg : regionListPalind){ reg += "\t.\t.\n"; if(this.featureIsVisible(reg)){ wr.write(reg); } } wr.close(); // Compress, index, read back as list of IntervalFeatures // ====================================================== File regexMatchBgzip= new File(regexMatchFile + ".gz"); File regexMatchIndex= new File(regexMatchFile + ".gz.tbi"); regexMatchBgzip.deleteOnExit(); regexMatchIndex.deleteOnExit();
new MakeTabixIndex(regexMatchFile, regexMatchBgzip, TabixFormat.BED);
5
OneNoteDev/Android-REST-API-Explorer
app/src/main/java/com/microsoft/o365_android_onenote_rest/SnippetDetailFragment.java
[ "public class AuthenticationManager {\n\n private static final String USER_ID_VAR_NAME = \"userId\";\n\n private static final int PREFERENCES_MODE = Context.MODE_PRIVATE;\n\n private final Activity mActivity;\n\n private final AuthenticationContext mAuthenticationContext;\n\n private final String\n mAuthenticationResourceId,\n mSharedPreferencesFilename,\n mClientId,\n mRedirectUri;\n\n AuthenticationManager(\n Activity activity,\n AuthenticationContext authenticationContext,\n String authenticationResourceId,\n String sharedPreferencesFilename,\n String clientId,\n String redirectUri) {\n mActivity = activity;\n mAuthenticationContext = authenticationContext;\n mAuthenticationResourceId = authenticationResourceId;\n mSharedPreferencesFilename = sharedPreferencesFilename;\n mClientId = clientId;\n mRedirectUri = redirectUri;\n }\n\n private SharedPreferences getSharedPreferences() {\n return mActivity.getSharedPreferences(mSharedPreferencesFilename, PREFERENCES_MODE);\n }\n\n public void connect(AuthenticationCallback<AuthenticationResult> authenticationCallback) {\n if (isConnected()) {\n authenticateSilent(authenticationCallback);\n } else {\n authenticatePrompt(authenticationCallback);\n }\n }\n\n /**\n * Disconnects the app from Office 365 by clearing the token cache, setting the client objects\n * to null, and removing the user id from shred preferences.\n */\n public void disconnect() {\n // Clear tokens.\n if (mAuthenticationContext.getCache() != null) {\n mAuthenticationContext.getCache().removeAll();\n }\n\n // Forget the user\n removeUserId();\n }\n\n private void authenticatePrompt(\n final AuthenticationCallback<AuthenticationResult> authenticationCallback) {\n mAuthenticationContext\n .acquireToken(\n mAuthenticationResourceId,\n mClientId,\n mRedirectUri,\n null,\n PromptBehavior.Always,\n null,\n new AuthenticationCallback<AuthenticationResult>() {\n @Override\n public void onSuccess(final AuthenticationResult authenticationResult) {\n if (Succeeded == authenticationResult.getStatus()) {\n setUserId(authenticationResult.getUserInfo().getUserId());\n authenticationCallback.onSuccess(authenticationResult);\n } else {\n onError(\n new AuthenticationException(ADALError.AUTH_FAILED,\n authenticationResult.getErrorCode()));\n }\n }\n\n @Override\n public void onError(Exception e) {\n disconnect();\n authenticationCallback.onError(e);\n }\n }\n );\n }\n\n private void authenticateSilent(\n final AuthenticationCallback<AuthenticationResult> authenticationCallback) {\n mAuthenticationContext.acquireTokenSilent(\n mAuthenticationResourceId,\n mClientId,\n getUserId(),\n new AuthenticationCallback<AuthenticationResult>() {\n @Override\n public void onSuccess(AuthenticationResult authenticationResult) {\n authenticationCallback.onSuccess(authenticationResult);\n }\n\n @Override\n public void onError(Exception e) {\n authenticatePrompt(authenticationCallback);\n }\n });\n }\n\n private boolean isConnected() {\n return getSharedPreferences().contains(USER_ID_VAR_NAME);\n }\n\n private String getUserId() {\n return getSharedPreferences().getString(USER_ID_VAR_NAME, \"\");\n }\n\n private void setUserId(String value) {\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.putString(USER_ID_VAR_NAME, value);\n editor.apply();\n }\n\n private void removeUserId() {\n SharedPreferences.Editor editor = getSharedPreferences().edit();\n editor.remove(USER_ID_VAR_NAME);\n editor.apply();\n }\n\n}", "public abstract class AbstractSnippet<Service, Result> {\n\n public static final Services sServices = new Services();\n\n private String mName, mDesc, mSection, mUrl, mO365Version, mMSAVersion;\n public final Service mService;\n public final Input mInputArgs;\n\n private static final int sNameIndex = 0;\n private static final int sDescIndex = 1;\n private static final int sUrlIndex = 2;\n private static final int sO365VersionIndex = 3;\n private static final int sMSAVersionIndex = 4;\n\n\n /**\n * Snippet constructor\n *\n * @param category Snippet category (Notebook, sectionGroup, section, page)\n * @param descriptionArray The String array for the specified snippet\n */\n public AbstractSnippet(\n SnippetCategory<Service> category,\n Integer descriptionArray) {\n\n //Get snippet configuration information from the\n //XML configuration for the snippet\n getSnippetArrayContent(category, descriptionArray);\n\n mService = category.mService;\n mInputArgs = Input.None;\n }\n\n /**\n * Snippet constructor\n *\n * @param category Snippet category (Notebook, sectionGroup, section, page)\n * @param descriptionArray The String array for the specified snippet\n * @param inputArgs any input arguments\n */\n public AbstractSnippet(\n SnippetCategory<Service> category,\n Integer descriptionArray,\n Input inputArgs) {\n\n //Get snippet configuration information from the\n //XML configuration for the snippet\n getSnippetArrayContent(category, descriptionArray);\n\n mSection = category.mSection;\n mService = category.mService;\n mInputArgs = inputArgs;\n }\n\n /**\n * Gets the items from the specified snippet XML string array and stores the values\n * in private class fields\n *\n * @param category\n * @param descriptionArray\n */\n private void getSnippetArrayContent(SnippetCategory<Service> category, Integer descriptionArray) {\n if (null != descriptionArray) {\n String[] params = SnippetApp.getApp().getResources().getStringArray(descriptionArray);\n\n try {\n mName = params[sNameIndex];\n mDesc = params[sDescIndex];\n mUrl = params[sUrlIndex];\n mO365Version = params[sO365VersionIndex];\n mMSAVersion = params[sMSAVersionIndex];\n } catch (IndexOutOfBoundsException ex) {\n throw new RuntimeException(\n \"Invalid array in \"\n + category.mSection\n + \" snippet XML file\"\n , ex);\n }\n } else {\n mName = category.mSection;\n mDesc = mUrl = null;\n mO365Version = null;\n mMSAVersion = null;\n }\n mSection = category.mSection;\n }\n\n protected static class Services {\n\n public final NotebooksService mNotebooksService;\n public final PagesService mPagesService;\n public final SectionGroupsService mSectionGroupsService;\n public final SectionsService mSectionsService;\n\n Services() {\n mNotebooksService = notebookSnippetCategory.mService;\n mPagesService = pagesSnippetCategory.mService;\n mSectionGroupsService = sectionGroupsSnippetCategory.mService;\n mSectionsService = sectionsSnippetCategory.mService;\n }\n }\n\n @SuppressWarnings(\"unused\")\n public void setUp(Services services, retrofit.Callback<String[]> callback) {\n // Optional method....\n callback.success(new String[]{}, null);\n }\n\n /**\n * Returns the version segment of the endpoint url with input from\n * XML snippet description and authentication method (Office 365, MSA)\n *\n * @return the version of the endpoint to use\n */\n public String getVersion() {\n return User.isMsa() ? mMSAVersion : mO365Version;\n }\n\n\n public String getName() {\n return mName;\n }\n\n public String getDescription() {\n return mDesc;\n }\n\n public String getUrl() {\n return mUrl;\n }\n\n public String getSection() {\n return mSection;\n }\n\n /**\n * Abstract declaration of method which subclasses must define to actually run the snippet\n *\n * @param service the service instance to use\n * @param callback the recipient of the result\n */\n public abstract void request(Service service, Callback<Result> callback);\n\n}", "public interface Callback<T> extends retrofit.Callback<T> {\n\n Map<String, String> getParams();\n}", "public enum Input {\n None, Text, Spinner, Both\n}", "public class SnippetContent {\n\n public static List<AbstractSnippet<?, ?>> ITEMS = new ArrayList<>();\n\n static {\n AbstractSnippet<?, ?>[][] baseSnippets = new AbstractSnippet<?, ?>[][]{\n getNotebookSnippets(),\n getPagesSnippets(),\n getSectionGroupsSnippets(),\n getSectionsServiceSnippets()\n };\n\n for (AbstractSnippet<?, ?>[] snippetArray : baseSnippets) {\n Collections.addAll(ITEMS, snippetArray);\n }\n }\n\n}", "public class SharedPrefsUtil {\n\n public static final String PREF_AUTH_TOKEN = \"PREF_AUTH_TOKEN\";\n\n public static SharedPreferences getSharedPreferences() {\n return SnippetApp.getApp().getSharedPreferences(AppModule.PREFS, Context.MODE_PRIVATE);\n }\n\n public static void persistAuthToken(AuthenticationResult result) {\n setAccessToken(result.getAccessToken());\n User.isOrg(true);\n }\n\n public static void persistAuthToken(LiveConnectSession session) {\n setAccessToken(session.getAccessToken());\n User.isMsa(true);\n }\n\n private static void setAccessToken(String accessToken) {\n getSharedPreferences().edit().putString(PREF_AUTH_TOKEN, accessToken).commit();\n }\n}", "public class User {\n\n private static final String PREF_MSA = \"PREF_MSA\";\n private static final String PREF_ORG = \"PREF_ORG\";\n\n static void isMsa(boolean msa) {\n set(PREF_MSA, msa);\n }\n\n static void isOrg(boolean org) {\n set(PREF_ORG, org);\n }\n\n public static boolean isMsa() {\n return is(PREF_MSA);\n }\n\n public static boolean isOrg() {\n return is(PREF_ORG);\n }\n\n private static boolean is(String which) {\n return SharedPrefsUtil.getSharedPreferences().getBoolean(which, false);\n }\n\n private static void set(String which, boolean state) {\n SharedPrefsUtil\n .getSharedPreferences()\n .edit()\n .putBoolean(which, state)\n .commit();\n }\n}" ]
import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.ClipboardManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.microsoft.AuthenticationManager; import com.microsoft.aad.adal.AuthenticationCallback; import com.microsoft.aad.adal.AuthenticationResult; import com.microsoft.live.LiveAuthClient; import com.microsoft.live.LiveAuthException; import com.microsoft.live.LiveAuthListener; import com.microsoft.live.LiveConnectSession; import com.microsoft.live.LiveStatus; import com.microsoft.o365_android_onenote_rest.snippet.AbstractSnippet; import com.microsoft.o365_android_onenote_rest.snippet.Callback; import com.microsoft.o365_android_onenote_rest.snippet.Input; import com.microsoft.o365_android_onenote_rest.snippet.SnippetContent; import com.microsoft.o365_android_onenote_rest.util.SharedPrefsUtil; import com.microsoft.o365_android_onenote_rest.util.User; import com.microsoft.onenotevos.BaseVO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; import retrofit.RetrofitError; import retrofit.client.Header; import retrofit.client.Response; import timber.log.Timber; import static android.R.layout.simple_spinner_dropdown_item; import static android.R.layout.simple_spinner_item; import static android.view.View.GONE; import static android.view.View.VISIBLE; import static com.microsoft.o365_android_onenote_rest.R.id.btn_launch_browser; import static com.microsoft.o365_android_onenote_rest.R.id.btn_run; import static com.microsoft.o365_android_onenote_rest.R.id.progressbar; import static com.microsoft.o365_android_onenote_rest.R.id.spinner; import static com.microsoft.o365_android_onenote_rest.R.id.txt_desc; import static com.microsoft.o365_android_onenote_rest.R.id.txt_hyperlink; import static com.microsoft.o365_android_onenote_rest.R.id.txt_input; import static com.microsoft.o365_android_onenote_rest.R.id.txt_request_url; import static com.microsoft.o365_android_onenote_rest.R.id.txt_response_body; import static com.microsoft.o365_android_onenote_rest.R.id.txt_response_headers; import static com.microsoft.o365_android_onenote_rest.R.id.txt_status_code; import static com.microsoft.o365_android_onenote_rest.R.id.txt_status_color; import static com.microsoft.o365_android_onenote_rest.R.string.clippy; import static com.microsoft.o365_android_onenote_rest.R.string.req_url; import static com.microsoft.o365_android_onenote_rest.R.string.response_body; import static com.microsoft.o365_android_onenote_rest.R.string.response_headers;
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.o365_android_onenote_rest; public class SnippetDetailFragment<T, Result> extends BaseFragment implements Callback<Result>, AuthenticationCallback<AuthenticationResult>, LiveAuthListener { public static final String ARG_ITEM_ID = "item_id"; public static final String ARG_TEXT_INPUT = "TextInput"; public static final String ARG_SPINNER_SELECTION = "SpinnerSelection"; public static final int UNSET = -1; public static final String APP_STORE_URI = "https://play.google.com/store/apps/details?id=com.microsoft.office.onenote"; @InjectView(txt_status_code) protected TextView mStatusCode; @InjectView(txt_status_color) protected View mStatusColor; @InjectView(txt_desc) protected TextView mSnippetDescription; @InjectView(txt_request_url) protected TextView mRequestUrl; @InjectView(txt_response_headers) protected TextView mResponseHeaders; @InjectView(txt_response_body) protected TextView mResponseBody; @InjectView(spinner) protected Spinner mSpinner; @InjectView(txt_input) protected EditText mEditText; @InjectView(progressbar) protected ProgressBar mProgressbar; @InjectView(btn_run) protected Button mRunButton; @Inject protected AuthenticationManager mAuthenticationManager; @Inject protected LiveAuthClient mLiveAuthClient; boolean setupDidRun = false; private AbstractSnippet<T, Result> mItem; public SnippetDetailFragment() { } @OnClick(txt_request_url) public void onRequestUrlClicked(TextView tv) { clipboard(tv); } @OnClick(txt_response_headers) public void onResponseHeadersClicked(TextView tv) { clipboard(tv); } @OnClick(txt_response_body) public void onResponseBodyClicked(TextView tv) { clipboard(tv); } @InjectView(btn_launch_browser) protected Button mLaunchBrowser; private void clipboard(TextView tv) { int which; switch (tv.getId()) { case txt_request_url: which = req_url; break; case txt_response_headers: which = response_headers; break; case txt_response_body: which = response_body; break; default: which = UNSET; } String what = which == UNSET ? "" : getString(which) + " "; what += getString(clippy); Toast.makeText(getActivity(), what, Toast.LENGTH_SHORT).show(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // old way ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); clipboardManager.setText(tv.getText()); } else { clipboard11(tv); } } @TargetApi(11) private void clipboard11(TextView tv) { android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) getActivity() .getSystemService(Context.CLIPBOARD_SERVICE); ClipData clipData = ClipData.newPlainText("OneNote", tv.getText()); clipboardManager.setPrimaryClip(clipData); } @OnClick(btn_run) public void onRunClicked(Button btn) { mRequestUrl.setText(""); mResponseHeaders.setText(""); mResponseBody.setText(""); displayStatusCode("", getResources().getColor(R.color.transparent)); mProgressbar.setVisibility(VISIBLE); mItem.request(mItem.mService, this); } @OnClick(txt_hyperlink) public void onDocsLinkClicked(TextView textView) { launchUri(Uri.parse(mItem.getUrl())); } private void launchUri(Uri uri) { Intent launchOneNoteExtern = new Intent(Intent.ACTION_VIEW, uri); try { startActivity(launchOneNoteExtern); } catch (ActivityNotFoundException e) { launchOneNoteExtern = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_STORE_URI)); startActivity(launchOneNoteExtern); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { mItem = (AbstractSnippet<T, Result>)
SnippetContent.ITEMS.get(getArguments().getInt(ARG_ITEM_ID));
4
Jigsaw-Code/Intra
Android/app/src/main/java/app/intra/net/go/GoVpnAdapter.java
[ "public class CountryCode {\n // The SIM or CDMA country.\n private final @NonNull String deviceCountry;\n\n // The country claimed by the attached cell network.\n private final @NonNull String networkCountry;\n\n public CountryCode(Context context) {\n TelephonyManager telephonyManager =\n (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);\n\n deviceCountry = countryFromSim(telephonyManager);\n networkCountry = telephonyManager.getNetworkCountryIso();\n }\n\n public @NonNull String getDeviceCountry() {\n return deviceCountry;\n }\n\n public @NonNull String getNetworkCountry() {\n return networkCountry;\n }\n\n private static @NonNull String countryFromSim(TelephonyManager telephonyManager) {\n String simCountry = telephonyManager.getSimCountryIso();\n if (!simCountry.isEmpty()) {\n return simCountry;\n }\n // User appears to be non-GSM. Try CDMA.\n try {\n // Get the system properties by reflection.\n @SuppressLint(\"PrivateApi\")\n Class<?> systemPropertiesClass = Class.forName(\"android.os.SystemProperties\");\n Method get = systemPropertiesClass.getMethod(\"get\", String.class);\n String cdmaOperator = (String)get.invoke(systemPropertiesClass,\n \"ro.cdma.home.operator.numeric\");\n if (cdmaOperator == null || cdmaOperator.isEmpty()) {\n // System is neither GSM nor CDMA.\n return \"\";\n }\n String mcc = cdmaOperator.substring(0, 3);\n @SuppressLint(\"PrivateApi\")\n Class<?> mccTableClass = Class.forName(\"com.android.internal.telephony.MccTable\");\n Method countryCodeForMcc = mccTableClass.getMethod(\"countryCodeForMcc\", String.class);\n return (String)countryCodeForMcc.invoke(mccTableClass, mcc);\n } catch (Exception e) {\n LogWrapper.logException(e);\n return \"\";\n }\n }\n}", "public class IntraVpnService extends VpnService implements NetworkListener,\n SharedPreferences.OnSharedPreferenceChangeListener, Protector {\n\n /**\n * null: There is no connection\n * NEW: The connection has not yet completed bootstrap.\n * WORKING: The last query (or bootstrap) succeeded.\n * FAILING: The last query (or bootstrap) failed.\n */\n public enum State { NEW, WORKING, FAILING };\n\n private static final String LOG_TAG = \"IntraVpnService\";\n private static final int SERVICE_ID = 1; // Only has to be unique within this app.\n private static final String MAIN_CHANNEL_ID = \"vpn\";\n private static final String WARNING_CHANNEL_ID = \"warning\";\n private static final String NO_PENDING_CONNECTION = \"This value is not a possible URL.\";\n\n // Reference to the singleton VpnController, for convenience\n private static final VpnController vpnController = VpnController.getInstance();\n\n // The network manager is populated in onStartCommand. Its main function is to enable delayed\n // initialization if the network is initially disconnected.\n @GuardedBy(\"vpnController\")\n private NetworkManager networkManager;\n\n // The state of the device's network access, recording the latest update from networkManager.\n private boolean networkConnected = false;\n\n // The VPN adapter runs within this service and is responsible for establishing the VPN and\n // passing packets to the network. vpnAdapter is only null before startup and after shutdown,\n // but it may be atomically replaced by restartVpn().\n @GuardedBy(\"vpnController\")\n private GoVpnAdapter vpnAdapter = null;\n\n // The URL of the DNS server. null and \"\" are special values indicating the default server.\n // This value can change if the user changes their configuration after starting the VPN.\n @GuardedBy(\"vpnController\")\n private String url = null;\n\n // The URL of a pending connection attempt, or a special value if there is no pending connection\n // attempt. This value is only used within updateServerConnection(), where it serves to avoid\n // the creation of duplicate outstanding server connection attempts. Whenever pendingUrl\n // indicates a pending connection, serverConnection should be null to avoid sending queries to the\n // previously selected server.\n @GuardedBy(\"vpnController\")\n private String pendingUrl = NO_PENDING_CONNECTION;\n\n private AnalyticsWrapper analytics;\n\n public boolean isOn() {\n return vpnAdapter != null;\n }\n\n @Override\n public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {\n if (PersistentState.APPS_KEY.equals(key) && vpnAdapter != null) {\n // Restart the VPN so the new app exclusion choices take effect immediately.\n restartVpn();\n }\n if (PersistentState.URL_KEY.equals(key)) {\n url = PersistentState.getServerUrl(this);\n spawnServerUpdate();\n }\n }\n\n private void spawnServerUpdate() {\n synchronized (vpnController) {\n if (networkManager != null) {\n new Thread(\n new Runnable() {\n public void run() {\n updateServerConnection();\n }\n }, \"updateServerConnection-onStartCommand\")\n .start();\n }\n }\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n synchronized (vpnController) {\n Log.i(LOG_TAG, String.format(\"Starting DNS VPN service, url=%s\", url));\n url = PersistentState.getServerUrl(this);\n\n // Registers this class as a listener for user preference changes.\n PreferenceManager.getDefaultSharedPreferences(this).\n registerOnSharedPreferenceChangeListener(this);\n\n if (networkManager != null) {\n spawnServerUpdate();\n return START_REDELIVER_INTENT;\n }\n\n // If we're online, |networkManager| immediately calls this.onNetworkConnected(), which in turn\n // calls startVpn() to actually start. If we're offline, the startup actions will be delayed\n // until we come online.\n networkManager = new NetworkManager(IntraVpnService.this, IntraVpnService.this);\n\n // Mark this as a foreground service. This is normally done to ensure that the service\n // survives under memory pressure. Since this is a VPN service, it is presumably protected\n // anyway, but the foreground service mechanism allows us to set a persistent notification,\n // which helps users understand what's going on, and return to the app if they want.\n PendingIntent mainActivityIntent =\n PendingIntent.getActivity(\n this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);\n\n Notification.Builder builder;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n CharSequence name = getString(R.string.channel_name);\n String description = getString(R.string.channel_description);\n // LOW is the lowest importance that is allowed with startForeground in Android O.\n int importance = NotificationManager.IMPORTANCE_LOW;\n NotificationChannel channel = new NotificationChannel(MAIN_CHANNEL_ID, name, importance);\n channel.setDescription(description);\n\n NotificationManager notificationManager = getSystemService(NotificationManager.class);\n notificationManager.createNotificationChannel(channel);\n builder = new Notification.Builder(this, MAIN_CHANNEL_ID);\n } else {\n builder = new Notification.Builder(this);\n // Min-priority notifications don't show an icon in the notification bar, reducing clutter.\n builder = builder.setPriority(Notification.PRIORITY_MIN);\n }\n\n builder.setSmallIcon(R.drawable.ic_status_bar)\n .setContentTitle(getResources().getText(R.string.notification_title))\n .setContentText(getResources().getText(R.string.notification_content))\n .setContentIntent(mainActivityIntent);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n // Secret notifications are not shown on the lock screen. No need for this app to show there.\n // Only available in API >= 21\n builder = builder.setVisibility(Notification.VISIBILITY_SECRET);\n }\n\n startForeground(SERVICE_ID, builder.getNotification());\n\n updateQuickSettingsTile();\n\n return START_REDELIVER_INTENT;\n }\n }\n\n @WorkerThread\n private void updateServerConnection() {\n synchronized (vpnController) {\n if (vpnAdapter != null) {\n vpnAdapter.updateDohUrl();\n }\n }\n }\n\n /**\n * Starts the VPN. This method performs network activity, so it must not run on the main thread.\n * This method is idempotent, and is synchronized so that it can safely be called from a\n * freshly spawned thread.\n */\n @WorkerThread\n private void startVpn() {\n synchronized (vpnController) {\n if (vpnAdapter != null) {\n return;\n }\n\n startVpnAdapter();\n\n vpnController.onStartComplete(this, vpnAdapter != null);\n if (vpnAdapter == null) {\n LogWrapper.log(Log.WARN, LOG_TAG, \"Failed to startVpn VPN adapter\");\n stopSelf();\n }\n }\n }\n\n private void restartVpn() {\n synchronized (vpnController) {\n // Attempt seamless handoff as described in the docs for VpnService.Builder.establish().\n final GoVpnAdapter oldAdapter = vpnAdapter;\n vpnAdapter = makeVpnAdapter();\n oldAdapter.close();\n if (vpnAdapter != null) {\n vpnAdapter.start();\n } else {\n LogWrapper.log(Log.WARN, LOG_TAG, \"Restart failed\");\n }\n }\n }\n\n @Override\n public void onCreate() {\n LogWrapper.log(Log.INFO, LOG_TAG, \"Creating DNS VPN service\");\n vpnController.setIntraVpnService(this);\n\n analytics = AnalyticsWrapper.get(this);\n\n syncNumRequests();\n }\n\n public void signalStopService(boolean userInitiated) {\n LogWrapper.log(\n Log.INFO,\n LOG_TAG,\n String.format(\"Received stop signal. User initiated: %b\", userInitiated));\n\n if (!userInitiated) {\n final long[] vibrationPattern = {1000}; // Vibrate for one second.\n // Show revocation warning\n Notification.Builder builder;\n NotificationManager notificationManager =\n (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n if (VERSION.SDK_INT >= VERSION_CODES.O) {\n CharSequence name = getString(R.string.warning_channel_name);\n String description = getString(R.string.warning_channel_description);\n int importance = NotificationManager.IMPORTANCE_HIGH;\n NotificationChannel channel = new NotificationChannel(WARNING_CHANNEL_ID, name, importance);\n channel.setDescription(description);\n channel.enableVibration(true);\n channel.setVibrationPattern(vibrationPattern);\n\n notificationManager.createNotificationChannel(channel);\n builder = new Notification.Builder(this, WARNING_CHANNEL_ID);\n } else {\n builder = new Notification.Builder(this);\n builder.setVibrate(vibrationPattern);\n // Deprecated in API 26.\n builder = builder.setPriority(Notification.PRIORITY_MAX);\n }\n\n PendingIntent mainActivityIntent = PendingIntent.getActivity(\n this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);\n\n builder.setSmallIcon(R.drawable.ic_status_bar)\n .setContentTitle(getResources().getText(R.string.warning_title))\n .setContentText(getResources().getText(R.string.notification_content))\n .setFullScreenIntent(mainActivityIntent, true) // Open the main UI if possible.\n .setAutoCancel(true);\n\n if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {\n builder.setCategory(Notification.CATEGORY_ERROR);\n }\n\n notificationManager.notify(0, builder.getNotification());\n }\n\n stopVpnAdapter();\n stopSelf();\n\n updateQuickSettingsTile();\n }\n\n private GoVpnAdapter makeVpnAdapter() {\n return GoVpnAdapter.establish(this);\n }\n\n private void startVpnAdapter() {\n synchronized (vpnController) {\n if (vpnAdapter == null) {\n LogWrapper.log(Log.INFO, LOG_TAG, \"Starting VPN adapter\");\n vpnAdapter = makeVpnAdapter();\n if (vpnAdapter != null) {\n vpnAdapter.start();\n analytics.logStartVPN(vpnAdapter.getClass().getSimpleName());\n } else {\n LogWrapper.log(Log.ERROR, LOG_TAG, \"Failed to start VPN adapter!\");\n }\n }\n }\n }\n\n private void stopVpnAdapter() {\n synchronized (vpnController) {\n if (vpnAdapter != null) {\n vpnAdapter.close();\n vpnAdapter = null;\n vpnController.onConnectionStateChanged(this, null);\n }\n }\n }\n\n private void updateQuickSettingsTile() {\n if (VERSION.SDK_INT >= VERSION_CODES.N) {\n TileService.requestListeningState(this,\n new ComponentName(this, IntraTileService.class));\n }\n }\n\n @Override\n public void onDestroy() {\n synchronized (vpnController) {\n LogWrapper.log(Log.INFO, LOG_TAG, \"Destroying DNS VPN service\");\n\n PreferenceManager.getDefaultSharedPreferences(this).\n unregisterOnSharedPreferenceChangeListener(this);\n\n if (networkManager != null) {\n networkManager.destroy();\n }\n\n syncNumRequests();\n\n vpnController.setIntraVpnService(null);\n\n stopForeground(true);\n if (vpnAdapter != null) {\n signalStopService(false);\n }\n }\n }\n\n @Override\n public void onRevoke() {\n LogWrapper.log(Log.WARN, LOG_TAG, \"VPN service revoked.\");\n stopSelf();\n\n // Disable autostart if VPN permission is revoked.\n PersistentState.setVpnEnabled(this, false);\n }\n\n public VpnService.Builder newBuilder() {\n VpnService.Builder builder = new VpnService.Builder();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n // Some WebRTC apps rely on the ability to bind to specific interfaces, which is only\n // possible if we allow bypass.\n builder = builder.allowBypass();\n\n try {\n // Workaround for any app incompatibility bugs.\n for (String packageName : PersistentState.getExcludedPackages(this)) {\n builder = builder.addDisallowedApplication(packageName);\n }\n // Play Store incompatibility is a known issue, so always exclude it.\n builder = builder.addDisallowedApplication(\"com.android.vending\");\n } catch (PackageManager.NameNotFoundException e) {\n LogWrapper.logException(e);\n Log.e(LOG_TAG, \"Failed to exclude an app\", e);\n }\n }\n return builder;\n }\n\n public void recordTransaction(Transaction transaction) {\n transaction.responseTime = SystemClock.elapsedRealtime();\n transaction.responseCalendar = Calendar.getInstance();\n\n getTracker().recordTransaction(this, transaction);\n\n Intent intent = new Intent(InternalNames.RESULT.name());\n intent.putExtra(InternalNames.TRANSACTION.name(), transaction);\n LocalBroadcastManager.getInstance(IntraVpnService.this).sendBroadcast(intent);\n\n if (!networkConnected) {\n // No need to update the user-visible connection state while there is no network.\n return;\n }\n\n // Update the connection state. If the transaction succeeded, then the connection is working.\n // If the transaction failed, then the connection is not working.\n // If the transaction was canceled, then we don't have any new information about the status\n // of the connection, so we don't send an update.\n if (transaction.status == Transaction.Status.COMPLETE) {\n vpnController.onConnectionStateChanged(this, State.WORKING);\n } else if (transaction.status != Transaction.Status.CANCELED) {\n vpnController.onConnectionStateChanged(this, State.FAILING);\n }\n }\n\n private QueryTracker getTracker() {\n return vpnController.getTracker(this);\n }\n\n private void syncNumRequests() {\n getTracker().sync(this);\n }\n\n private void setNetworkConnected(boolean connected) {\n networkConnected = connected;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n // Indicate that traffic will be sent over the current active network.\n // See e.g. https://issuetracker.google.com/issues/68657525\n final Network activeNetwork = getSystemService(ConnectivityManager.class).getActiveNetwork();\n setUnderlyingNetworks(connected ? new Network[]{ activeNetwork } : null);\n }\n }\n\n // NetworkListener interface implementation\n @Override\n public void onNetworkConnected(NetworkInfo networkInfo) {\n LogWrapper.log(Log.INFO, LOG_TAG, \"Connected event.\");\n setNetworkConnected(true);\n // This code is used to start the VPN for the first time, but startVpn is idempotent, so we can\n // call it every time. startVpn performs network activity so it has to run on a separate thread.\n new Thread(\n new Runnable() {\n public void run() {\n updateServerConnection();\n startVpn();\n }\n }, \"startVpn-onNetworkConnected\")\n .start();\n }\n\n @Override\n public void onNetworkDisconnected() {\n LogWrapper.log(Log.INFO, LOG_TAG, \"Disconnected event.\");\n setNetworkConnected(false);\n vpnController.onConnectionStateChanged(this, null);\n }\n\n @Override // From the Protect interface.\n public String getResolvers() {\n List<String> ips = new ArrayList<>();\n for (InetAddress ip : networkManager.getSystemResolvers()) {\n String address = ip.getHostAddress();\n if (!GoVpnAdapter.FAKE_DNS_IP.equals(address)) {\n ips.add(address);\n }\n }\n return TextUtils.join(\",\", ips);\n }\n}", "public class PersistentState {\n private static final String LOG_TAG = \"PersistentState\";\n\n public static final String APPS_KEY = \"pref_apps\";\n public static final String URL_KEY = \"pref_server_url\";\n\n private static final String APPROVED_KEY = \"approved\";\n private static final String ENABLED_KEY = \"enabled\";\n private static final String SERVER_KEY = \"server\";\n\n private static final String INTERNAL_STATE_NAME = \"MainActivity\";\n\n // The approval state is currently stored in a separate preferences file.\n // TODO: Unify preferences into a single file.\n private static final String APPROVAL_PREFS_NAME = \"IntroState\";\n\n private static SharedPreferences getInternalState(Context context) {\n return context.getSharedPreferences(INTERNAL_STATE_NAME, Context.MODE_PRIVATE);\n }\n\n private static SharedPreferences getUserPreferences(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context);\n }\n\n static boolean getVpnEnabled(Context context) {\n return getInternalState(context).getBoolean(ENABLED_KEY, false);\n }\n\n static void setVpnEnabled(Context context, boolean enabled) {\n SharedPreferences.Editor editor = getInternalState(context).edit();\n editor.putBoolean(ENABLED_KEY, enabled);\n editor.apply();\n }\n\n public static void syncLegacyState(Context context) {\n // Copy the domain choice into the new URL setting, if necessary.\n if (getServerUrl(context) != null) {\n // New server URL is already populated\n return;\n }\n\n // There is no URL setting, so read the legacy server name.\n SharedPreferences settings = getInternalState(context);\n String domain = settings.getString(SERVER_KEY, null);\n if (domain == null) {\n // Legacy setting is in the default state, so we can leave the new URL setting in the default\n // state as well.\n return;\n }\n\n String[] urls = context.getResources().getStringArray(R.array.urls);\n String defaultDomain = context.getResources().getString(R.string.legacy_domain0);\n String url = null;\n if (domain.equals(defaultDomain)) {\n // Common case: the domain is dns.google.com, which now corresponds to dns.google (url 0).\n url = urls[0];\n } else {\n // In practice, we expect that domain will always be cloudflare-dns.com at this point, because\n // that was the only other option in the relevant legacy versions of Intra.\n // Look for the corresponding URL among the builtin servers.\n for (String u : urls) {\n Uri parsed = Uri.parse(u);\n if (domain.equals(parsed.getHost())) {\n url = u;\n break;\n }\n }\n }\n\n if (url == null) {\n LogWrapper.log(Log.WARN, LOG_TAG, \"Legacy domain is unrecognized\");\n return;\n }\n setServerUrl(context, url);\n }\n\n public static void setServerUrl(Context context, String url) {\n SharedPreferences.Editor editor = getUserPreferences(context).edit();\n editor.putString(URL_KEY, url);\n editor.apply();\n }\n\n public static String getServerUrl(Context context) {\n String urlTemplate = getUserPreferences(context).getString(URL_KEY, null);\n if (urlTemplate == null) {\n return null;\n }\n return Untemplate.strip(urlTemplate);\n }\n\n private static String extractHost(String url) {\n try {\n URL parsed = new URL(url);\n return parsed.getHost();\n } catch (MalformedURLException e) {\n LogWrapper.log(Log.WARN, LOG_TAG, \"URL is corrupted\");\n return null;\n }\n }\n\n // Converts a null url into the actual default url. Otherwise, returns url unmodified.\n public static @NonNull String expandUrl(Context context, @Nullable String url) {\n if (url == null || url.isEmpty()) {\n return context.getResources().getString(R.string.url0);\n }\n return url;\n }\n\n // Returns a domain representing the current configured server URL, for use as a display name.\n public static String getServerName(Context context) {\n return extractHost(expandUrl(context, getServerUrl(context)));\n }\n\n /**\n * Extract the hostname from the URL, while avoiding disclosure of custom servers.\n * @param url A DoH server configuration url (or url template).\n * @return Returns the domain name in the URL, or \"CUSTOM_SERVER\" if the url is not one of the\n * built-in servers.\n */\n public static String extractHostForAnalytics(Context context, String url) {\n String expanded = expandUrl(context, url);\n String[] urls = context.getResources().getStringArray(R.array.urls);\n if (Arrays.asList(urls).contains(expanded)) {\n return extractHost(expanded);\n }\n return InternalNames.CUSTOM_SERVER.name();\n }\n\n private static SharedPreferences getApprovalSettings(Context context) {\n return context.getSharedPreferences(APPROVAL_PREFS_NAME, Context.MODE_PRIVATE);\n }\n\n public static boolean getWelcomeApproved(Context context) {\n return getApprovalSettings(context).getBoolean(APPROVED_KEY, false);\n }\n\n public static void setWelcomeApproved(Context context, boolean approved) {\n SharedPreferences.Editor editor = getApprovalSettings(context).edit();\n editor.putBoolean(APPROVED_KEY, approved);\n editor.apply();\n }\n\n static Set<String> getExcludedPackages(Context context) {\n return getUserPreferences(context).getStringSet(APPS_KEY, new HashSet<String>());\n }\n}", "public class VpnController {\n\n private static VpnController dnsVpnServiceState;\n\n public Object clone() throws CloneNotSupportedException {\n throw new CloneNotSupportedException();\n }\n\n public static synchronized VpnController getInstance() {\n if (dnsVpnServiceState == null) {\n dnsVpnServiceState = new VpnController();\n }\n return dnsVpnServiceState;\n }\n\n private IntraVpnService intraVpnService = null;\n private IntraVpnService.State connectionState = null;\n private QueryTracker tracker = null;\n\n private VpnController() {}\n\n void setIntraVpnService(IntraVpnService intraVpnService) {\n this.intraVpnService = intraVpnService;\n }\n\n public @Nullable IntraVpnService getIntraVpnService() {\n return this.intraVpnService;\n }\n\n public synchronized void onConnectionStateChanged(Context context, IntraVpnService.State state) {\n if (intraVpnService == null) {\n // User clicked disable while the connection state was changing.\n return;\n }\n connectionState = state;\n stateChanged(context);\n }\n\n private void stateChanged(Context context) {\n Intent broadcast = new Intent(InternalNames.DNS_STATUS.name());\n LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);\n }\n\n public synchronized QueryTracker getTracker(Context context) {\n if (tracker == null) {\n tracker = new QueryTracker(context);\n }\n return tracker;\n }\n\n public synchronized void start(Context context) {\n if (intraVpnService != null) {\n return;\n }\n PersistentState.setVpnEnabled(context, true);\n stateChanged(context);\n Intent startServiceIntent = new Intent(context, IntraVpnService.class);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n context.startForegroundService(startServiceIntent);\n } else {\n context.startService(startServiceIntent);\n }\n }\n\n synchronized void onStartComplete(Context context, boolean succeeded) {\n if (!succeeded) {\n // VPN setup only fails if VPN permission has been revoked. If this happens, clear the\n // user intent state and reset to the default state.\n stop(context);\n } else {\n stateChanged(context);\n }\n }\n\n public synchronized void stop(Context context) {\n PersistentState.setVpnEnabled(context, false);\n connectionState = null;\n if (intraVpnService != null) {\n intraVpnService.signalStopService(true);\n }\n intraVpnService = null;\n stateChanged(context);\n }\n\n public synchronized VpnState getState(Context context) {\n boolean requested = PersistentState.getVpnEnabled(context);\n boolean on = intraVpnService != null && intraVpnService.isOn();\n return new VpnState(requested, on, connectionState);\n }\n\n}", "public class AnalyticsWrapper implements NetworkListener {\n private static AnalyticsWrapper singleton;\n\n // Analytics events\n private enum Events {\n BOOTSTRAP,\n BOOTSTRAP_FAILED,\n BYTES,\n EARLY_RESET,\n STARTVPN,\n TRY_ALL_ACCEPTED,\n TRY_ALL_CANCELLED,\n TRY_ALL_DIALOG,\n TRY_ALL_FAILED,\n TRY_ALL_REQUESTED,\n UDP,\n }\n\n private enum NetworkTypes {\n MOBILE,\n WIFI,\n OTHER,\n NONE\n }\n\n private final @NonNull CountryCode countryCode;\n private final @NonNull FirebaseAnalytics analytics;\n private final @NonNull NetworkManager networkManager;\n\n private @Nullable NetworkInfo networkInfo = null;\n\n private AnalyticsWrapper(Context context) {\n countryCode = new CountryCode(context);\n analytics = FirebaseAnalytics.getInstance(context);\n\n // Register for network info updates. Calling this constructor will synchronously call\n // onNetworkConnected if there is an active network.\n networkManager = new NetworkManager(context, this);\n }\n\n public static AnalyticsWrapper get(Context context) {\n if (singleton == null) {\n singleton = new AnalyticsWrapper(context);\n }\n return singleton;\n }\n\n @Override\n public void onNetworkConnected(NetworkInfo networkInfo) {\n this.networkInfo = networkInfo;\n }\n\n @Override\n public void onNetworkDisconnected() {\n this.networkInfo = null;\n }\n\n private NetworkTypes getNetworkType() {\n NetworkInfo info = networkInfo; // For atomicity against network updates in a different thread.\n if (info == null) {\n return NetworkTypes.NONE;\n }\n int type = info.getType();\n if (type == ConnectivityManager.TYPE_MOBILE) {\n return NetworkTypes.MOBILE;\n } else if (type == ConnectivityManager.TYPE_WIFI) {\n return NetworkTypes.WIFI;\n }\n return NetworkTypes.OTHER;\n }\n\n private void log(Events e, @NonNull BundleBuilder b) {\n String deviceCountry = countryCode.getDeviceCountry().toUpperCase(Locale.ROOT);\n String networkCountry = countryCode.getNetworkCountry().toUpperCase(Locale.ROOT);\n if (!deviceCountry.isEmpty() && !networkCountry.isEmpty()\n && !deviceCountry.equals(networkCountry)) {\n // The country codes disagree (e.g. device is roaming), so the effective network location is\n // unclear. Report the ISO code for \"unknown or unspecified\".\n networkCountry = \"ZZ\";\n }\n b.put(Params.DEVICE_COUNTRY, deviceCountry);\n b.put(Params.NETWORK_COUNTRY, networkCountry);\n b.put(Params.NETWORK_TYPE, getNetworkType().name());\n analytics.logEvent(e.name(), b.build());\n }\n\n /**\n * The DOH server connection was established successfully.\n * @param server The DOH server hostname for analytics.\n * @param latencyMs How long bootstrap took.\n */\n public void logBootstrap(String server, int latencyMs) {\n log(Events.BOOTSTRAP, new BundleBuilder()\n .put(Params.SERVER, server)\n .put(Params.LATENCY, latencyMs));\n }\n\n /**\n * The DOH server connection failed to establish successfully.\n * @param server The DOH server hostname.\n */\n public void logBootstrapFailed(String server) {\n log(Events.BOOTSTRAP_FAILED, new BundleBuilder().put(Params.SERVER, server));\n }\n\n /**\n * A connected TCP socket closed.\n * @param upload total bytes uploaded over the lifetime of a socket\n * @param download total bytes downloaded\n * @param port TCP port number (i.e. protocol type)\n * @param tcpHandshakeMs TCP handshake latency in milliseconds\n * @param duration socket lifetime in seconds\n * TODO: Add firstByteMs, the time between socket open and first byte from server.\n */\n public void logTCP(long upload, long download, int port, int tcpHandshakeMs, int duration) {\n log(Events.BYTES, new BundleBuilder()\n .put(Params.UPLOAD, upload)\n .put(Params.DOWNLOAD, download)\n .put(Params.PORT, port)\n .put(Params.TCP_HANDSHAKE_MS, tcpHandshakeMs)\n .put(Params.DURATION, duration));\n }\n\n /**\n * A TCP socket connected, but then failed after some bytes were uploaded, without receiving any\n * downstream data, triggering a retry.\n * @param bytes Amount uploaded before failure\n * @param chunks Number of upload writes before reset\n * @param timeout Whether the initial connection failed with a timeout\n * @param split Number of bytes included in the first retry segment\n * @param success Whether retry resulted in success (i.e. downstream data received)\n */\n public void logEarlyReset(int bytes, int chunks, boolean timeout, int split, boolean success) {\n log(Events.EARLY_RESET, new BundleBuilder()\n .put(Params.BYTES, bytes)\n .put(Params.CHUNKS, chunks)\n .put(Params.TIMEOUT, timeout ? 1 : 0)\n .put(Params.SPLIT, split)\n .put(Params.RETRY, success ? 1 : 0));\n }\n\n /**\n * The VPN was established.\n * @param mode The VpnAdapter implementation in use.\n */\n public void logStartVPN(String mode) {\n log(Events.STARTVPN, new BundleBuilder().put(Params.MODE, mode));\n }\n\n /**\n * Try-all concluded with the user approving a server.\n * @param server The selected server.\n */\n public void logTryAllAccepted(String server) {\n log(Events.TRY_ALL_ACCEPTED, new BundleBuilder().put(Params.SERVER, server));\n }\n\n /**\n * Try-all concluded with a user cancellation.\n * @param server The selected server.\n */\n public void logTryAllCancelled(String server) {\n log(Events.TRY_ALL_CANCELLED, new BundleBuilder().put(Params.SERVER, server));\n }\n\n /**\n * Try-all reached the point of showing the user a confirmation dialog.\n * @param server The selected server.\n */\n public void logTryAllDialog(String server) {\n log(Events.TRY_ALL_DIALOG, new BundleBuilder().put(Params.SERVER, server));\n }\n\n /**\n * Try-all failed to find any working server.\n */\n public void logTryAllFailed() {\n log(Events.TRY_ALL_FAILED, new BundleBuilder());\n }\n\n /**\n * The user requested try-all.\n */\n public void logTryAllRequested() {\n log(Events.TRY_ALL_REQUESTED, new BundleBuilder());\n }\n\n /**\n * A UDP association has concluded\n * @param upload Number of bytes uploaded on this association\n * @param download Number of bytes downloaded on this association\n * @param duration Duration of the association in seconds.\n */\n public void logUDP(long upload, long download, int duration) {\n log(Events.UDP, new BundleBuilder()\n .put(Params.UPLOAD, upload)\n .put(Params.DOWNLOAD, download)\n .put(Params.DURATION, duration));\n }\n}", "public class LogWrapper {\n public static void logException(Throwable t) {\n Log.e(\"LogWrapper\", \"Error\", t);\n if (BuildConfig.DEBUG) {\n return;\n }\n try {\n FirebaseCrashlytics.getInstance().recordException(t);\n } catch (IllegalStateException e) {\n // This only occurs during unit tests.\n }\n }\n\n public static void log(int severity, String tag, String message) {\n Log.println(severity, tag, message);\n if (BuildConfig.DEBUG) {\n return;\n }\n try {\n FirebaseCrashlytics.getInstance().log(tag + \": \" + message);\n } catch (IllegalStateException e) {\n // This only occurs during unit tests.\n }\n }\n}", "public class RemoteConfig {\n public static Task<Boolean> update() {\n try {\n FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();\n return config.fetchAndActivate();\n } catch (IllegalStateException e) {\n LogWrapper.logException(e);\n return Tasks.forResult(false);\n }\n }\n\n static String getExtraIPKey(String domain) {\n // Convert everything to lowercase for consistency.\n // The only allowed characters in a remote config key are A-Z, a-z, 0-9, and _.\n return \"extra_ips_\" + domain.toLowerCase(Locale.ROOT).replaceAll(\"\\\\W\", \"_\");\n }\n\n // Returns any additional IPs known for this domain, as a string containing a comma-separated\n // list, or the empty string if none are known.\n public static String getExtraIPs(String domain) {\n try {\n return FirebaseRemoteConfig.getInstance().getString(getExtraIPKey(domain));\n } catch (IllegalStateException e) {\n LogWrapper.logException(e);\n return \"\";\n }\n }\n\n public static boolean getChoirEnabled() {\n try {\n return FirebaseRemoteConfig.getInstance().getBoolean(\"choir\");\n } catch (IllegalStateException e) {\n LogWrapper.logException(e);\n return false;\n }\n }\n}" ]
import android.content.Context; import android.content.res.Resources; import android.net.VpnService; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.ParcelFileDescriptor; import android.os.SystemClock; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import app.intra.R; import app.intra.sys.CountryCode; import app.intra.sys.IntraVpnService; import app.intra.sys.PersistentState; import app.intra.sys.VpnController; import app.intra.sys.firebase.AnalyticsWrapper; import app.intra.sys.firebase.LogWrapper; import app.intra.sys.firebase.RemoteConfig; import doh.Transport; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Locale; import protect.Protector; import tun2socks.Tun2socks;
public static GoVpnAdapter establish(@NonNull IntraVpnService vpnService) { ParcelFileDescriptor tunFd = establishVpn(vpnService); if (tunFd == null) { return null; } return new GoVpnAdapter(vpnService, tunFd); } private GoVpnAdapter(IntraVpnService vpnService, ParcelFileDescriptor tunFd) { this.vpnService = vpnService; this.tunFd = tunFd; } public synchronized void start() { connectTunnel(); } private void connectTunnel() { if (tunnel != null) { return; } // VPN parameters final String fakeDns = FAKE_DNS_IP + ":" + DNS_DEFAULT_PORT; // Strip leading "/" from ip:port string. listener = new GoIntraListener(vpnService); String dohURL = PersistentState.getServerUrl(vpnService); try { LogWrapper.log(Log.INFO, LOG_TAG, "Starting go-tun2socks"); Transport transport = makeDohTransport(dohURL); // connectIntraTunnel makes a copy of the file descriptor. tunnel = Tun2socks.connectIntraTunnel(tunFd.getFd(), fakeDns, transport, getProtector(), listener); } catch (Exception e) { LogWrapper.logException(e); VpnController.getInstance().onConnectionStateChanged(vpnService, IntraVpnService.State.FAILING); return; } if (RemoteConfig.getChoirEnabled()) { enableChoir(); } } // Set up failure reporting with Choir. private void enableChoir() { CountryCode countryCode = new CountryCode(vpnService); @NonNull String country = countryCode.getNetworkCountry(); if (country.isEmpty()) { country = countryCode.getDeviceCountry(); } if (country.isEmpty()) { // Country code is mandatory for Choir. Log.i(LOG_TAG, "No country code found"); return; } String file = vpnService.getFilesDir() + File.separator + CHOIR_FILENAME; try { tunnel.enableSNIReporter(file, "intra.metrics.gstatic.com", country); } catch (Exception e) { // Choir setup failure is logged but otherwise ignored, because it does not prevent Intra // from functioning correctly. LogWrapper.logException(e); } } private static ParcelFileDescriptor establishVpn(IntraVpnService vpnService) { try { VpnService.Builder builder = vpnService.newBuilder() .setSession("Intra go-tun2socks VPN") .setMtu(VPN_INTERFACE_MTU) .addAddress(LanIp.GATEWAY.make(IPV4_TEMPLATE), IPV4_PREFIX_LENGTH) .addRoute("0.0.0.0", 0) .addDnsServer(LanIp.DNS.make(IPV4_TEMPLATE)); if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { builder.addDisallowedApplication(vpnService.getPackageName()); } if (VERSION.SDK_INT >= VERSION_CODES.Q) { builder.setMetered(false); // There's no charge for using Intra. } return builder.establish(); } catch (Exception e) { LogWrapper.logException(e); return null; } } private @Nullable Protector getProtector() { if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { // We don't need socket protection in these versions because the call to // "addDisallowedApplication" effectively protects all sockets in this app. return null; } return vpnService; } public synchronized void close() { if (tunnel != null) { tunnel.disconnect(); } if (tunFd != null) { try { tunFd.close(); } catch (IOException e) { LogWrapper.logException(e); } } tunFd = null; } private doh.Transport makeDohTransport(@Nullable String url) throws Exception { @NonNull String realUrl = PersistentState.expandUrl(vpnService, url); String dohIPs = getIpString(vpnService, realUrl); String host = new URL(realUrl).getHost(); long startTime = SystemClock.elapsedRealtime(); final doh.Transport transport; try { transport = Tun2socks.newDoHTransport(realUrl, dohIPs, getProtector(), null, listener); } catch (Exception e) {
AnalyticsWrapper.get(vpnService).logBootstrapFailed(host);
4
Mangopay/cardregistration-android-kit
mangopay/src/main/java/com/mangopay/android/sdk/domain/GetTokenInteractorImpl.java
[ "public interface GetTokenInteractor {\n interface Callback {\n void onGetTokenSuccess(String response);\n\n void onGetTokenError(MangoException error);\n }\n\n void execute(Callback callback, String cardRegistrationURL, String preregistrationData,\n String accessKeyRef, String cardNumber, String cardExpirationDate, String cardCvx);\n\n}", "public interface CardService {\n\n void post(String url, List<AbstractMap.SimpleEntry<String, String>> params,\n String acceptHeader, ServiceCallback callback);\n}", "public class CardServiceImpl implements CardService {\n\n @SuppressWarnings(\"unchecked\")\n @Override public void post(String mURL, List<AbstractMap.SimpleEntry<String, String>> params,\n String acceptHeader, ServiceCallback callback) {\n try {\n URL obj = new URL(mURL);\n HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection();\n\n connection.setConnectTimeout((int) SECONDS.toMillis(30));\n connection.setReadTimeout((int) SECONDS.toMillis(30));\n\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Content-type\", \"application/x-www-form-urlencoded\");\n connection.setRequestProperty(\"Accept\", acceptHeader);\n connection.setDoInput(true);\n connection.setDoOutput(true);\n\n PrintLog.debug(\"Started get token request\\n\" + connection.getRequestMethod() + \": \" + mURL);\n\n OutputStream os = connection.getOutputStream();\n BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, \"UTF-8\"));\n writer.write(TextUtil.getQuery(params));\n writer.flush();\n writer.close();\n os.close();\n\n connection.connect();\n\n int responseCode = connection.getResponseCode();\n StringBuilder response = new StringBuilder();\n if (responseCode == HttpsURLConnection.HTTP_OK) {\n String line;\n BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n while ((line = br.readLine()) != null) {\n response.append(line);\n }\n callback.success(response.toString());\n } else {\n String line;\n BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));\n while ((line = br.readLine()) != null) {\n response.append(line);\n }\n\n MangoException error = JsonUtil.getMangoError(callback, response.toString());\n if (error != null) {\n if (error.getMessage() == null) {\n error = new MangoException(ErrorCode.SERVER_ERROR.getValue(),\n connection.getResponseMessage());\n }\n callback.failure(error);\n }\n }\n connection.disconnect();\n } catch (IOException e) {\n callback.failure(new MangoException(e));\n PrintLog.error(e.getMessage());\n }\n }\n}", "public interface ServiceCallback<T> {\n\n void success(T jsonResponse);\n\n void failure(MangoException error);\n}", "public interface Executor {\n\n void run(final Interactor interactor);\n}", "public interface Interactor {\n\n void run();\n}", "public interface MainThread {\n\n void post(final Runnable runnable);\n}", "public class CreateTokenRequest extends RequestObject {\n\n private String data;\n private String accessKeyRef;\n private String cardNumber;\n private String cardExpirationDate;\n private String cardCvx;\n\n public CreateTokenRequest(String data, String accessKeyRef, String cardNumber,\n String cardExpirationDate, String cardCvx) {\n this.data = data;\n this.accessKeyRef = accessKeyRef;\n this.cardNumber = cardNumber;\n this.cardExpirationDate = cardExpirationDate;\n this.cardCvx = cardCvx;\n }\n\n public String getData() {\n return data;\n }\n\n public String getAccessKeyRef() {\n return accessKeyRef;\n }\n\n public String getCardNumber() {\n return cardNumber;\n }\n\n public String getCardExpirationDate() {\n return cardExpirationDate;\n }\n\n public String getCardCvx() {\n return cardCvx;\n }\n\n}", "public class MangoException extends RuntimeException {\n\n private String id;\n private String type;\n private long timestamp;\n\n public MangoException(Throwable throwable) {\n super(throwable);\n this.id = ErrorCode.SDK_ERROR.getValue();\n this.timestamp = System.currentTimeMillis();\n }\n\n public MangoException(String id, String message) {\n this(id, message, null);\n }\n\n public MangoException(String id, String message, String type) {\n super(message);\n this.id = id;\n this.type = type;\n this.timestamp = System.currentTimeMillis();\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n @Override public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n MangoException error = (MangoException) o;\n\n return !(id != null ? !id.equals(error.id) : error.id != null);\n\n }\n\n @Override public int hashCode() {\n return id != null ? id.hashCode() : 0;\n }\n\n @Override public String toString() {\n return \"MangoError{\" +\n \"id='\" + id + '\\'' +\n \", message='\" + getMessage() + '\\'' +\n \", type='\" + type + '\\'' +\n \", timestamp=\" + timestamp +\n '}';\n }\n}" ]
import com.mangopay.android.sdk.domain.api.GetTokenInteractor; import com.mangopay.android.sdk.domain.service.CardService; import com.mangopay.android.sdk.domain.service.CardServiceImpl; import com.mangopay.android.sdk.domain.service.ServiceCallback; import com.mangopay.android.sdk.executor.Executor; import com.mangopay.android.sdk.executor.Interactor; import com.mangopay.android.sdk.executor.MainThread; import com.mangopay.android.sdk.model.CreateTokenRequest; import com.mangopay.android.sdk.model.exception.MangoException;
package com.mangopay.android.sdk.domain; /** * Get Token request implementation */ public class GetTokenInteractorImpl extends BaseInteractorImpl<CardService> implements Interactor, GetTokenInteractor { private String mRegistrationURL; private String mPreData; private String mAccessKey; private String mCardNumber; private String mExpirationDate; private String mCardCvx; private Callback mCallback; public GetTokenInteractorImpl(Executor executor, MainThread mainThread) { super(executor, mainThread, new CardServiceImpl()); } @Override public void execute(Callback callback, String cardRegistrationURL, String preregistrationData, String accessKeyRef, String cardNumber, String cardExpirationDate, String cardCvx) { validateCallbackSpecified(callback); this.mCallback = callback; this.mRegistrationURL = cardRegistrationURL; this.mPreData = preregistrationData; this.mAccessKey = accessKeyRef; this.mCardNumber = cardNumber; this.mExpirationDate = cardExpirationDate; this.mCardCvx = cardCvx; this.mExecutor.run(this); } @Override public void run() { CreateTokenRequest requestBody = new CreateTokenRequest(mPreData, mAccessKey, mCardNumber, mExpirationDate, mCardCvx);
ServiceCallback<String> callback = new ServiceCallback<String>() {
3
WorldSEnder/MCAnm
src/main/java/com/github/worldsender/mcanm/client/mcanmmodel/parts/Point.java
[ "public class BoneBinding {\n\t/** To be interpreted as unsigned */\n\tpublic byte boneIndex;\n\tpublic float bindingValue;\n\n\tpublic static BoneBinding[] readMultipleFrom(DataInputStream di) throws IOException {\n\t\tBoneBinding[] bindings = new BoneBinding[RawDataV1.MAX_NBR_BONEBINDINGS];\n\t\tint bindIndex;\n\t\tint i = 0;\n\t\twhile (i < RawDataV1.MAX_NBR_BONEBINDINGS && (bindIndex = di.readUnsignedByte()) != 0xFF) {\n\t\t\tBoneBinding binding = new BoneBinding();\n\t\t\t// Read strength of binding\n\t\t\tfloat bindingValue = di.readFloat();\n\t\t\tif (Math.abs(bindingValue) > 100.0F || bindingValue < 0)\n\t\t\t\tthrow new ModelFormatException(\n\t\t\t\t\t\tString.format(\n\t\t\t\t\t\t\t\t\"Value for binding seems out of range: %f (expected to be in [0, 100]\",\n\t\t\t\t\t\t\t\tbindingValue));\n\t\t\t// Apply attributes\n\t\t\tbinding.boneIndex = (byte) bindIndex;\n\t\t\tbinding.bindingValue = bindingValue;\n\t\t\tbindings[i++] = binding;\n\t\t}\n\t\treturn Arrays.copyOf(bindings, i);\n\t}\n}", "public class TesselationPoint {\n\tpublic Vector3f coords;\n\tpublic Vector3f normal;\n\tpublic Vector2f texCoords;\n\tpublic BoneBinding[] boneBindings;\n\n\tpublic static TesselationPoint readFrom(DataInputStream di) throws IOException {\n\t\tTesselationPoint tessP = new TesselationPoint();\n\t\t// Read coords\n\t\tVector3f coords = Utils.readVector3f(di);\n\t\t// Read normal\n\t\tVector3f normal = Utils.readVector3f(di);\n\t\tif (normal.length() == 0)\n\t\t\tthrow new ModelFormatException(\"Normal vector can't have zerolength.\");\n\t\t// Read materialIndex coordinates\n\t\tVector2f texCoords = Utils.readVector2f(di);\n\t\t// Read bindings\n\t\tBoneBinding[] bindings = BoneBinding.readMultipleFrom(di);\n\t\t// Apply attributes\n\t\ttessP.coords = coords;\n\t\ttessP.normal = normal;\n\t\ttessP.texCoords = texCoords;\n\t\ttessP.boneBindings = bindings;\n\t\treturn tessP;\n\t}\n}", "public interface ITesselator {\n\n\tvoid setTextureUV(double u, double v);\n\n\tvoid setNormal(float x, float y, float z);\n\n\tvoid addVertex(double x, double y, double z);\n}", "public interface IBone {\n\tpublic static final IBone STATIC_BONE = new IBone() {\n\t\t@Override\n\t\tpublic void transformNormal(Vector3f normal) {}\n\n\t\t@Override\n\t\tpublic void transformToLocal(Matrix4f matrix) {}\n\n\t\t@Override\n\t\tpublic void transformFromLocal(Matrix4f matrix) {}\n\n\t\t@Override\n\t\tpublic void transform(Point4f position) {}\n\n\t\t@Override\n\t\tpublic void transform(Matrix4f matrix) {}\n\t};\n\n\t/**\n\t * Transforms the matrix given by the transformation currently acted out by the specified bone. Assumes that the\n\t * matrix describes a transformation relative to the bone's origin.\n\t *\n\t * @param position\n\t * the position to transform\n\t */\n\tvoid transformFromLocal(Matrix4f matrix);\n\n\tvoid transformToLocal(Matrix4f matrix);\n\n\t/**\n\t * Transforms the matrix given by the transformation currently acted out by the specified bone. The matrix describes\n\t * a transformation relative to the skeleton's origin.\n\t *\n\t * @param position\n\t * the position to transform\n\t */\n\tvoid transform(Matrix4f matrix);\n\n\t/**\n\t * Transforms the position given by the transformation currently acted out by the specified bone.\n\t *\n\t * @param position\n\t * the position to transform\n\t */\n\tvoid transform(Point4f position);\n\n\t/**\n\t * Transforms the normal given by the transformation currently acted out by the specified bone.\n\t *\n\t * @param position\n\t * the position to transform\n\t */\n\tvoid transformNormal(Vector3f normal);\n}", "public interface ISkeleton {\n\tpublic static final ISkeleton EMPTY = new ISkeleton() {\n\n\t\t@Override\n\t\tpublic void setup(IAnimation animation, float frame) {}\n\n\t\t@Override\n\t\tpublic IBone getBoneByName(String bone) {\n\t\t\treturn IBone.STATIC_BONE;\n\t\t}\n\n\t\t@Override\n\t\tpublic IBone getBoneByIndex(int index) {\n\t\t\treturn IBone.STATIC_BONE;\n\t\t}\n\n\t\t@Override\n\t\tpublic void debugDraw(Tessellator tess) {}\n\t};\n\n\tIBone getBoneByName(String bone);\n\n\tIBone getBoneByIndex(int index);\n\n\t/**\n\t * Sets up the Skeleton for the animation given\n\t */\n\tvoid setup(IAnimation animation, float frame);\n\n\t/**\n\t * Added for debug, don't actually use this, especially when on the server\n\t * \n\t * @param tess\n\t */\n\tvoid debugDraw(Tessellator tess);\n\n\t@Override\n\tboolean equals(Object obj);\n\n\t@Override\n\tint hashCode();\n}" ]
import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.vecmath.Point4f; import javax.vecmath.Tuple2f; import javax.vecmath.Tuple3f; import javax.vecmath.Tuple4f; import javax.vecmath.Vector2f; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.BoneBinding; import com.github.worldsender.mcanm.client.mcanmmodel.visitor.TesselationPoint; import com.github.worldsender.mcanm.client.renderer.ITesselator; import com.github.worldsender.mcanm.common.skeleton.IBone; import com.github.worldsender.mcanm.common.skeleton.ISkeleton; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad;
package com.github.worldsender.mcanm.client.mcanmmodel.parts; public class Point { private static class BoundPoint extends Point { private static class Binding { // Used as a buffer, doesn't requite to always create new // temporaries. Prevents parallelization, though private static Point4f posBuff = new Point4f(); private static Vector3f normBuff = new Vector3f(); private IBone bone; private float strength; public Binding(IBone bone, float strenght) { this.bone = Objects.requireNonNull(bone); this.strength = strenght; } /** * Computes the transformed and weighted position of the given vertex. Adds that to the target vertex. * * @param base * the vertex to transform * @param trgt * the vertex to add to. If null is given, it is just assigned to * @return the final vertex, a new vertex if <code>null</code> was given */ public void addTransformed(Vertex base, Vertex trgt) { Objects.requireNonNull(base); Objects.requireNonNull(trgt); base.getPosition(posBuff); base.getNormal(normBuff); // Transform points with matrix this.bone.transform(posBuff); this.bone.transformNormal(normBuff); posBuff.scale(this.strength); normBuff.scale(this.strength); trgt.offset(posBuff); trgt.addNormal(normBuff); } public void normalize(float sum) { this.strength /= sum; } } private List<Binding> binds; private Vertex transformed;
public BoundPoint(Vector3f pos, Vector3f norm, Vector2f uv, BoneBinding[] readBinds, ISkeleton skelet) {
0
onesocialweb/osw-openfire-plugin
src/java/org/onesocialweb/openfire/handler/MessageEventInterceptor.java
[ "@SuppressWarnings(\"serial\")\npublic class AccessDeniedException extends Exception {\n\n\tpublic AccessDeniedException(String message) {\n\t\tsuper(message);\n\t}\n\t\n}", "@SuppressWarnings(\"serial\")\npublic class InvalidRelationException extends Exception {\n\n\tpublic InvalidRelationException(String message) {\n\t\tsuper(message);\n\t}\n\t\n}", "public class PEPActivityHandler extends PEPNodeHandler {\n\n\tpublic static String NODE = \"urn:xmpp:microblog:0\";\n\t\n\tprivate XMPPServer server;\n\t\n\tprivate Map<String, PEPCommandHandler> handlers = new ConcurrentHashMap<String, PEPCommandHandler>();\n\n\tpublic PEPActivityHandler() {\n\t\tsuper(\"Handler for PEP microbloging PEP node\");\n\t}\n\t\t\n\t@Override\n\tpublic String getNode() {\n\t\treturn NODE;\n\t}\n\n\t@Override\n\tpublic void initialize(XMPPServer server) {\n\t\tsuper.initialize(server);\n\t\tthis.server = server;\n\t\taddHandler(new ActivityPublishHandler());\n\t\taddHandler(new ActivityQueryHandler());\n\t\taddHandler(new ActivityDeleteHandler());\n\t\taddHandler(new ActivitySubscribeHandler());\n\t\taddHandler(new ActivityUnsubscribeHandler());\n\t\taddHandler(new ActivitySubscribersHandler());\n\t\taddHandler(new ActivitySubscriptionsHandler());\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic IQ handleIQ(IQ packet) throws UnauthorizedException {\n\t\t// We search for a handler based on the element name\n\t\t// and process the packet with the handler if found.\n final Element childElement = packet.getChildElement();\n final List<Element> pubsubElements = childElement.elements();\t\n\n if (pubsubElements != null && pubsubElements.size() > 0) {\n \tElement actionElement = pubsubElements.get(0);\n \tPEPCommandHandler handler = getHandler(actionElement.getName());\n\t\t\tif (handler != null) {\n\t\t\t\treturn handler.handleIQ(packet);\n\t\t\t}\n\t\t}\n\n\t\t// No valid hanlder found. Return a feature not implemented\n\t\t// error.\n\t\tIQ result = IQ.createResultIQ(packet);\n\t\tresult.setChildElement(packet.getChildElement().createCopy());\n\t\tresult.setError(PacketError.Condition.feature_not_implemented);\n\t\treturn result;\n\t}\n\n\tprivate void addHandler(PEPCommandHandler handler) {\n\t\thandler.initialize(server);\n\t\thandlers.put(handler.getCommand(), handler);\n\t}\n\n\tprivate PEPCommandHandler getHandler(String name) {\n\t\treturn handlers.get(name);\n\t}\n\n}", "public class ActivityManager {\n\n\t/**\n\t * Singleton: keep a static reference to teh only instance\n\t */\n\tprivate static ActivityManager instance;\n\n\tpublic static ActivityManager getInstance() {\n\t\tif (instance == null) {\n\t\t\t// Carefull, we are in a threaded environment !\n\t\t\tsynchronized (ActivityManager.class) {\n\t\t\t\tinstance = new ActivityManager();\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Class dependencies \n\t * TODO Make this a true dependency injection\n\t */\n\tprivate final ActivityFactory activityFactory;\n\n\tprivate final AclFactory aclFactory;\n\n\t/**\n\t * Publish a new activity to the activity stream of the given user.\n\t * activity-actor element is overwrittern using the user profile data to\n\t * avoid spoofing. Notifications messages are sent to the users subscribed\n\t * to this user activities.\n\t * \n\t * @param user\n\t * The user who the activity belongs to\n\t * @param entry\n\t * The activity entry to publish\n\t * @throws UserNotFoundException\n\t */\n\tpublic void publishActivity(String userJID, ActivityEntry entry) throws UserNotFoundException {\n\t\t// Overide the actor to avoid spoofing\n\t\tUser user = UserManager.getInstance().getUser(new JID(userJID).getNode());\n\t\tActivityActor actor = activityFactory.actor();\n\t\tactor.setUri(userJID);\n\t\tactor.setName(user.getName());\n\t\tactor.setEmail(user.getEmail());\n\n\t\t// Persist the activities\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\tentry.setId(DefaultAtomHelper.generateId());\n\t\tfor (ActivityObject object : entry.getObjects()) {\n\t\t\tobject.setId(DefaultAtomHelper.generateId());\n\t\t}\n\t\tentry.setActor(actor);\n\t\tentry.setPublished(Calendar.getInstance().getTime());\n\t\tem.persist(entry);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// Broadcast the notifications\n\t\tnotify(userJID, entry);\n\t}\n\t\n\t/**\n\t * Updates an activity in the activity stream of the given user.\n\t * activity-actor element is overwrittern using the user profile data to\n\t * avoid spoofing. Notifications messages are sent to the users subscribed\n\t * to this user activities.\n\t * \n\t * @param user\n\t * The user who the activity belongs to\n\t * @param entry\n\t * The activity entry to update\n\t * @throws UserNotFoundException\n\t */\n\tpublic void updateActivity(String userJID, ActivityEntry entry) throws UserNotFoundException, UnauthorizedException {\n\t\t// Overide the actor to avoid spoofing\n\t\tUser user = UserManager.getInstance().getUser(new JID(userJID).getNode());\n\t\tActivityActor actor = activityFactory.actor();\n\t\tactor.setUri(userJID);\n\t\tactor.setName(user.getName());\n\t\tactor.setEmail(user.getEmail());\n\t\t\n\t\t// Persist the activities\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\tPersistentActivityEntry oldEntry=em.find(PersistentActivityEntry.class, entry.getId());\n\t\t\n\t\tif ((oldEntry==null) || (!oldEntry.getActor().getUri().equalsIgnoreCase(userJID)))\n\t\t\tthrow new UnauthorizedException();\n\t\t\n\t\t\n\t\tDate published=oldEntry.getPublished();\n\t\tentry.setPublished(published);\n\t\tentry.setUpdated(Calendar.getInstance().getTime());\n\t\t\n\t\tem.remove(oldEntry);\n\t\t\n\t\tentry.setActor(actor);\n\t\tem.persist(entry);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// Broadcast the notifications\n\t\tnotify(userJID, entry);\n\t}\n\t\n\tpublic void deleteActivity(String fromJID, String activityId) throws UnauthorizedException {\n\t\t\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\t\n\t\tPersistentActivityEntry activity= em.find(PersistentActivityEntry.class, activityId);\n\t\t\n\t\tif ((activity==null) || (!activity.getActor().getUri().equalsIgnoreCase(fromJID)))\n\t\t\tthrow new UnauthorizedException();\n\t\t\n\t\tem.remove(activity);\n\t\t\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t\t\n\t\tnotifyDelete(fromJID, activityId);\n\t}\n\t\n\tpublic void deleteMessage(String activityId) {\n\t\t\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\t\n\t\tQuery query = em.createQuery(\"SELECT x FROM Messages x WHERE x.activity.id = ?1\");\n\t\tquery.setParameter(1, activityId);\t\t\n\t\tList<ActivityMessage> messages = query.getResultList();\n\t\tfor (ActivityMessage message:messages){\n\t\t\tem.remove(message);\n\t\t}\n\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t}\n\n\t/**\n\t * Retrieve the last activities of the target user, taking into account the\n\t * access rights of the requesting user.\n\t * \n\t * @param requestorJID\n\t * the user requesting the activities\n\t * @param targetJID\n\t * the user whose activities are requested\n\t * @return an immutable list of the last activities of the target entity that can be seen by the\n\t * requesting entity\n\t * @throws UserNotFoundException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<ActivityEntry> getActivities(String requestorJID, String targetJID) throws UserNotFoundException {\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT DISTINCT entry FROM ActivityEntry entry\" + \" JOIN entry.rules rule \"\n\t\t\t\t+ \" JOIN rule.actions action \" + \" JOIN rule.subjects subject \"\n\t\t\t\t+ \" WHERE entry.actor.uri = :target \" + \" AND action.name = :view \"\n\t\t\t\t+ \" AND action.permission = :grant \" + \" AND (subject.type = :everyone \"\n\t\t\t\t+ \" OR (subject.type = :group_type \" + \" AND subject.name IN (:groups)) \"\n\t\t\t\t+ \" OR (subject.type = :person \" + \" AND subject.name = :jid)) ORDER BY entry.published DESC\");\n\n\t\t// Parametrize the query\n\t\tquery.setParameter(\"target\", targetJID);\n\t\tquery.setParameter(\"view\", AclAction.ACTION_VIEW);\n\t\tquery.setParameter(\"grant\", AclAction.PERMISSION_GRANT);\n\t\tquery.setParameter(\"everyone\", AclSubject.EVERYONE);\n\t\tquery.setParameter(\"group_type\", AclSubject.GROUP);\n\t\tquery.setParameter(\"groups\", getGroups(targetJID, requestorJID));\n\t\tquery.setParameter(\"person\", AclSubject.PERSON);\n\t\tquery.setParameter(\"jid\", requestorJID);\n\t\tquery.setMaxResults(20);\n\t\tList<ActivityEntry> result = query.getResultList();\n\t\tem.close();\n\n\t\treturn Collections.unmodifiableList(result);\n\t}\n\n\t/**\n\t * Handle an activity pubsub event. Such a message is usually\n\t * received by a user in these conditions: - the local user has subscribed\n\t * to the remote user activities - the local user is \"mentionned\" in this\n\t * activity - this activity relates to another activity of the local user\n\t * \n\t * @param remoteJID\n\t * the entity sending the message\n\t * @param localJID\n\t * the entity having received the message\n\t * @param activity\n\t * the activity contained in the message\n\t * @throws InvalidActivityException\n\t * @throws AccessDeniedException\n\t */\n\tpublic synchronized void handleMessage(String remoteJID, String localJID, ActivityEntry activity) throws InvalidActivityException, AccessDeniedException {\n\n\t\t// Validate the activity\n\t\tif (activity == null || !activity.hasId()) {\n\t\t\tthrow new InvalidActivityException();\n\t\t}\n\t\t\n\t\t// Create a message for the recipient\n\t\tActivityMessage message = new PersistentActivityMessage();\n\t\tmessage.setSender(remoteJID);\n\t\tmessage.setRecipient(localJID);\n\t\t//in case of an activity update we keep the received date as the date of\n\t\t//original publish, otherwise the updated posts will start showing on top of\n\t\t// the inbox..which we agreed we don't want...\n\t\tmessage.setReceived(activity.getPublished());\n\n\t\t// Search if the activity exists in the database\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tPersistentActivityEntry previousActivity = em.find(PersistentActivityEntry.class, activity.getId());\n\n\t\t// Assign the activity to the existing one if it exists\n\t\tif (previousActivity != null) {\n\t\t\tmessage.setActivity(previousActivity);\n\t\t} else {\n\t\t\tmessage.setActivity(activity);\n\t\t}\n\t\t\n\t\t//in case of an update the message will already exist in the DB\n\t\tQuery query = em.createQuery(\"SELECT x FROM Messages x WHERE x.activity.id = ?1\");\n\t\tquery.setParameter(1, activity.getId());\t\t\n\t\tList<ActivityMessage> messages = query.getResultList();\n\t\t\n\t\tem.getTransaction().begin();\n\t\tfor (ActivityMessage oldMessage:messages){\n\t\t\tif (oldMessage.getRecipient().equalsIgnoreCase(localJID))\n\t\t\t\tem.remove(oldMessage);\n\t\t}\n\t\tem.getTransaction().commit();\n\n\t\t// We go ahead and post the message to the recipient mailbox\n\t\tem.getTransaction().begin();\n\t\tem.persist(message);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t\t\t\t\n\t}\n\t\n\t\n\t\n\t/**\n\t * Subscribe an entity to another entity activities.\n\t * \n\t * @param from the subscriber\n\t * @param to entity being subscribed to\n\t * @throws AlreadySubscribed\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic synchronized void subscribe(String from, String to) {\n\t\t\n\t\t// Check if it already exist\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.subscriber = ?1 AND x.target = ?2\");\n\t\tquery.setParameter(1, from);\n\t\tquery.setParameter(2, to);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\t\n\t\t// If already exist, we don't have anything left to do\n\t\tif (subscriptions != null && subscriptions.size() > 0) {\n\t\t\tem.close();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Add the subscription\n\t\tSubscription subscription = new PersistentSubscription();\n\t\tsubscription.setSubscriber(from);\n\t\tsubscription.setTarget(to);\n\t\tsubscription.setCreated(Calendar.getInstance().getTime());\n\t\t\n\t\t// Store\n\t\tem.getTransaction().begin();\n\t\tem.persist(subscription);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\t\n\n\t/**\n\t * Delete a subscription.\n\t * \n\t * @param from the entity requesting to unsubscribe\n\t * @param to the subscription target\n\t * @throws SubscriptionNotFound\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic synchronized void unsubscribe(String from, String to) {\n\t\tEntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\t\n\t\t// Check if it already exist\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.subscriber = ?1 AND x.target = ?2\");\n\t\tquery.setParameter(1, from);\n\t\tquery.setParameter(2, to);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\t\n\t\t// If it does not exist, we don't have anything left to do \n\t\tif (subscriptions == null || subscriptions.size()== 0) {\n\t\t\tem.close();\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t// Remove the subscriptions\n\t\t// There should never be more than one.. but better safe than sorry\n\t\tem.getTransaction().begin();\n\t\tfor (Subscription activitySubscription : subscriptions) {\n\t\t\tem.remove(activitySubscription);\n\t\t}\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Subscription> getSubscribers(String targetJID) {\n\t\t// Get a list of people who are interested by this stuff\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.target = ?1\");\n\t\tquery.setParameter(1, targetJID);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\tem.close();\n\t\treturn subscriptions;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Subscription> getSubscriptions(String subscriberJID) {\n\t\t// Get a list of people who are interested by this stuff\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Subscriptions x WHERE x.subscriber = ?1\");\n\t\tquery.setParameter(1, subscriberJID);\n\t\tList<Subscription> subscriptions = query.getResultList();\n\t\tem.close();\n\t\treturn subscriptions;\n\t}\n\n\tprivate void notify(String fromJID, ActivityEntry entry) throws UserNotFoundException {\n\n\t\t// TODO We may want to do some cleaning of activities before\n\t\t// forwarding them (e.g. remove the acl, it is no one business)\n\t\tfinal ActivityDomWriter writer = new DefaultActivityDomWriter();\n\t\tfinal XMPPServer server = XMPPServer.getInstance();\n\t\tfinal List<Subscription> subscriptions = getSubscribers(fromJID);\n\t//\tfinal Roster roster = XMPPServer.getInstance().getRosterManager().getRoster(new JID(fromJID).getNode());\n\t\tfinal DOMDocument domDocument = new DOMDocument();\n\n\t\t// Prepare the message\n\t\tfinal Element entryElement = (Element) domDocument.appendChild(domDocument.createElementNS(Atom.NAMESPACE, Atom.ENTRY_ELEMENT));\n\t\twriter.write(entry, entryElement);\n\t\tdomDocument.removeChild(entryElement);\n\n\t\tfinal Message message = new Message();\n\t\tmessage.setFrom(fromJID);\n\t\tmessage.setBody(\"New activity: \" + entry.getTitle());\n\t\tmessage.setType(Message.Type.headline);\n\t\torg.dom4j.Element eventElement = message.addChildElement(\"event\", \"http://jabber.org/protocol/pubsub#event\");\n\t\torg.dom4j.Element itemsElement = eventElement.addElement(\"items\");\n\t\titemsElement.addAttribute(\"node\", PEPActivityHandler.NODE);\n\t\torg.dom4j.Element itemElement = itemsElement.addElement(\"item\");\n\t\titemElement.addAttribute(\"id\", entry.getId());\n\t\titemElement.add((org.dom4j.Element) entryElement);\n\n\t\t// Keep a list of people we sent it to avoid duplicates\n\t\tList<String> alreadySent = new ArrayList<String>();\n\t\t\n\t\t// Send to this user\n\t\talreadySent.add(fromJID);\n\t\tmessage.setTo(fromJID);\n\t\tserver.getMessageRouter().route(message);\t\n\t\t\t\t\t\t\n\t\t// Send to all subscribers\n\t\tfor (Subscription activitySubscription : subscriptions) {\n\t\t\tString recipientJID = activitySubscription.getSubscriber();\n\t\t\tif (!canSee(fromJID, entry, recipientJID)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\talreadySent.add(recipientJID);\t\t\t\t\t\t\n\t\t\tmessage.setTo(recipientJID);\n\t\t\tserver.getMessageRouter().route(message);\t\n\t\t}\n\n\t\t// Send to recipients, if they can see it and have not already received it\n\t\tif (entry.hasRecipients()) {\n\t\t\tfor (AtomReplyTo recipient : entry.getRecipients()) {\n\t\t\t\t//TODO This is dirty, the recipient should be an IRI etc...\n\t\t\t\tString recipientJID = recipient.getHref(); \n\t\t\t\tif (!alreadySent.contains(recipientJID) && canSee(fromJID, entry, recipientJID)) {\n\t\t\t\t\talreadySent.add(fromJID);\n\t\t\t\t\t\n\t\t\t\t\tmessage.setTo(recipientJID);\n\t\t\t\t\tserver.getMessageRouter().route(message);\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\t\t\t\n\t}\n\t\n\n\tprivate void notifyDelete(String fromJID, String activityId) {\n\n\t\t\n\t\tfinal XMPPServer server = XMPPServer.getInstance();\n\t\tfinal List<Subscription> subscriptions = getSubscribers(fromJID);\n\t\n\t\t// Prepare the message\n\t\t\n\t\tfinal Message message = new Message();\n\t\tmessage.setFrom(fromJID);\n\t\tmessage.setBody(\"Delete activity: \" + activityId);\n\t\tmessage.setType(Message.Type.headline);\n\t\t\n\t\torg.dom4j.Element eventElement = message.addChildElement(\"event\", \"http://jabber.org/protocol/pubsub#event\");\n\t\torg.dom4j.Element itemsElement = eventElement.addElement(\"items\");\n\t\titemsElement.addAttribute(\"node\", PEPActivityHandler.NODE);\n\t\torg.dom4j.Element retractElement = itemsElement.addElement(\"retract\");\n\t\tretractElement.addAttribute(\"id\", activityId);\n\t\t\n\n\t\t// Keep a list of people we sent it to avoid duplicates\n\t\tList<String> alreadySent = new ArrayList<String>();\n\t\t\n\t\t// Send to this user\n\t\talreadySent.add(fromJID);\n\t\tmessage.setTo(fromJID);\n\t\tserver.getMessageRouter().route(message);\t\n\t\t\t\t\t\t\n\t\t// Send to all subscribers\n\t\tfor (Subscription activitySubscription : subscriptions) {\n\t\t\tString recipientJID = activitySubscription.getSubscriber();\t\t\t\n\t\t\talreadySent.add(recipientJID);\t\t\t\t\t\t\n\t\t\tmessage.setTo(recipientJID);\n\t\t\tserver.getMessageRouter().route(message);\t\n\t\t}\t\t\t\n\t\t\n\t}\n\t\n\tprivate List<String> getGroups(String ownerJID, String userJID) {\n\t\tRosterManager rosterManager = XMPPServer.getInstance().getRosterManager();\n\t\tRoster roster;\n\t\ttry {\n\t\t\troster = rosterManager.getRoster(new JID(ownerJID).getNode());\n\t\t\tRosterItem rosterItem = roster.getRosterItem(new JID(userJID));\n\t\t\tif (rosterItem != null) {\n\t\t\t\treturn rosterItem.getGroups();\n\t\t\t}\n\t\t} catch (UserNotFoundException e) {\n\t\t}\n\n\t\treturn new ArrayList<String>();\n\t}\n\n\tprivate boolean canSee(String fromJID, ActivityEntry entry, String viewer) throws UserNotFoundException {\n\t\t// Get a view action\n\t\tfinal AclAction viewAction = aclFactory.aclAction(AclAction.ACTION_VIEW, AclAction.PERMISSION_GRANT);\n\t\tAclRule rule = null;\n\t\tfor (AclRule aclRule : entry.getAclRules()) {\n\t\t\tif (aclRule.hasAction(viewAction)) {\n\t\t\t\trule = aclRule;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// If no view action was found, we consider it is denied\n\t\tif (rule == null)\n\t\t\treturn false;\n\t\t\n\t\treturn AclManager.canSee(fromJID, rule, viewer);\n\t\t\n\t}\n\n\t/**\n\t * Private constructor to enforce the singleton\n\t */\n\tprivate ActivityManager() {\n\t\tactivityFactory = new PersistentActivityFactory();\n\t\taclFactory = new PersistentAclFactory();\n\t}\n}", "public class RelationManager {\n\n\tpublic static final String NODE = \"http://onesocialweb.org/spec/1.0/relations\";\n\t\n\t/**\n\t * Singleton: keep a static reference to teh only instance\n\t */\n\tprivate static RelationManager instance;\n\n\tpublic static RelationManager getInstance() {\n\t\tif (instance == null) {\n\t\t\t// Carefull, we are in a threaded environment !\n\t\t\tsynchronized (RelationManager.class) {\n\t\t\t\tinstance = new RelationManager();\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Retrieves the relation of the target user as can be seen by the requesting user.\n\t * \n\t * TODO ACL is not yet implemented. All relations are returned at this stage.\n\t * \n\t * @param requestorJID the entity requesting the relations.\n\t * @param targetJID the entity whose relations are requested.\n\t * @return the list of relations of the target user, as can be seen by the requestor \n\t * @throws UserNotFoundException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic List<Relation> getRelations(String requestorJID, String targetJID) throws UserNotFoundException {\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT DISTINCT relation FROM Relation relation WHERE relation.owner = :target\");\n\n\t\t// Parametrize the query\n\t\tquery.setParameter(\"target\", targetJID);\n\t\tList<Relation> result = query.getResultList();\n\t\tem.close();\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Setup a new relation.\n\t * \n\t * @param userJID the user seting up the new relation\n\t * @param relation the relation to setup\n\t * @throws InvalidRelationException\n\t */\n\tpublic void setupRelation(String userJID, PersistentRelation relation) throws InvalidRelationException {\n\t\t// Validate the relation request\n\t\t// TODO More should be validated here\n\t\tif (!relation.hasFrom() || !relation.hasTo() || !relation.hasNature()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing required elements\");\n\t\t}\n\n\t\t// Verify that the from or to is the user making the request\n\t\tif (!(relation.getFrom().equals(userJID) || relation.getTo().equals(userJID))) {\n\t\t\tthrow new InvalidRelationException(\"Must be part of the relation to create it\");\n\t\t}\n\n\t\t// Assign a unique ID to this new relation\n\t\trelation.setId(DefaultAtomHelper.generateId());\n\n\t\t// Set the request status\n\t\trelation.setStatus(Relation.Status.REQUEST);\n\n\t\t// We store the relation for requestor\n\t\trelation.setOwner(userJID);\n\n\t\t// Persist the relation\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tem.getTransaction().begin();\n\t\tem.persist(relation);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// We cleanup and notifiy the relation for the recipient\n\t\trelation.setAclRules(null);\n\t\trelation.setComment(null);\n\t\tnotify(userJID, relation);\n\t}\n\n\t/**\n\t * Update an existing relation.\n\t * \n\t * @param userJID the user seting up the new relation\n\t * @param relation the relation to setup\n\t * @throws InvalidRelationException\n\t */\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void updateRelation(String userJID, PersistentRelation relation) throws InvalidRelationException {\n\t\t// Validate the relation request\n\t\t// TODO More should be validated here\n\t\tif (!relation.hasId() || !relation.hasStatus()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing required elements\");\n\t\t}\n\n\t\t// Search for an existing relation with the given ID\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Relation x WHERE x.owner = ?1 AND x.guid = ?2\");\n\t\tquery.setParameter(1, userJID);\n\t\tquery.setParameter(2, relation.getId());\n\t\tList<PersistentRelation> relations = query.getResultList();\n\n\t\t// If no match, or more than one, we have an issue\n\t\tif (relations.size() != 1) {\n\t\t\tthrow new InvalidRelationException(\"Could not find relationship with id \" + relation.getId());\n\t\t}\n\n\t\t// We update the persisted relation\n\t\tem.getTransaction().begin();\n\t\tPersistentRelation storedRelation = relations.get(0);\n\t\tstoredRelation.setStatus(relation.getStatus());\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\n\t\t// We cleanup and notifiy the relation for the recipient\n\t\tstoredRelation.setAclRules(null);\n\t\tstoredRelation.setComment(null);\n\t\tnotify(userJID, storedRelation);\n\t}\n\n\t/**\n\t * Handles a relation notification message.\n\t * \n\t * @param remoteJID the entity sending the message\n\t * @param localJID the entity having received the message\n\t * @param relation the relation being notified\n\t * @throws InvalidRelationException\n\t */\n\tpublic void handleMessage(String remoteJID, String localJID, Relation relation) throws InvalidRelationException {\n\t\t// We need at least a status field\n\t\tif (!relation.hasStatus()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing a status field\");\n\t\t}\n\n\t\t// Is this a new request ?\n\t\tif (relation.getStatus().equals(Relation.Status.REQUEST)) {\n\t\t\thandleRequestMessage(remoteJID, localJID, relation);\n\t\t} else {\n\t\t\thandleUpdateMessage(remoteJID, localJID, relation);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void handleRequestMessage(String remoteJID, String localJID, Relation relation) throws InvalidRelationException {\n\t\t// Are required fields for a new relation setup present ?\n\t\tif (!relation.hasNature() || !relation.hasStatus() || !relation.hasFrom() || !relation.hasTo() || !relation.hasId()) {\n\t\t\tthrow new InvalidRelationException(\"Relation is missing required elements\");\n\t\t}\n\n\t\t// The relation should be between the sender and the receiver\n\t\tif (getDirection(relation, remoteJID, localJID) == 0) {\n\t\t\tthrow new InvalidRelationException(\"Relation from/to do not match message from/to\");\n\t\t}\n\n\t\t// Cannot add a relation to yourself\n\t\tif (relation.getFrom().equals(relation.getTo())) {\n\t\t\tthrow new InvalidRelationException(\"Cannot add relation to yourself\");\n\t\t}\n\n\t\t// Verify that this relation is not already here\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Relation x WHERE x.owner = ?1 AND x.guid = ?2\");\n\t\tquery.setParameter(1, localJID);\n\t\tquery.setParameter(2, relation.getId());\n\t\tList<PersistentRelation> relations = query.getResultList();\n\n\t\t// If there is a match, we give up\n\t\t// TODO Not that fast. The other end may jut have not received any\n\t\t// answer and wants to try again\n\t\t// we should deal with all these recovery features.\n\t\tif (relations.size() > 0) {\n\t\t\tthrow new InvalidRelationException(\"This relation has already been requested\");\n\t\t}\n\n\t\t// Save the relation\n\t\tPersistentRelation persistentRelation = (PersistentRelation) relation;\n\t\tpersistentRelation.setOwner(localJID);\n\n\t\tem.getTransaction().begin();\n\t\tem.persist(persistentRelation);\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void handleUpdateMessage(String remoteJID, String localJID, Relation relation) throws InvalidRelationException {\n\t\t// Search for the stored relation\n\t\tfinal EntityManager em = OswPlugin.getEmFactory().createEntityManager();\n\t\tQuery query = em.createQuery(\"SELECT x FROM Relation x WHERE x.owner = ?1 AND x.guid = ?2\");\n\t\tquery.setParameter(1, localJID);\n\t\tquery.setParameter(2, relation.getId());\n\t\tList<PersistentRelation> relations = query.getResultList();\n\n\t\t// If no match, or more than one, we have an issue\n\t\tif (relations.size() != 1) {\n\t\t\tthrow new InvalidRelationException(\"Could not find matching relationship\");\n\t\t}\n\n\t\t// We update the persisted relation\n\t\tem.getTransaction().begin();\n\t\tPersistentRelation previous = relations.get(0);\n\t\tprevious.setStatus(relation.getStatus());\n\t\tem.getTransaction().commit();\n\t\tem.close();\n\t}\n\n\tprivate void notify(String localJID, Relation relation) {\n\t\tfinal DOMDocument domDocument = new DOMDocument();\n\t\tfinal Element entryElement = (Element) domDocument.appendChild(domDocument.createElementNS(Onesocialweb.NAMESPACE, Onesocialweb.RELATION_ELEMENT));\n\t\tfinal RelationDomWriter writer = new DefaultRelationDomWriter();\n\t\twriter.write(relation, entryElement);\n\t\tdomDocument.removeChild(entryElement);\n\n\t\tfinal Message message = new Message();\n\t\tmessage.setFrom(localJID);\n\t\tmessage.setType(Message.Type.headline);\n\t\torg.dom4j.Element eventElement = message.addChildElement(\"event\", \"http://jabber.org/protocol/pubsub#event\");\n\t\torg.dom4j.Element itemsElement = eventElement.addElement(\"items\");\n\t\titemsElement.addAttribute(\"node\", NODE);\n\t\torg.dom4j.Element itemElement = itemsElement.addElement(\"item\");\n\t\titemElement.addAttribute(\"id\", relation.getId());\n\t\titemElement.add((org.dom4j.Element) entryElement);\n\n\t\t// Send to this user\n\t\tmessage.setTo(getOtherEnd(relation, localJID));\n\t\tserver.getMessageRouter().route(message);\n\t}\n\n\tprivate String getOtherEnd(Relation relation, String userJID) {\n\t\tif (!relation.hasFrom() || !relation.hasTo()) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (relation.getFrom().equals(userJID)) {\n\t\t\treturn relation.getTo();\n\t\t}\n\n\t\tif (relation.getTo().equals(userJID)) {\n\t\t\treturn relation.getFrom();\n\t\t}\n\n\t\t// The given JID is no part of this relation\n\t\treturn null;\n\t}\n\n\tprivate int getDirection(Relation relation, String fromJID, String toJID) {\n\t\tif (!relation.hasFrom() || !relation.hasTo()) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (relation.getFrom().equals(fromJID) && relation.getTo().equals(toJID)) {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (relation.getFrom().equals(toJID) && relation.getTo().equals(fromJID)) {\n\t\t\treturn -1;\n\t\t}\n\n\t\t// If we are here, the relation does not concern from & to\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Class dependencies (should be true dependency injection someday)\n\t */\n\n\tprivate final XMPPServer server;\n\n\t/**\n\t * Private constructor to enforce the singleton\n\t */\n\tprivate RelationManager() {\n\t\tserver = XMPPServer.getInstance();\n\t}\n\n}", "public class PersistentActivityDomReader extends ActivityDomReader {\n\n\t@Override\n\tprotected AclDomReader getAclDomReader() {\n\t\treturn new PersistentAclDomReader();\n\t}\n\n\t@Override\n\tprotected ActivityFactory getActivityFactory() {\n\t\treturn new PersistentActivityFactory();\n\t}\n\n\t@Override\n\tprotected AtomDomReader getAtomDomReader() {\n\t\treturn new PersistentAtomDomReader();\n\t}\n\n\t@Override\n\tprotected Date parseDate(String atomDate) {\n\t\treturn DefaultAtomHelper.parseDate(atomDate);\n\t}\n\n}", "public class PersistentRelationDomReader extends RelationDomReader {\n\n\t@Override\n\tprotected AclDomReader getAclDomReader() {\n\t\treturn new PersistentAclDomReader();\n\t}\n\n\t@Override\n\tprotected RelationFactory getRelationFactory() {\n\t\treturn new PersistentRelationFactory();\n\t}\n\n}" ]
import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.activity.InvalidActivityException; import org.dom4j.Element; import org.jivesoftware.openfire.SessionManager; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.interceptor.PacketInterceptor; import org.jivesoftware.openfire.interceptor.PacketRejectedException; import org.jivesoftware.openfire.session.ClientSession; import org.jivesoftware.openfire.session.Session; import org.jivesoftware.util.Log; import org.onesocialweb.model.activity.ActivityEntry; import org.onesocialweb.model.relation.Relation; import org.onesocialweb.openfire.exception.AccessDeniedException; import org.onesocialweb.openfire.exception.InvalidRelationException; import org.onesocialweb.openfire.handler.activity.PEPActivityHandler; import org.onesocialweb.openfire.manager.ActivityManager; import org.onesocialweb.openfire.manager.RelationManager; import org.onesocialweb.openfire.model.activity.PersistentActivityDomReader; import org.onesocialweb.openfire.model.relation.PersistentRelationDomReader; import org.onesocialweb.xml.dom.ActivityDomReader; import org.onesocialweb.xml.dom.RelationDomReader; import org.onesocialweb.xml.dom4j.ElementAdapter; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet;
/* * Copyright 2010 Vodafone Group Services Ltd. * * 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 org.onesocialweb.openfire.handler; public class MessageEventInterceptor implements PacketInterceptor { private final XMPPServer server; public MessageEventInterceptor() { server = XMPPServer.getInstance(); } @SuppressWarnings( { "deprecation", "unchecked" }) public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) throws PacketRejectedException { // We only care for incoming Messages has not yet been processed if (incoming && !processed && packet instanceof Message) { final Message message = (Message) packet; final JID fromJID = message.getFrom(); final JID toJID = message.getTo(); // We are only interested by message to bareJID (we don't touch the one sent to fullJID) if (!toJID.toBareJID().equalsIgnoreCase(toJID.toString())) { return; } // We only care for messaes to local users if (!server.isLocal(toJID) || !server.getUserManager().isRegisteredUser(toJID)) { return; } // We only bother about pubsub events Element eventElement = message.getChildElement("event", "http://jabber.org/protocol/pubsub#event"); if (eventElement == null) { return; } // That contains items Element itemsElement = eventElement.element("items"); if (itemsElement == null || itemsElement.attribute("node") == null) return; // Relating to the microblogging node if (itemsElement.attribute("node").getValue().equals( PEPActivityHandler.NODE)) { Log.debug("Processing an activity event from " + fromJID + " to " + toJID); final ActivityDomReader reader = new PersistentActivityDomReader(); List<Element> items=(List<Element>) itemsElement.elements("item"); if ((items!=null) && (items.size()!=0)){ for (Element itemElement :items) { ActivityEntry activity = reader .readEntry(new ElementAdapter(itemElement .element("entry"))); try { ActivityManager.getInstance().handleMessage( fromJID.toBareJID(), toJID.toBareJID(), activity); } catch (InvalidActivityException e) { throw new PacketRejectedException();
} catch (AccessDeniedException e) {
0
ervinsae/EZCode
app/src/main/java/com/ervin/litepal/MainActivity.java
[ "public class BaseActivity extends AppCompatActivity {\n\n @Override\n public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {\n super.onCreate(savedInstanceState, persistentState);\n\n }\n\n}", "public class HomeActivity extends BaseActivity implements View.OnClickListener,ListView.OnItemClickListener,FragmentCallback{\n\n private DrawerLayout drawerLayout;\n private View drawer;\n private ListView menuList;\n\n private FragmentManager fragmentManager;\n private Fragment mContent;\n private HomeFragment homeFragment;\n private ModeFragment modeFragment;\n private AboutFragment aboutFragment;\n private SettingFragment settingFragment;\n private RetrofitFragment retrofitFragment;\n private MeizhiFragment meizhiFragment;\n\n private CircleImageView ivAavatar;\n\n private int imageIcon[] = {R.mipmap.ic_navview_explore,R.mipmap.ic_navview_map,R.mipmap.ic_navview_my_schedule,\n R.mipmap.ic_navview_play_circle_fill,R.mipmap.ic_navview_social,R.mipmap.ic_navview_settings,R.mipmap.ic_navview_video_library};\n\n private int imageStr[] = {R.string.menu_home,R.string.menu_Mode,R.string.menu_retrofit,\n R.string.menu_profile,R.string.menu_setting,R.string.menu_about,R.string.menu_meizhi};\n\n public HomeActivity getActivity(){\n return this;\n }\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_drawer_main);\n\n initView();\n fragmentManager = getSupportFragmentManager();\n homeFragment = new HomeFragment();\n modeFragment = new ModeFragment();\n aboutFragment = new AboutFragment();\n settingFragment = new SettingFragment();\n retrofitFragment = new RetrofitFragment();\n meizhiFragment = new MeizhiFragment();\n\n mContent = homeFragment; // 默认Fragment\n fragmentManager.beginTransaction().replace(R.id.content_main, mContent).commit();\n menuList.setAdapter(new MenuAdapter());\n }\n\n private void initView() {\n ivAavatar = (CircleImageView) findViewById(R.id.iv_avatar);\n drawer = findViewById(R.id.left_drawer);\n drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);\n menuList = (ListView) findViewById(R.id.menu_list);\n menuList.setOnItemClickListener(this);\n\n ivAavatar.setOnClickListener(this);\n }\n\n @Override\n public void onClick(View v) {\n switch (v.getId()){\n case R.id.show_drawer:\n menuSetting();\n break;\n case R.id.iv_avatar:\n Intent intent = new Intent(this,ProfileActivity.class);\n startActivity(intent);\n break;\n }\n }\n\n public void menuSetting() {\n if(drawerLayout.isDrawerOpen(drawer)){\n drawerLayout.closeDrawers();\n }else{\n drawerLayout.openDrawer(drawer);\n }\n }\n\n @Override\n public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n switch (position){\n case 0:\n switchFragment(position,homeFragment);\n break;\n case 1:\n switchFragment(position,modeFragment);\n break;\n case 2:\n //Login();\n switchFragment(position,retrofitFragment);\n break;\n case 3:\n /* FrameLayout ff = (FrameLayout) getActivity().findViewById(R.id.content_main);\n LinearLayout ll =*/\n Intent intent = new Intent(HomeActivity.this,CategoryActivity.class);\n startActivity(intent);\n break;\n case 4:\n /*Intent intent2 = new Intent(HomeActivity.this,SettingActivity.class);\n startActivity(intent2);*/\n switchFragment(position,settingFragment);\n break;\n case 5:\n /*Intent intent3 = new Intent(HomeActivity.this,AboutActivity.class);\n startActivity(intent3);*/\n switchFragment(position,aboutFragment);\n break;\n case 6:\n switchFragment(position,meizhiFragment);\n break;\n }\n }\n\n @Override\n public void callbackMenuSetting(Bundle args) {\n menuSetting();\n }\n\n public void switchFragment(int position,Fragment fragment){\n if(! fragment.isAdded()) {\n fragmentManager.beginTransaction().replace(R.id.content_main, fragment).commit();\n }\n menuList.setItemChecked(position,true);\n drawerLayout.closeDrawer(drawer);\n }\n\n public class MenuAdapter extends BaseAdapter{\n\n @Override\n public int getCount() {\n return imageIcon.length;\n }\n\n @Override\n public Object getItem(int position) {\n return null;\n }\n\n @Override\n public long getItemId(int position) {\n return 0;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n convertView = View.inflate(HomeActivity.this,R.layout.menu_list_item,null);\n TextView tvItem = (TextView) convertView.findViewById(R.id.tv_menu_item);\n tvItem.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(convertView.getContext(),imageIcon[position]),null,null,null);\n tvItem.setText(getResources().getString(imageStr[position]));\n return convertView;\n }\n }\n\n}", "public class WelcomeFragments extends Fragment {\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n super.onCreateView(inflater, container, savedInstanceState);\n return inflater.inflate(R.layout.fragment_main,container,false);\n }\n}", "public final class BusProvider {\n private static final Bus BUS = new Bus();\n\n public static Bus getInstance() {\n return BUS;\n }\n\n private BusProvider() {\n // No instances.\n }\n}", "public class EventBase {\n\n\n}", "public class SyncEvent extends EventBase {\n\n public static final int SUCCESS = 0;\n public static final int FAIL = 1;\n\n public int code;\n public SyncEvent(int code){\n this.code = code;\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.ervin.litepal.ui.BaseActivity; import com.ervin.litepal.ui.HomeActivity; import com.ervin.litepal.ui.fragment.WelcomeFragments; import com.ervin.litepal.event.BusProvider; import com.ervin.litepal.event.EventBase; import com.ervin.litepal.event.SyncEvent; import com.squareup.otto.Subscribe;
package com.ervin.litepal; public class MainActivity extends BaseActivity implements View.OnClickListener{ Button btn; Button decline; Fragment fragment; private TextView tvTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btn); decline = (Button) findViewById(R.id.button_decline); btn.setOnClickListener(this); decline.setOnClickListener(this); tvTitle = (TextView) findViewById(R.id.toolbar_center_title); tvTitle.setText(R.string.welcome); fragment = new WelcomeFragments(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.welcome_content, fragment); fragmentTransaction.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn: enterHome(); break; case R.id.button_decline: finish(); break; } } private void enterHome(){ Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); } @Override protected void onResume() { super.onResume();
BusProvider.getInstance().register(this);
3
Catherine22/MobileManager
app/src/main/java/com/itheima/mobilesafe/SplashActivity.java
[ "@SuppressWarnings(\"unused\")\npublic class CLog {\n private static final boolean DEBUG = BuildConfig.SHOW_LOG;\n\n public static String getTag() {\n String tag = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n if (ste[i].getMethodName().equals(\"getTag\")) {\n tag = \"(\" + ste[i + 1].getFileName() + \":\" + ste[i + 1].getLineNumber() + \")\";\n }\n }\n return tag;\n }\n\n public static void v(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.v(tab, message);\n }\n }\n\n public static void d(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.d(tab, message);\n }\n }\n\n public static void e(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.e(tab, message);\n }\n }\n\n public static void w(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.w(tab, message);\n }\n }\n\n public static void i(String tab, String message) {\n if (MyApplication.getInstance().getPackageName().contains(\".test\") || DEBUG) {\n Config.showDebugLog = true;\n Log.i(tab, message);\n }\n }\n\n}", "public class Constants {\n //Tags of the fragments\n public final static int ANTI_THEFT_FRAG = 0;\n public final static int APPS_MAG_FRAG = 2;\n public final static int TASK_FRAG = 3;\n public final static int A_TOOLS_FRAG = 7;\n public final static int SETTINGS_FRAG = 8;\n public final static int SETUP1_FRAG = 9;\n public final static int SETUP2_FRAG = 10;\n public final static int SETUP3_FRAG = 11;\n public final static int SETUP4_FRAG = 12;\n public final static int SETUP_FRAG = 13;\n public final static int CONTACTS_FRAG = 14;\n public final static int NUM_ADDRESS_QUERY_FRAG = 15;\n public final static int BLACKLIST_FRAG = 16;\n public final static int TRAFFIC_MAG_FRAG = 17;\n public final static int ANTI_VIRUS_FRAG = 18;\n public final static int CLEAR_CACHE_FRAG = 19;\n\n //activity request code\n public final static int REQUEST_CODE_ENABLE_ADMIN = 10001;\n public final static int PERMISSION_OVERLAY = 10002;\n public final static int PERMISSION_WRITE_SETTINGS = 10003;\n public final static int CHANGEING_DEFAULT_SMS_APP = 10004;\n public final static int ACCOUNT_KIT_REQ_CODE = 10005;\n public final static int UNINSTASLL_APP = 10006;\n public final static int OPEN_SETTINGS = 10007;\n public final static int ACCESS_PERMISSION = 10008;\n\n //response code\n public static final int FAILED_TO_SEND = 0;\n public static final int SENT_SUCCESSFULLY = 1;\n public static final int TIMEOUT = 2;\n\n public static String[] addressBgs = new String[]{\"半透明\", \"活力橙\", \"卫士蓝\", \"金属灰\", \"苹果绿\"};\n public static int[] addressBgRes = new int[]{R.drawable.call_locate_white, R.drawable.call_locate_orange, R.drawable.call_locate_blue, R.drawable.call_locate_gray, R.drawable.call_locate_green};\n\n //Login\n public final static int NONE = 0;\n public final static int ACCOUNTKIT = 1;\n public final static int FB = 2;\n public final static int GOOGLE = 3;\n public final static int SINA = 4;\n public final static int QQ = 5;\n public final static int WEIBO = 6;\n public final static int WECHAT = 7;\n public static String[] loginAccounts = new String[]{\"NONE\", \"AccountKit\", \"Facebook\", \"Google\", \"Sina\", \"QQ\", \"Weibo\", \"WeChat\"};\n}", "public class SecurityUtils {\n\n private final static String TAG = \"SecurityUtils\";\n private final static String APK_KEY = \"A6550F699983450DBBF65E5C41687B\";\n private final static String MODULUS = \"AKfszhN0I/O12wcJ+r4wX0Im//5+pGeSFCXo4jOH18khVsspwgDaZgUJRxYIeK87kDOmk8U1j01Rsx2UFlThMjfwT9oliR1K/QihIujN7dgLSnBHh8wWXBI+P+hZq01uF2qrvWZQ+t2JySVBh7DO9uXxdjHrOLou97w3pjZzU4zn\";\n private final static String EXPONENT = \"AQAB\";\n\n /**\n *\n * @param ctx\n * @return\n * @throws PackageManager.NameNotFoundException\n * @throws NoSuchAlgorithmException\n */\n public boolean verifyApk(Context ctx) throws PackageManager.NameNotFoundException, NoSuchAlgorithmException {\n PackageInfo pkgInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_META_DATA | PackageManager.GET_SIGNATURES);\n Bundle bundle = pkgInfo.applicationInfo.metaData;\n if (!bundle.containsKey(\"Catherine.secret.key\")) {\n CLog.e(TAG, \"Error meta-data\");\n return false;\n } else {\n String SDKKey = bundle.getString(\"Catherine.secret.key\");\n\n //SHA1 fingerprint\n String strResult = \"\";\n for (Signature signature : pkgInfo.signatures) {\n MessageDigest md = MessageDigest.getInstance(\"SHA1\");\n md.update(signature.toByteArray());\n for (byte b : md.digest()) {\n String strAppend = Integer.toString(b & 0xff, 16);\n if (strAppend.length() == 1)\n strResult += \"0\";\n strResult += strAppend;\n }\n strResult = strResult.toUpperCase();\n }\n CLog.d(TAG, strResult);\n\n //两两交换位置\n String rawSignature = strResult;\n try {\n String[] a = rawSignature.split(\"\");\n String[] b = rawSignature.split(\"\");\n String temp = \"\";\n for (int i = 1; i <= rawSignature.length() - 1; i = i + 2) {\n if ((i + 1) > rawSignature.length()) break;\n String c = a[i];\n a[i] = b[i + 1];\n b[i + 1] = c;\n temp += a[i] + b[i + 1];\n }\n rawSignature = temp;\n } catch (Exception e) {\n rawSignature = \"\";\n }\n CLog.d(TAG, rawSignature);\n\n String encodeKey;\n byte[] data;\n try {\n data = rawSignature.getBytes(\"UTF-8\");\n encodeKey = Base64.encodeToString(data, Base64.DEFAULT);\n } catch (Exception e) {\n encodeKey = \"\";\n }\n CLog.d(TAG, \"encodeKey:\" + encodeKey);\n\n String decodeKey;\n try {\n byte[] data1 = Base64.decode(SDKKey, Base64.DEFAULT);\n\n decodeKey = new String(data1, \"UTF-8\");\n } catch (Exception e) {\n decodeKey = \"\";\n }\n CLog.d(TAG, \"decodeKey:\" + decodeKey);\n\n //private key = \"Catherine\"\n // 根据定义secret key的规则调整(目前是base64编码(yyyyMMdd + \"Catherine\" + (yyyyMMdd%2))),所以还原private key时要判断前面的逻辑。\n String privateKey;\n try {\n String rawF = decodeKey.substring(0, 8);\n String key = decodeKey.substring(8, decodeKey.length() - 1);\n String checkSum = decodeKey.substring(decodeKey.length() - 1, decodeKey.length());\n\n if ((Integer.parseInt(rawF) + Integer.parseInt(checkSum)) % 2 == 0)\n privateKey = key;\n else\n privateKey = \"\";\n } catch (Exception e) {\n privateKey = \"\";\n }\n CLog.d(TAG, \"privateKey:\" + privateKey);\n\n String apkKey = md5(privateKey + encodeKey).toUpperCase();\n CLog.d(TAG, \"apkKey:\" + apkKey);\n\n return APK_KEY.equals(apkKey);\n }\n }\n\n private static String md5(String s) {\n try {\n MessageDigest digest = java.security.MessageDigest.getInstance(\"MD5\");\n digest.update(s.getBytes());\n byte messageDigest[] = digest.digest();\n\n StringBuilder hexString = new StringBuilder();\n for (byte aMessageDigest : messageDigest)\n hexString.append(Integer.toHexString(0xFF & aMessageDigest));\n return hexString.toString();\n } catch (Exception e) {\n return \"\";\n }\n }\n\n\n /**\n * Decrypt messages by RSA algorithm<br>\n *\n * @param message\n * @return Original message\n * @throws NoSuchAlgorithmException\n * @throws NoSuchPaddingException\n * @throws InvalidKeyException\n * @throws IllegalBlockSizeException\n * @throws BadPaddingException\n * @throws UnsupportedEncodingException\n * @throws InvalidAlgorithmParameterException\n * @throws InvalidKeySpecException\n * @throws ClassNotFoundException\n */\n public static String decryptRSA(String message) throws NoSuchAlgorithmException, NoSuchPaddingException,\n InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException,\n InvalidAlgorithmParameterException, ClassNotFoundException, InvalidKeySpecException {\n Cipher c2 = Cipher.getInstance(Algorithm.rules.get(\"RSA\")); // 创建一个Cipher对象,注意这里用的算法需要和Key的算法匹配\n\n BigInteger m = new BigInteger(Base64.decode(MODULUS.getBytes(), Base64.DEFAULT));\n BigInteger e = new BigInteger(Base64.decode(EXPONENT.getBytes(), Base64.DEFAULT));\n c2.init(Cipher.DECRYPT_MODE, converStringToPublicKey(m, e)); // 设置Cipher为解密工作模式,需要把Key传进去\n byte[] decryptedData = c2.doFinal(Base64.decode(message.getBytes(), Base64.DEFAULT));\n return new String(decryptedData, Algorithm.CHARSET);\n }\n\n /**\n * You can component a publicKey by a specific pair of values - modulus and\n * exponent.\n *\n * @param modulus When you generate a new RSA KeyPair, you'd get a PrivateKey, a\n * modulus and an exponent.\n * @param exponent When you generate a new RSA KeyPair, you'd get a PrivateKey, a\n * modulus and an exponent.\n * @throws ClassNotFoundException\n * @throws NoSuchAlgorithmException\n * @throws InvalidKeySpecException\n */\n public static Key converStringToPublicKey(BigInteger modulus, BigInteger exponent)\n throws ClassNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException {\n byte[] modulusByteArry = modulus.toByteArray();\n byte[] exponentByteArry = exponent.toByteArray();\n\n // 由接收到的参数构造RSAPublicKeySpec对象\n RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(new BigInteger(modulusByteArry),\n new BigInteger(exponentByteArry));\n // 根据RSAPublicKeySpec对象获取公钥对象\n KeyFactory kFactory = KeyFactory.getInstance(Algorithm.KEYPAIR_ALGORITHM);\n PublicKey publicKey = kFactory.generatePublic(rsaPublicKeySpec);\n // System.out.println(\"==>public key: \" +\n // bytesToHexString(publicKey.getEncoded()));\n return publicKey;\n }\n\n\n static {\n //relate to LOCAL_MODULE in Android.mk\n System.loadLibrary(\"keys\");\n }\n\n public native String[] getAuthChain(String key);\n\n public native String getAuthentication();\n\n public native int getdynamicID(int timestamp);\n}", "public class Settings {\n public static int DISPLAY_WIDTH_PX;\n public static int DISPLAY_HEIGHT_PX;\n public static String simSerialNumber;\n public static String safePhone;\n\n public static final String BACKUP_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + \"/itheima/Backups/\";\n public static final String taoBaoGetAddressUrl = \"https://tcc.taobao.com/cc/json/mobile_tel_segment.htm\";//淘宝\n public static final String tenpayUrl = \"http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi\";//财付通\n}", "public class SpNames {\n //file\n public final static String FILE_CONFIG = \"config\";\n\n //parameters\n public final static String loginType = \"loginType\";\n public final static String configed = \"configed\";\n public final static String safe_phone = \"safe_phone\";\n public final static String password = \"password\";\n public final static String default_sms_app = \"default_sms_app\";\n public final static String update = \"update\";\n public final static String address_bg = \"address_bg\";\n public final static String sim_serial = \"sim_serial\";\n public final static String longitude = \"longitude\";\n public final static String latitude = \"latitude\";\n public final static String accutacy = \"accutacy\";\n public final static String address_x = \"address_x\";\n public final static String address_y = \"address_y\";\n public final static String first_open = \"first_open\";\n}", "public class StreamUtils {\n /**\n * @param is 输入流\n * @return String 返回的字符串\n * @throws IOException\n */\n public static String toString(InputStream is) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int len = 0;\n while ((len = is.read(buffer)) != -1) {\n baos.write(buffer, 0, len);\n }\n is.close();\n String result = baos.toString();\n baos.close();\n return result;\n }\n\n /**\n * 把一个inputstream里面的内容转化成一个byte[]\n */\n public static byte[] toBytes(InputStream is) throws Exception {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int len = 0;\n while ((len = is.read(buffer)) != -1) {\n bos.write(buffer, 0, len);\n }\n is.close();\n bos.flush();\n byte[] result = bos.toByteArray();\n //System.out.println(new String(result));\n return result;\n }\n\n /**\n * 解决中文乱码, 使用GBK\n * @param is 输入流\n * @return 返回的字符串\n * @throws Exception\n */\n public static String toGBKString(InputStream is) throws Exception {\n BufferedReader in = new BufferedReader(new InputStreamReader(is, \"GBK\"));\n StringBuffer buffer = new StringBuffer();\n String line = \"\";\n while ((line = in.readLine()) != null){\n buffer.append(line);\n }\n return buffer.toString();\n }\n}" ]
import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.BitmapFactory; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.DisplayMetrics; import android.view.animation.AlphaAnimation; import android.widget.TextView; import android.widget.Toast; import com.itheima.mobilesafe.utils.CLog; import com.itheima.mobilesafe.utils.Constants; import com.itheima.mobilesafe.utils.SecurityUtils; import com.itheima.mobilesafe.utils.Settings; import com.itheima.mobilesafe.utils.SpNames; import com.itheima.mobilesafe.utils.StreamUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException;
//进入主页面 enterHome(); dialog.dismiss(); } }); builder.setMessage(description); builder.setPositiveButton("立刻升级", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 下载APK,并且替换安装 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // sdcard存在 // afnal // FinalHttp finalhttp = new FinalHttp(); // finalhttp.download(apkurl, Environment // .getExternalStorageDirectory().getAbsolutePath() + "/mobilesafe2.0.apk", // new AjaxCallBack<File>() { // // @Override // public void onFailure(Throwable t, int errorNo, // String strMsg) { // t.printStackTrace(); // Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_LONG).show(); // super.onFailure(t, errorNo, strMsg); // } // // @Override // public void onLoading(long count, long current) { // // super.onLoading(count, current); // tv_update_info.setVisibility(View.VISIBLE); // //当前下载百分比 // int progress = (int) (current * 100 / count); // tv_update_info.setText("下载进度:" + progress + "%"); // } // // @Override // public void onSuccess(File t) { // // super.onSuccess(t); // installAPK(t); // } // // /** // * 安装APK // * @param t // */ // private void installAPK(File t) { // Intent intent = new Intent(); // intent.setAction("android.intent.action.VIEW"); // intent.addCategory("android.intent.category.DEFAULT"); // intent.setDataAndType(Uri.fromFile(t), "application/vnd.android.package-archive"); // // startActivity(intent); // // } // // // }); } else { Toast.makeText(getApplicationContext(), "没有sdcard,请安装上在试", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("下次再说", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); enterHome();// 进入主页面 } }); builder.show(); } protected void enterHome() { Intent intent = new Intent(this, HomeActivity.class); intent.putExtra("launchFromIntent", launchFromIntent); startActivity(intent); // 关闭当前页面 finish(); //必须要在finish()或startActivity()后面执行 overridePendingTransition(R.anim.tran_in, R.anim.tran_out); } /** * 得到应用程序的版本名称 */ private String getVersionName() { // 用来管理手机的APK PackageManager pm = getPackageManager(); try { // 得到知道APK的功能清单文件 PackageInfo info = pm.getPackageInfo(getPackageName(), 0); return info.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); return ""; } } /** * 取得设备信息 * 初始化数据库 */ private void initSettings() { //取得屏幕信息 DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics);
Settings.DISPLAY_WIDTH_PX = metrics.widthPixels;
3
instaclick/PDI-Plugin-Step-AMQP
src/test/java/com/instaclick/pentaho/plugin/amqp/processor/ProcessorFactoryTest.java
[ "public class AMQPPlugin extends BaseStep implements StepInterface\r\n{\r\n private AMQPPluginData data;\r\n private AMQPPluginMeta meta;\r\n\r\n final private ProcessorFactory factory = new ProcessorFactory();\r\n private Processor processor;\r\n\r\n private final TransListener transListener = new TransListener()\r\n {\r\n @Override\r\n public void transStarted(Trans trans) throws KettleException { }\r\n\r\n @Override\r\n public void transActive(Trans trans) { }\r\n\r\n @Override\r\n public void transFinished(Trans trans) throws KettleException\r\n {\r\n logMinimal(\"Trans Finished - transactional=\" + data.isTransactional);\r\n\r\n if ( ! data.isTransactional && ! data.activeConfirmation ) {\r\n return;\r\n }\r\n\r\n if (trans.getErrors() > 0) {\r\n logMinimal(String.format(\"Transformation failure, ignoring changes\", trans.getErrors()));\r\n onFailure();\r\n\r\n return;\r\n }\r\n\r\n if (isStopped()) {\r\n logMinimal(\"Transformation STOPPED, ignoring changes\");\r\n shutdown();\r\n return;\r\n }\r\n\r\n onSuccess();\r\n }\r\n };\r\n\r\n public AMQPPlugin(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)\r\n {\r\n super(stepMeta, stepDataInterface, copyNr, transMeta, trans);\r\n }\r\n\r\n @Override\r\n public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException, KettleStepException\r\n {\r\n meta = (AMQPPluginMeta) smi;\r\n data = (AMQPPluginData) sdi;\r\n Object[] r = getRow();\r\n\r\n if (first) {\r\n first = false;\r\n\r\n try {\r\n initPluginStep();\r\n } catch (Exception e) {\r\n throw new AMQPException(e.getMessage(), e);\r\n }\r\n\r\n try {\r\n processor.start();\r\n } catch (IOException e) {\r\n setOutputDone();\r\n throw new AMQPException(e.getMessage(), e);\r\n }\r\n }\r\n\r\n while ( ! isStopped()) {\r\n\r\n try {\r\n if ( ! processor.process(r)) {\r\n\r\n setOutputDone();\r\n\r\n return false;\r\n }\r\n } catch (IOException e) {\r\n throw new AMQPException(e.getMessage(), e);\r\n }\r\n\r\n // log progress\r\n if (checkFeedback(getLinesWritten())) {\r\n logBasic(String.format(\"liner %s\", getLinesWritten()));\r\n }\r\n\r\n return true;\r\n }\r\n\r\n setOutputDone();\r\n\r\n return false;\r\n }\r\n\r\n @Override\r\n public boolean init(StepMetaInterface smi, StepDataInterface sdi)\r\n {\r\n meta = (AMQPPluginMeta) smi;\r\n data = (AMQPPluginData) sdi;\r\n\r\n return super.init(smi, sdi);\r\n }\r\n\r\n /**\r\n * Initialize\r\n */\r\n private void initPluginStep() throws Exception\r\n {\r\n RowMetaInterface rowMeta = (getInputRowMeta() != null)\r\n ? (RowMetaInterface) getInputRowMeta().clone()\r\n : new RowMeta();\r\n\r\n // clone the input row structure and place it in our data object\r\n data.outputRowMeta = rowMeta;\r\n // use meta.getFields() to change it, so it reflects the output row structure\r\n meta.getFields(rowMeta, getStepname(), null, null, this, repository, metaStore);\r\n\r\n Integer port = null;\r\n String body = environmentSubstitute(meta.getBodyField());\r\n String routing = environmentSubstitute(meta.getRouting());\r\n String uri = environmentSubstitute(meta.getUri());\r\n String host = environmentSubstitute(meta.getHost());\r\n String vhost = environmentSubstitute(meta.getVhost());\r\n String username = environmentSubstitute(meta.getUsername());\r\n String deliveryTagField = environmentSubstitute(meta.getDeliveryTagField());\r\n String password = decryptPasswordOptionallyEncrypted(environmentSubstitute(meta.getPassword()));\r\n\r\n if ( ! Const.isEmpty(meta.getPort())) {\r\n port = Integer.parseInt(environmentSubstitute(meta.getPort()));\r\n }\r\n\r\n if (body == null) {\r\n throw new AMQPException(\"Unable to retrieve field : \" + meta.getBodyField());\r\n }\r\n\r\n if ((username == null || password == null || host == null || port == null) && (uri == null)) {\r\n throw new AMQPException(\"Unable to retrieve connection information\");\r\n }\r\n\r\n // get field index\r\n data.bodyFieldIndex = data.outputRowMeta.indexOfValue(body);\r\n data.target = environmentSubstitute(meta.getTarget());\r\n data.bindings = meta.getBindings();\r\n data.limit = meta.getLimit();\r\n data.prefetchCount = meta.getPrefetchCount();\r\n data.waitTimeout = meta.getWaitTimeout();\r\n\r\n data.uri = uri;\r\n data.host = host;\r\n data.port = port;\r\n data.vhost = vhost;\r\n data.username = username;\r\n data.password = password;\r\n\r\n data.useSsl = meta.isUseSsl();\r\n data.isTransactional = meta.isTransactional();\r\n data.isWaitingConsumer = meta.isWaitingConsumer();\r\n data.isRequeue = meta.isRequeue();\r\n data.isConsumer = meta.isConsumer();\r\n data.isProducer = meta.isProducer();\r\n\r\n //Confirmation sniffers\r\n data.ackStepName = environmentSubstitute(meta.getAckStepName());\r\n data.ackStepDeliveryTagField = environmentSubstitute(meta.getAckStepDeliveryTagField());\r\n data.rejectStepName = environmentSubstitute(meta.getRejectStepName());\r\n data.rejectStepDeliveryTagField = environmentSubstitute(meta.getRejectStepDeliveryTagField());\r\n\r\n //init Producer\r\n data.exchtype = meta.getExchtype();\r\n data.isAutodel = meta.isAutodel();\r\n data.isDurable = meta.isDurable();\r\n data.isDeclare = meta.isDeclare();\r\n data.isExclusive = meta.isExclusive();\r\n\r\n if ( ! Const.isEmpty(routing)) {\r\n data.routingIndex = data.outputRowMeta.indexOfValue(routing);\r\n\r\n if (data.routingIndex < 0) {\r\n throw new AMQPException(\"Unable to retrieve routing key field : \" + meta.getRouting());\r\n }\r\n }\r\n\r\n if ( ! Const.isEmpty(deliveryTagField)) {\r\n data.deliveryTagIndex = data.outputRowMeta.indexOfValue(deliveryTagField);\r\n\r\n if (data.deliveryTagIndex < 0) {\r\n throw new AMQPException(\"Unable to retrieve DeliveryTag field : \" + deliveryTagField);\r\n }\r\n }\r\n\r\n if (data.bodyFieldIndex < 0) {\r\n throw new AMQPException(\"Unable to retrieve body field : \" + body);\r\n }\r\n\r\n if (data.target == null) {\r\n throw new AMQPException(\"Unable to retrieve queue/exchange name\");\r\n }\r\n\r\n logMinimal(getString(\"AmqpPlugin.Body.Label\") + \" : \" + body);\r\n logMinimal(getString(\"AmqpPlugin.Routing.Label\") + \" : \" + routing);\r\n logMinimal(getString(\"AmqpPlugin.Target.Label\") + \" : \" + data.target);\r\n logMinimal(getString(\"AmqpPlugin.Limit.Label\") + \" : \" + data.limit);\r\n logMinimal(getString(\"AmqpPlugin.UseSsl.Label\") + \" : \" + data.useSsl);\r\n logMinimal(getString(\"AmqpPlugin.URI.Label\") + \" : \" + uri);\r\n logMinimal(getString(\"AmqpPlugin.Username.Label\") + \" : \" + username);\r\n logDebug(getString(\"AmqpPlugin.Password.Label\") + \" : \" + password);\r\n logMinimal(getString(\"AmqpPlugin.Host.Label\") + \" : \" + host);\r\n logMinimal(getString(\"AmqpPlugin.Port.Label\") + \" : \" + port);\r\n logMinimal(getString(\"AmqpPlugin.Vhost.Label\") + \" : \" + vhost);\r\n\r\n if ( data.isConsumer && data.isTransactional && data.prefetchCount > 0 ) {\r\n throw new AMQPException(getString(\"AmqpPlugin.Error.PrefetchCountAndTransactionalNotSupported\"));\r\n }\r\n\r\n if ( data.isConsumer && data.isRequeue) {\r\n logMinimal(getString(\"AmqpPlugin.Info.RequeueDevelopmentUsage\"));\r\n }\r\n\r\n if (data.isConsumer && ( ! Const.isEmpty(data.ackStepName) || ! Const.isEmpty(data.rejectStepName))) {\r\n // we start active confirmation , need not to Ack messages in batches\r\n data.activeConfirmation = true;\r\n }\r\n\r\n processor = factory.processorFor(this, data, meta);\r\n\r\n // hook to transListener, to make final flush to transactional case, or in case ack/nack steps should finish.\r\n if (data.isTransactional || data.activeConfirmation ) {\r\n getTrans().addTransListener(transListener);\r\n }\r\n }\r\n\r\n private void onSuccess()\r\n {\r\n logMinimal(\"On success invoked\");\r\n\r\n if (processor == null) {\r\n return;\r\n }\r\n\r\n try {\r\n processor.onSuccess();\r\n } catch (KettleStepException ex) {\r\n logError(ex.getMessage());\r\n } catch (IOException ex) {\r\n logError(ex.getMessage());\r\n }\r\n\r\n this.shutdown();\r\n }\r\n\r\n private void onFailure()\r\n {\r\n logMinimal(\"On failure invoked\");\r\n\r\n if (processor == null) {\r\n return;\r\n }\r\n\r\n try {\r\n processor.onFailure();\r\n } catch (KettleStepException ex) {\r\n logError(ex.getMessage());\r\n } catch (IOException ex) {\r\n logError(ex.getMessage());\r\n }\r\n\r\n this.shutdown();\r\n }\r\n\r\n private void shutdown()\r\n {\r\n try {\r\n processor.shutdown();\r\n } catch (KettleStepException ex) {\r\n logError(ex.getMessage());\r\n } catch (IOException ex) {\r\n logError(ex.getMessage());\r\n }\r\n }\r\n\r\n @Override\r\n public void dispose(StepMetaInterface smi, StepDataInterface sdi)\r\n {\r\n meta = (AMQPPluginMeta) smi;\r\n data = (AMQPPluginData) sdi;\r\n\r\n logDebug(\"Dispose invoked\");\r\n\r\n if ( ! data.isTransactional && ! data.activeConfirmation ) {\r\n onSuccess();\r\n }\r\n\r\n super.dispose(smi, sdi);\r\n }\r\n\r\n @Override\r\n public void stopRunning( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {\r\n try {\r\n processor.cancel();;\r\n } catch (KettleStepException ex) {\r\n logError(ex.getMessage());\r\n } catch (IOException ex) {\r\n logError(ex.getMessage());\r\n }\r\n \r\n super.stopRunning(smi, sdi);\r\n }\r\n\r\n}\r", "public class AMQPPluginData extends BaseStepData implements StepDataInterface\r\n{\r\n public static final String MODE_PRODUCER = \"producer\";\r\n public static final String MODE_CONSUMER = \"consumer\";\r\n\r\n public static final String TARGET_TYPE_EXCHANGE = \"exchange\";\r\n public static final String TARGET_TYPE_QUEUE = \"queue\";\r\n\r\n public static final String EXCHTYPE_FANOUT = \"fanout\";\r\n public static final String EXCHTYPE_DIRECT = \"direct\";\r\n public static final String EXCHTYPE_HEADERS = \"headers\";\r\n public static final String EXCHTYPE_TOPIC = \"topic\";\r\n\r\n public List<AMQPPluginMeta.Binding> bindings;\r\n public RowMetaInterface outputRowMeta;\r\n public Integer bodyFieldIndex = null;\r\n public Integer routingIndex = null;\r\n\r\n public boolean isTransactional = false;\r\n public boolean isProducer = false;\r\n public boolean isConsumer = false;\r\n public boolean isTxOpen = false;\r\n public boolean isDeclare = false;\r\n public boolean isDurable = true;\r\n public boolean isAutodel = false;\r\n public boolean isExclusive = false;\r\n public boolean isWaitingConsumer = false;\r\n public boolean isRequeue = false;\r\n public String exchtype = \"\";\r\n public String body = null;\r\n public String routing;\r\n public String target;\r\n public long amqpTag;\r\n public Long limit;\r\n public Long waitTimeout;\r\n public int prefetchCount = 0;\r\n public long count = 0;\r\n public long ack = 0;\r\n public long rejected = 0;\r\n\r\n public String uri;\r\n public String host;\r\n public int port;\r\n public String vhost;\r\n public String username;\r\n public String password;\r\n public boolean useSsl = false;\r\n\r\n // Delayed confirmation realted\r\n public Integer deliveryTagIndex = null;\r\n\r\n public boolean activeConfirmation = false;\r\n public String ackStepName = null;\r\n public String ackStepDeliveryTagField = null;\r\n\r\n public String rejectStepName = null;\r\n public String rejectStepDeliveryTagField = null;\r\n\r\n public List<Long> ackMsgInTransaction = null;\r\n public List<Long> rejectedMsgInTransaction = null;\r\n\r\n public AMQPPluginData()\r\n {\r\n super();\r\n }\r\n}\r", "public class AMQPPluginMeta extends BaseStepMeta implements StepMetaInterface\r\n{\r\n private static final String FIELD_TRANSACTIONAL = \"transactional\";\r\n private static final String FIELD_BODY_FIELD = \"body_field\";\r\n private static final String FIELD_ROUTING = \"routing\";\r\n private static final String FIELD_DELIVERYTAG_FIELD = \"deliverytag_field\";\r\n private static final String FIELD_LIMIT = \"limit\";\r\n private static final String FIELD_PREFETCHCOUNT = \"prefetchCount\";\r\n private static final String FIELD_TARGET = \"target\";\r\n private static final String FIELD_MODE = \"mode\";\r\n private static final String FIELD_URI = \"uri\";\r\n\r\n private static final String FIELD_USERNAME = \"username\";\r\n private static final String FIELD_PASSWORD = \"password\";\r\n private static final String FIELD_HOST = \"host\";\r\n private static final String FIELD_PORT = \"port\";\r\n private static final String FIELD_VHOST = \"vhost\";\r\n private static final String FIELD_USESSL = \"usessl\";\r\n private static final String FIELD_BINDING = \"binding\";\r\n private static final String FIELD_BINDING_LINE = \"line\";\r\n private static final String FIELD_BINDING_LINE_TARGET = \"target_value\";\r\n private static final String FIELD_BINDING_LINE_TARGET_TYPE = \"target_type_value\";\r\n private static final String FIELD_BINDING_LINE_ROUTING = \"routing_value\";\r\n private static final String FIELD_DECLARE = \"declare\";\r\n private static final String FIELD_DURABLE = \"durable\";\r\n private static final String FIELD_AUTODEL = \"autodel\";\r\n private static final String FIELD_EXCHTYPE = \"exchtype\";\r\n private static final String FIELD_EXCLUSIVE = \"exclusive\";\r\n private static final String FIELD_WAITINGCONSUMER = \"waiting_consumer\";\r\n private static final String FIELD_REQUEUE = \"requeue\";\r\n private static final String FIELD_WAITTIMEOUT = \"waiting_timout\";\r\n\r\n\r\n private static final String FIELD_ACKSTEPNAME = \"ack_stepname\";\r\n private static final String FIELD_ACKDELIVERYTAG_FIELD = \"ack_deliverytag_field\";\r\n private static final String FIELD_REJECTSTEPNAME = \"reject_stepname\";\r\n private static final String FIELD_REJECTSTEPDELIVERYTAG_FIELD = \"reject_deliverytag_field\";\r\n\r\n private static final String DEFAULT_BODY_FIELD = \"message\";\r\n private static final String DEFAULT_DELIVERYTAG_FIELD = \"amqpdeliverytag\";\r\n private static final String DEFAULT_EXCHTYPE = AMQPPluginData.EXCHTYPE_DIRECT;\r\n\r\n private String uri;\r\n private String routing;\r\n private String target;\r\n private Long limit;\r\n private Long waitTimeout;\r\n private int prefetchCount;\r\n private String username;\r\n private String password;\r\n private String host;\r\n private String port;\r\n private String vhost;\r\n private String exchtype;\r\n private boolean usessl = false;\r\n private boolean declare = false;\r\n private boolean durable = true;\r\n private boolean autodel = false;\r\n private boolean requeue = false;\r\n private boolean exclusive = false;\r\n private boolean waitingConsumer = false; \r\n private boolean transactional = false;\r\n private String bodyField = DEFAULT_BODY_FIELD;\r\n private String deliveryTagField = DEFAULT_DELIVERYTAG_FIELD;\r\n public String ackStepName = null;\r\n public String ackStepDeliveryTagField = null;\r\n public String rejectStepName = null;\r\n public String rejectStepDeliveryTagField = null;\r\n private String mode = AMQPPluginData.MODE_CONSUMER;\r\n\r\n private final List<AMQPPluginMeta.Binding> bindings = new ArrayList<AMQPPluginMeta.Binding>();\r\n\r\n public static class Binding\r\n {\r\n private final String target;\r\n private final String routing;\r\n private final String target_type;\r\n\r\n Binding(final String target, final String target_type, final String routing)\r\n {\r\n this.target = target;\r\n this.routing = routing;\r\n this.target_type = target_type;\r\n }\r\n\r\n public String getTarget()\r\n {\r\n return target;\r\n }\r\n\r\n public String getRouting()\r\n {\r\n return routing;\r\n }\r\n public String getTargetType()\r\n {\r\n return target_type;\r\n }\r\n }\r\n\r\n public AMQPPluginMeta()\r\n {\r\n super();\r\n }\r\n\r\n public StepDialogInterface getDialog(Shell shell, StepMetaInterface meta, TransMeta transMeta, String name)\r\n {\r\n return new AMQPPluginDialog(shell, meta, transMeta, name);\r\n }\r\n\r\n @Override\r\n public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans disp)\r\n {\r\n return new AMQPPlugin(stepMeta, stepDataInterface, cnr, transMeta, disp);\r\n }\r\n\r\n @Override\r\n public StepDataInterface getStepData()\r\n {\r\n return new AMQPPluginData();\r\n }\r\n\r\n @Override\r\n public void getFields(RowMetaInterface inputRowMeta, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space, Repository repository, IMetaStore ims) throws KettleStepException\r\n {\r\n if (AMQPPluginData.MODE_CONSUMER.equals(mode)) {\r\n // a value meta object contains the meta data for a field\r\n final ValueMetaInterface b = new ValueMeta(space.environmentSubstitute(getBodyField()), ValueMeta.TYPE_STRING);\r\n // the name of the step that adds this field\r\n b.setOrigin(name);\r\n // modify the row structure and add the field this step generates\r\n inputRowMeta.addValueMeta(b);\r\n\r\n if ( ! Const.isEmpty(getRouting())) {\r\n final ValueMetaInterface r = new ValueMeta(space.environmentSubstitute(getRouting()), ValueMeta.TYPE_STRING);\r\n r.setOrigin(name);\r\n inputRowMeta.addValueMeta(r);\r\n }\r\n\r\n if ( ! Const.isEmpty(deliveryTagField)) {\r\n final ValueMetaInterface r = new ValueMeta(space.environmentSubstitute(getDeliveryTagField()), ValueMeta.TYPE_INTEGER);\r\n r.setOrigin(name);\r\n inputRowMeta.addValueMeta(r);\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void check(List<CheckResultInterface> remarks, TransMeta transmeta, StepMeta stepMeta, RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace vs, Repository rpstr, IMetaStore ims)\r\n {\r\n final CheckResult prevSizeCheck = (prev == null || prev.isEmpty())\r\n ? new CheckResult(CheckResult.TYPE_RESULT_WARNING, \"Not receiving any fields from previous steps!\", stepMeta)\r\n : new CheckResult(CheckResult.TYPE_RESULT_OK, \"Step is connected to previous one, receiving \" + prev.size() + \" fields\", stepMeta);\r\n\r\n /// See if we have input streams leading to this step!\r\n final CheckResult inputLengthCheck = (input.length > 0)\r\n ? new CheckResult(CheckResult.TYPE_RESULT_OK, \"Step is receiving info from other steps.\", stepMeta)\r\n : new CheckResult(CheckResult.TYPE_RESULT_ERROR, \"No input received from other steps!\", stepMeta);\r\n\r\n remarks.add(prevSizeCheck);\r\n remarks.add(inputLengthCheck);\r\n }\r\n\r\n @Override\r\n public String getXML()\r\n {\r\n final StringBuilder bufer = new StringBuilder();\r\n\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_TRANSACTIONAL, isTransactional()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_BODY_FIELD, getBodyField()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_DELIVERYTAG_FIELD, getDeliveryTagField()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_LIMIT, getLimitString()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_PREFETCHCOUNT, getPrefetchCountString()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_WAITTIMEOUT, getWaitTimeoutString()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_ROUTING, getRouting()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_TARGET, getTarget()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_MODE, getMode()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_URI, getUri()));\r\n\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_USERNAME, getUsername()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_PASSWORD, getPassword()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_HOST, getHost()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_PORT, getPort()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_VHOST, getVhost()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_USESSL, isUseSsl()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_DECLARE, isDeclare()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_DURABLE, isDurable()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_AUTODEL, isAutodel()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_EXCLUSIVE, isExclusive()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_WAITINGCONSUMER, isWaitingConsumer()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_REQUEUE, isRequeue()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_EXCHTYPE, getExchtype()));\r\n\r\n bufer.append(\" <\" + FIELD_BINDING + \">\").append(Const.CR);\r\n for (Binding item : getBindings()) {\r\n bufer.append(\" <\" + FIELD_BINDING_LINE + \">\").append(Const.CR);\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_BINDING_LINE_TARGET, item.getTarget()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_BINDING_LINE_TARGET_TYPE, item.getTargetType()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_BINDING_LINE_ROUTING, item.getRouting()));\r\n bufer.append(\" </\" + FIELD_BINDING_LINE + \">\").append(Const.CR);\r\n }\r\n bufer.append(\" </\" + FIELD_BINDING + \">\").append(Const.CR);\r\n\r\n\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_ACKSTEPNAME, getAckStepName()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_ACKDELIVERYTAG_FIELD, getAckStepDeliveryTagField()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_REJECTSTEPNAME, getRejectStepName()));\r\n bufer.append(\" \").append(XMLHandler.addTagValue(FIELD_REJECTSTEPDELIVERYTAG_FIELD, getRejectStepDeliveryTagField()));\r\n\r\n return bufer.toString();\r\n }\r\n\r\n @Override\r\n public void loadXML(Node stepnode, List<DatabaseMeta> databases, IMetaStore ims) throws KettleXMLException\r\n {\r\n try {\r\n setTransactional(XMLHandler.getTagValue(stepnode, FIELD_TRANSACTIONAL));\r\n setBodyField(XMLHandler.getTagValue(stepnode, FIELD_BODY_FIELD));\r\n setDeliveryTagField(XMLHandler.getTagValue(stepnode, FIELD_DELIVERYTAG_FIELD));\r\n setRouting(XMLHandler.getTagValue(stepnode, FIELD_ROUTING));\r\n setTarget(XMLHandler.getTagValue(stepnode, FIELD_TARGET));\r\n setLimit(XMLHandler.getTagValue(stepnode, FIELD_LIMIT));\r\n setPrefetchCount(XMLHandler.getTagValue(stepnode, FIELD_PREFETCHCOUNT));\r\n setWaitTimeout(XMLHandler.getTagValue(stepnode, FIELD_WAITTIMEOUT));\r\n setMode(XMLHandler.getTagValue(stepnode, FIELD_MODE));\r\n setUri(XMLHandler.getTagValue(stepnode, FIELD_URI));\r\n\r\n setUsername(XMLHandler.getTagValue(stepnode, FIELD_USERNAME));\r\n setPassword(XMLHandler.getTagValue(stepnode, FIELD_PASSWORD));\r\n setHost(XMLHandler.getTagValue(stepnode, FIELD_HOST));\r\n setPort(XMLHandler.getTagValue(stepnode, FIELD_PORT));\r\n setVhost(XMLHandler.getTagValue(stepnode, FIELD_VHOST));\r\n setUseSsl(XMLHandler.getTagValue(stepnode, FIELD_USESSL));\r\n setDeclare(XMLHandler.getTagValue(stepnode, FIELD_DECLARE));\r\n setDurable(XMLHandler.getTagValue(stepnode, FIELD_DURABLE));\r\n setAutodel(XMLHandler.getTagValue(stepnode, FIELD_AUTODEL));\r\n setExclusive(XMLHandler.getTagValue(stepnode, FIELD_EXCLUSIVE));\r\n setWaitingConsumer(XMLHandler.getTagValue(stepnode, FIELD_WAITINGCONSUMER));\r\n setRequeue(XMLHandler.getTagValue(stepnode, FIELD_REQUEUE));\r\n setExchtype(XMLHandler.getTagValue(stepnode, FIELD_EXCHTYPE));\r\n\r\n Node binding = XMLHandler.getSubNode(stepnode, FIELD_BINDING);\r\n int count = XMLHandler.countNodes(binding, FIELD_BINDING_LINE);\r\n\r\n clearBindings();\r\n\r\n for (int i = 0; i < count; i++) {\r\n Node lnode = XMLHandler.getSubNodeByNr(binding, FIELD_BINDING_LINE, i);\r\n String targetItem = XMLHandler.getTagValue(lnode, FIELD_BINDING_LINE_TARGET);\r\n String typeItem = XMLHandler.getTagValue(lnode, FIELD_BINDING_LINE_TARGET_TYPE);\r\n String routingItem = XMLHandler.getTagValue(lnode, FIELD_BINDING_LINE_ROUTING);\r\n addBinding(targetItem, typeItem, routingItem);\r\n }\r\n\r\n\r\n setAckStepName(XMLHandler.getTagValue(stepnode, FIELD_ACKSTEPNAME));\r\n setAckStepDeliveryTagField(XMLHandler.getTagValue(stepnode, FIELD_ACKDELIVERYTAG_FIELD));\r\n setRejectStepName(XMLHandler.getTagValue(stepnode, FIELD_REJECTSTEPNAME));\r\n setRejectStepDeliveryTagField(XMLHandler.getTagValue(stepnode, FIELD_REJECTSTEPDELIVERYTAG_FIELD));\r\n\r\n\r\n } catch (Exception e) {\r\n throw new KettleXMLException(\"Unable to read step info from XML node\", e);\r\n }\r\n }\r\n\r\n @Override\r\n public void readRep(Repository rep, IMetaStore ims, ObjectId idStep, List<DatabaseMeta> databases) throws KettleException\r\n {\r\n try {\r\n setTransactional(rep.getStepAttributeString(idStep, FIELD_TRANSACTIONAL));\r\n setBodyField(rep.getStepAttributeString(idStep, FIELD_BODY_FIELD));\r\n setDeliveryTagField(rep.getStepAttributeString(idStep, FIELD_DELIVERYTAG_FIELD));\r\n setRouting(rep.getStepAttributeString(idStep, FIELD_ROUTING));\r\n setTarget(rep.getStepAttributeString(idStep, FIELD_TARGET));\r\n setLimit(rep.getStepAttributeString(idStep, FIELD_LIMIT));\r\n setPrefetchCount(rep.getStepAttributeString(idStep, FIELD_PREFETCHCOUNT));\r\n setWaitTimeout(rep.getStepAttributeString(idStep, FIELD_WAITTIMEOUT));\r\n setMode(rep.getStepAttributeString(idStep, FIELD_MODE));\r\n setUri(rep.getStepAttributeString(idStep, FIELD_URI));\r\n\r\n setUsername(rep.getStepAttributeString(idStep, FIELD_USERNAME));\r\n setPassword(rep.getStepAttributeString(idStep, FIELD_PASSWORD));\r\n setHost(rep.getStepAttributeString(idStep, FIELD_HOST));\r\n setPort(rep.getStepAttributeString(idStep, FIELD_PORT));\r\n setVhost(rep.getStepAttributeString(idStep, FIELD_VHOST));\r\n setUseSsl(rep.getStepAttributeString(idStep, FIELD_USESSL));\r\n setDurable(rep.getStepAttributeString(idStep, FIELD_DURABLE));\r\n setDeclare(rep.getStepAttributeString(idStep, FIELD_DECLARE));\r\n setAutodel(rep.getStepAttributeString(idStep, FIELD_AUTODEL));\r\n setExclusive(rep.getStepAttributeString(idStep, FIELD_EXCLUSIVE));\r\n setWaitingConsumer(rep.getStepAttributeString(idStep, FIELD_WAITINGCONSUMER));\r\n setRequeue(rep.getStepAttributeString(idStep, FIELD_REQUEUE));\r\n setExchtype(rep.getStepAttributeString(idStep, FIELD_EXCHTYPE));\r\n\r\n int nrbindingLines = rep.countNrStepAttributes(idStep, FIELD_BINDING_LINE_TARGET);\r\n\r\n clearBindings();\r\n\r\n for (int i = 0; i < nrbindingLines; i++) {\r\n String targetItem = rep.getStepAttributeString(idStep, i, FIELD_BINDING_LINE_TARGET);\r\n String typeItem = rep.getStepAttributeString(idStep, i, FIELD_BINDING_LINE_TARGET_TYPE);\r\n String routingItem = rep.getStepAttributeString(idStep, i, FIELD_BINDING_LINE_ROUTING);\r\n addBinding(targetItem, typeItem, routingItem);\r\n }\r\n\r\n setAckStepName(rep.getStepAttributeString(idStep, FIELD_ACKSTEPNAME));\r\n setAckStepDeliveryTagField(rep.getStepAttributeString(idStep, FIELD_ACKDELIVERYTAG_FIELD));\r\n setRejectStepName(rep.getStepAttributeString(idStep, FIELD_REJECTSTEPNAME));\r\n setRejectStepDeliveryTagField(rep.getStepAttributeString(idStep, FIELD_REJECTSTEPDELIVERYTAG_FIELD));\r\n\r\n\r\n } catch (KettleDatabaseException dbe) {\r\n throw new KettleException(\"error reading step with id_step=\" + idStep + \" from the repository\", dbe);\r\n } catch (KettleException e) {\r\n throw new KettleException(\"Unexpected error reading step with id_step=\" + idStep + \" from the repository\", e);\r\n }\r\n }\r\n\r\n @Override\r\n public void saveRep(Repository rep, IMetaStore ims, ObjectId idTransformation, ObjectId idStep) throws KettleException\r\n {\r\n try {\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_TRANSACTIONAL, isTransactional());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_BODY_FIELD, getBodyField());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_DELIVERYTAG_FIELD, getDeliveryTagField());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_LIMIT, getLimitString());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_PREFETCHCOUNT, getPrefetchCountString());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_WAITTIMEOUT, getWaitTimeoutString());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_ROUTING, getRouting());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_TARGET, getTarget());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_MODE, getMode());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_URI, getUri());\r\n\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_USERNAME, getUsername());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_PASSWORD, getPassword());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_HOST, getHost());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_PORT, getPort());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_VHOST, getVhost());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_USESSL, isUseSsl());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_DECLARE, isDeclare());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_DURABLE, isDurable());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_AUTODEL, isAutodel());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_EXCLUSIVE, isExclusive());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_WAITINGCONSUMER, isWaitingConsumer());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_REQUEUE, isRequeue());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_EXCHTYPE, getExchtype());\r\n\r\n int i = 0;\r\n\r\n for (Binding item : getBindings()) {\r\n rep.saveStepAttribute(idTransformation, idStep, i, FIELD_BINDING_LINE_TARGET, item.getTarget());\r\n rep.saveStepAttribute(idTransformation, idStep, i, FIELD_BINDING_LINE_TARGET_TYPE, item.getTargetType());\r\n rep.saveStepAttribute(idTransformation, idStep, i, FIELD_BINDING_LINE_ROUTING, item.getRouting());\r\n i++;\r\n }\r\n\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_ACKSTEPNAME, getAckStepName());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_ACKDELIVERYTAG_FIELD, getAckStepDeliveryTagField());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_REJECTSTEPNAME, getRejectStepName());\r\n rep.saveStepAttribute(idTransformation, idStep, FIELD_REJECTSTEPDELIVERYTAG_FIELD, getRejectStepDeliveryTagField());\r\n\r\n\r\n } catch (KettleDatabaseException dbe) {\r\n throw new KettleException(\"Unable to save step information to the repository, id_step=\" + idStep, dbe);\r\n }\r\n }\r\n\r\n @Override\r\n public void setDefault()\r\n {\r\n this.uri = \"amqp://guest:guest@localhost:5672\";\r\n this.mode = AMQPPluginData.MODE_CONSUMER;\r\n this.bodyField = DEFAULT_BODY_FIELD;\r\n this.deliveryTagField = DEFAULT_DELIVERYTAG_FIELD;\r\n this.exchtype = DEFAULT_EXCHTYPE;\r\n this.username = \"\";\r\n this.password = \"\";\r\n this.host = \"\";\r\n this.port = \"\";\r\n this.vhost = \"\";\r\n this.usessl = false;\r\n this.declare = false;\r\n this.durable = false;\r\n this.autodel = false;\r\n this.requeue = false;\r\n this.exclusive = false;\r\n this.transactional = false;\r\n this.waitingConsumer = false;\r\n this.prefetchCount = 0;\r\n this.waitTimeout = 60000L;\r\n this.ackStepName = \"\";\r\n this.ackStepDeliveryTagField = \"\";\r\n this.rejectStepName = \"\";\r\n this.rejectStepDeliveryTagField = \"\";\r\n\r\n bindings.clear();\r\n }\r\n\r\n @Override\r\n public boolean supportsErrorHandling()\r\n {\r\n return false;\r\n }\r\n\r\n public String getUri()\r\n {\r\n return uri;\r\n }\r\n\r\n public void setUri(String uri)\r\n {\r\n this.uri = uri;\r\n }\r\n\r\n public String getUsername()\r\n {\r\n return username;\r\n }\r\n\r\n public void setUsername(String username)\r\n {\r\n this.username = username;\r\n }\r\n\r\n public String getPassword()\r\n {\r\n return password;\r\n }\r\n\r\n public void setPassword(String password)\r\n {\r\n this.password = password;\r\n }\r\n\r\n public String getHost()\r\n {\r\n return host;\r\n }\r\n\r\n public void setHost(String host)\r\n {\r\n this.host = host;\r\n }\r\n\r\n public String getPort()\r\n {\r\n return port;\r\n }\r\n\r\n public void setPort(String port)\r\n {\r\n this.port = port;\r\n }\r\n\r\n public String getVhost()\r\n {\r\n return vhost;\r\n }\r\n\r\n public void setVhost(String vhost)\r\n {\r\n this.vhost = vhost;\r\n }\r\n\r\n public String getMode()\r\n {\r\n return mode;\r\n }\r\n\r\n public void setMode(String filter)\r\n {\r\n this.mode = filter;\r\n }\r\n\r\n\r\n public boolean isConsumer() \r\n { \r\n return AMQPPluginData.MODE_CONSUMER.equals(getMode()); \r\n }\r\n\r\n public boolean isProducer() \r\n {\r\n return AMQPPluginData.MODE_PRODUCER.equals(getMode());\r\n }\r\n\r\n\r\n public String getExchtype()\r\n {\r\n return exchtype;\r\n }\r\n\r\n public void setExchtype(String exchtype)\r\n {\r\n this.exchtype = exchtype;\r\n }\r\n\r\n public boolean isTransactional()\r\n {\r\n return transactional;\r\n }\r\n\r\n public void setTransactional(String transactional)\r\n {\r\n this.transactional = Boolean.TRUE.toString().equals(transactional) || \"Y\".equals(transactional);\r\n }\r\n\r\n public void setTransactional(boolean transactional)\r\n {\r\n this.transactional = transactional;\r\n }\r\n\r\n public boolean isUseSsl()\r\n {\r\n return usessl;\r\n }\r\n\r\n public void setUseSsl(String usessl)\r\n {\r\n this.usessl = Boolean.TRUE.toString().equals(usessl) || \"Y\".equals(usessl);\r\n }\r\n\r\n public void setUseSsl(boolean usessl)\r\n {\r\n this.usessl = usessl;\r\n }\r\n\r\n public boolean isDeclare()\r\n {\r\n return declare;\r\n }\r\n\r\n public void setDeclare(String declare)\r\n {\r\n this.declare = Boolean.TRUE.toString().equals(declare) || \"Y\".equals(declare);\r\n }\r\n\r\n public void setDeclare(boolean declare)\r\n {\r\n this.declare = declare;\r\n }\r\n\r\n public boolean isDurable()\r\n {\r\n return durable;\r\n }\r\n\r\n public void setDurable(String durable)\r\n {\r\n this.durable = Boolean.TRUE.toString().equals(durable) || \"Y\".equals(durable);\r\n }\r\n\r\n public void setDurable(boolean durable)\r\n {\r\n this.durable = durable;\r\n }\r\n\r\n public boolean isAutodel()\r\n {\r\n return autodel;\r\n }\r\n\r\n public void setAutodel(String autodel)\r\n {\r\n this.autodel = Boolean.TRUE.toString().equals(autodel) || \"Y\".equals(autodel);\r\n }\r\n\r\n public void setAutodel(boolean autodel)\r\n {\r\n this.autodel = autodel;\r\n }\r\n\r\n public boolean isExclusive()\r\n {\r\n return exclusive;\r\n }\r\n\r\n public void setExclusive(String exclusive)\r\n {\r\n this.exclusive = Boolean.TRUE.toString().equals(exclusive) || \"Y\".equals(exclusive);\r\n }\r\n\r\n public void setExclusive(boolean exclusive)\r\n {\r\n this.exclusive = exclusive;\r\n }\r\n\r\n public boolean isWaitingConsumer()\r\n {\r\n return waitingConsumer;\r\n }\r\n\r\n\r\n public void setWaitingConsumer(String val)\r\n {\r\n this.waitingConsumer = Boolean.TRUE.toString().equals(val) || \"Y\".equals(val);\r\n }\r\n\r\n public void setWaitingConsumer(boolean val)\r\n {\r\n this.waitingConsumer = val;\r\n }\r\n\r\n public boolean isRequeue()\r\n {\r\n return requeue;\r\n }\r\n\r\n\r\n public void setRequeue(String val)\r\n {\r\n this.requeue = Boolean.TRUE.toString().equals(val) || \"Y\".equals(val);\r\n }\r\n\r\n public void setRequeue(boolean val)\r\n {\r\n this.requeue = val;\r\n }\r\n\r\n public String getBodyField()\r\n {\r\n return bodyField;\r\n }\r\n\r\n public void setBodyField(String uniqueRowName)\r\n {\r\n this.bodyField = uniqueRowName;\r\n }\r\n\r\n public String getTarget()\r\n {\r\n if (Const.isEmpty(target) && AMQPPluginData.MODE_CONSUMER.equals(mode)) {\r\n target = \"queue_name\";\r\n }\r\n\r\n if (Const.isEmpty(target) && AMQPPluginData.MODE_PRODUCER.equals(mode)) {\r\n target = \"exchange_name\";\r\n }\r\n\r\n return target;\r\n }\r\n\r\n public void setTarget(String target)\r\n {\r\n this.target = target;\r\n }\r\n\r\n public String getRouting()\r\n {\r\n return routing;\r\n }\r\n\r\n public void setRouting(String routing)\r\n {\r\n this.routing = routing;\r\n }\r\n\r\n\r\n public String getDeliveryTagField()\r\n {\r\n return deliveryTagField;\r\n }\r\n\r\n public void setDeliveryTagField(String val)\r\n {\r\n this.deliveryTagField = val;\r\n }\r\n\r\n public String getAckStepName()\r\n {\r\n return ackStepName;\r\n }\r\n\r\n public void setAckStepName(String val)\r\n {\r\n this.ackStepName = val;\r\n }\r\n\r\n\r\n public String getAckStepDeliveryTagField()\r\n {\r\n return ackStepDeliveryTagField;\r\n }\r\n\r\n public void setAckStepDeliveryTagField(String val)\r\n {\r\n this.ackStepDeliveryTagField = val;\r\n }\r\n\r\n public String getRejectStepName()\r\n {\r\n return rejectStepName;\r\n }\r\n\r\n public void setRejectStepName(String val)\r\n {\r\n this.rejectStepName = val;\r\n }\r\n\r\n\r\n public String getRejectStepDeliveryTagField()\r\n {\r\n return rejectStepDeliveryTagField;\r\n }\r\n\r\n public void setRejectStepDeliveryTagField(String val)\r\n {\r\n this.rejectStepDeliveryTagField = val;\r\n }\r\n\r\n\r\n public Long getLimit()\r\n {\r\n if (limit == null) {\r\n limit = 10000L;\r\n }\r\n\r\n return limit;\r\n }\r\n\r\n public String getLimitString()\r\n {\r\n return String.valueOf(getLimit());\r\n }\r\n\r\n public void setLimit(Long limit)\r\n {\r\n this.limit = limit;\r\n }\r\n\r\n public void setLimit(String limit)\r\n {\r\n this.limit = null;\r\n\r\n if (Const.isEmpty(limit)) {\r\n return;\r\n }\r\n\r\n this.limit = Long.parseLong(limit);\r\n }\r\n\r\n public Long getWaitTimeout()\r\n {\r\n if (waitTimeout == null) {\r\n waitTimeout = 60000L;\r\n }\r\n\r\n return waitTimeout;\r\n }\r\n\r\n public String getWaitTimeoutString()\r\n {\r\n return String.valueOf(getWaitTimeout());\r\n }\r\n\r\n public void setWaitTimeout(Long waitTimeout)\r\n {\r\n this.waitTimeout = waitTimeout;\r\n }\r\n\r\n public void setWaitTimeout(String waitTimeout)\r\n {\r\n this.waitTimeout = null;\r\n\r\n if (Const.isEmpty(waitTimeout)) {\r\n return;\r\n }\r\n\r\n this.waitTimeout = Long.parseLong(waitTimeout);\r\n }\r\n\r\n public int getPrefetchCount()\r\n {\r\n return prefetchCount;\r\n }\r\n\r\n public String getPrefetchCountString()\r\n {\r\n return String.valueOf(getPrefetchCount());\r\n }\r\n\r\n public void setPrefetchCount(int prefetchCount)\r\n {\r\n this.prefetchCount = prefetchCount;\r\n }\r\n\r\n public void setPrefetchCount(String prefetchCount)\r\n {\r\n this.prefetchCount = 0;\r\n\r\n if (Const.isEmpty(prefetchCount)) {\r\n return;\r\n }\r\n\r\n this.prefetchCount = Integer.parseInt(prefetchCount);\r\n }\r\n\r\n public void addBinding(String target, String target_type, String routing)\r\n {\r\n this.bindings.add(new AMQPPluginMeta.Binding(target, target_type, routing));\r\n }\r\n\r\n public List<AMQPPluginMeta.Binding> getBindings()\r\n {\r\n return this.bindings;\r\n }\r\n\r\n public void clearBindings()\r\n {\r\n this.bindings.clear();\r\n }\r\n\r\n\r\n\r\n @Override\r\n public AMQPPluginMetaInjection getStepMetaInjectionInterface() {\r\n return new AMQPPluginMetaInjection( this );\r\n }\r\n\r\n public List<StepInjectionMetaEntry> extractStepMetadataEntries() throws KettleException {\r\n return getStepMetaInjectionInterface().extractStepMetadataEntries();\r\n }\r\n\r\n}\r", "public class ActiveConvirmationInitializer implements Initializer\n{\n public static final ActiveConvirmationInitializer INSTANCE = new ActiveConvirmationInitializer();\n\n protected ConfirmationAckListener ackDelivery(final Channel channel, final AMQPPlugin plugin, final AMQPPluginData data)\n {\n return new ConfirmationAckListener() {\n @Override\n public void ackDelivery(long deliveryTag) throws IOException\n {\n if ( ! data.isTransactional) {\n plugin.logDebug(\"Immidiate ack message \" + deliveryTag);\n channel.basicAck(deliveryTag, false);\n data.ack++;\n\n return;\n }\n\n plugin.logDebug(\"Postponed ack message \" + deliveryTag);\n data.ackMsgInTransaction.add(deliveryTag);\n }\n };\n }\n\n protected ConfirmationRejectListener rejectDelivery(final Channel channel, final AMQPPlugin plugin, final AMQPPluginData data)\n {\n return new ConfirmationRejectListener() {\n @Override\n public void rejectDelivery(long deliveryTag) throws IOException\n {\n plugin.incrementLinesRejected();\n\n if ( ! data.isTransactional) {\n plugin.logDebug(\"Immidiate reject message \" + deliveryTag);\n channel.basicNack(deliveryTag, false, false);\n data.rejected++;\n\n return;\n }\n\n plugin.logDebug(\"Postponed reject message \" + deliveryTag);\n data.rejectedMsgInTransaction.add(deliveryTag);\n }\n };\n }\n\n @Override\n public void initialize(final Channel channel, final AMQPPlugin plugin, final AMQPPluginData data) throws IOException, KettleStepException\n {\n //bind to step with acknowledge rows on input stream\n if ( ! Const.isEmpty(data.ackStepName) ) {\n\n final StepInterface si = plugin.getTrans().getStepInterface( data.ackStepName, 0);\n\n if (si == null) {\n throw new KettleStepException(\"Can not find step : \" + data.ackStepName );\n }\n\n if (plugin.getTrans().getStepInterface( data.ackStepName, 1 ) != null) {\n throw new KettleStepException(\"Only SINGLE INSTANCE Steps supported : \" + data.ackStepName );\n }\n\n si.addRowListener(new ConfirmationRowStepListener(data.ackStepDeliveryTagField, ackDelivery(channel, plugin, data)));\n\n if (data.isTransactional) {\n data.ackMsgInTransaction = new ArrayList<Long>();\n }\n }\n\n //bind to step with rejected rows on input stream\n if ( ! Const.isEmpty(data.rejectStepName) ) {\n\n final StepInterface si = plugin.getTrans().getStepInterface( data.rejectStepName, 0 );\n\n if (si == null) {\n throw new KettleStepException(\"Can not find step : \" + data.rejectStepName );\n }\n\n if (plugin.getTrans().getStepInterface( data.rejectStepName, 1 ) != null) {\n throw new KettleStepException(\"Only SINGLE INSTANCE Steps supported : \" + data.rejectStepName );\n }\n\n si.addRowListener(new ConfirmationRowStepListener(data.rejectStepDeliveryTagField, rejectDelivery(channel, plugin, data)));\n\n if (data.isTransactional) {\n data.rejectedMsgInTransaction = new ArrayList<Long>();\n }\n }\n }\n}", "public class ConsumerDeclareInitializer implements Initializer\n{\n public static final ConsumerDeclareInitializer INSTANCE = new ConsumerDeclareInitializer();\n\n @Override\n public void initialize(final Channel channel, final AMQPPlugin plugin, final AMQPPluginData data) throws IOException\n {\n plugin.logMinimal(String.format(\"Declaring Queue '%s' {durable:%s, exclusive:%s, auto_delete:%s}\", data.target, data.isDurable, data.isExclusive, data.isAutodel));\n channel.queueDeclare(data.target, data.isDurable, data.isExclusive, data.isAutodel, null);\n\n for (final Binding item : data.bindings) {\n final String queueName = data.target;\n final String exchangeName = plugin.environmentSubstitute(item.getTarget());\n final String routingKey = plugin.environmentSubstitute(item.getRouting());\n\n plugin.logMinimal(String.format(\"Binding Queue '%s' to Exchange '%s' using routing key '%s'\", queueName, exchangeName, routingKey));\n channel.queueBind(queueName, exchangeName, routingKey);\n }\n }\n}", "public class ProducerDeclareInitializer implements Initializer\n{\n public static final ProducerDeclareInitializer INSTANCE = new ProducerDeclareInitializer();\n\n @Override\n public void initialize(final Channel channel, final AMQPPlugin plugin, final AMQPPluginData data) throws IOException\n {\n plugin.logMinimal(String.format(\"Declaring Exchange '%s' {type:%s, durable:%s, auto_delete:%s}\", data.target, data.exchtype, data.isDurable, data.isAutodel));\n channel.exchangeDeclare(data.target, data.exchtype, data.isDurable, data.isAutodel, null);\n\n for (final Binding item : data.bindings) {\n final String exchangeName = data.target;\n final String targetName = plugin.environmentSubstitute(item.getTarget());\n final String routingKey = plugin.environmentSubstitute(item.getRouting());\n final String targetType = plugin.environmentSubstitute(item.getTargetType());\n\n if (AMQPPluginData.TARGET_TYPE_QUEUE.equals(targetType)) {\n plugin.logMinimal(String.format(\"Binding Queue '%s' to Exchange '%s' using routing key '%s'\", targetName, exchangeName, routingKey));\n channel.queueBind(targetName, exchangeName, routingKey);\n\n continue;\n }\n\n plugin.logMinimal(String.format(\"Binding Exchange '%s' to Exchange '%s' using routing key '%s'\", targetName, exchangeName, routingKey));\n channel.exchangeBind(targetName, exchangeName, routingKey);\n }\n }\n}" ]
import com.instaclick.pentaho.plugin.amqp.AMQPPlugin; import com.instaclick.pentaho.plugin.amqp.AMQPPluginData; import com.instaclick.pentaho.plugin.amqp.AMQPPluginMeta; import com.instaclick.pentaho.plugin.amqp.initializer.ActiveConvirmationInitializer; import com.instaclick.pentaho.plugin.amqp.initializer.ConsumerDeclareInitializer; import com.instaclick.pentaho.plugin.amqp.initializer.ProducerDeclareInitializer; import com.rabbitmq.client.Channel; import static org.hamcrest.CoreMatchers.instanceOf; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Before; import static org.mockito.Mockito.*;
package com.instaclick.pentaho.plugin.amqp.processor; public class ProcessorFactoryTest { AMQPPluginMeta meta; AMQPPluginData data; AMQPPlugin plugin; Channel channel; @Before public void setUp() { channel = mock(Channel.class, RETURNS_MOCKS); meta = mock(AMQPPluginMeta.class); data = mock(AMQPPluginData.class); plugin = mock(AMQPPlugin.class); data.target = "queue_name"; } @Test public void testProcessorForActiveConfirmationDeclaringConsumer() throws Exception { final ProcessorFactory instance = new ProcessorFactory() { @Override protected Channel channelFor(AMQPPluginData data) { return channel; } }; data.activeConfirmation = true; data.isWaitingConsumer = true; data.isDeclare = true; data.isConsumer = true; final Processor processor = instance.processorFor(plugin, data, meta); assertThat(processor, instanceOf(WaitingConsumerProcessor.class)); final BaseProcessor baseProcessor = (BaseProcessor) processor; assertEquals(2, baseProcessor.initializers.size());
assertTrue(baseProcessor.initializers.contains(ConsumerDeclareInitializer.INSTANCE));
4
marcocor/smaph
src/main/java/it/unipi/di/acube/smaph/learn/featurePacks/BindingFeaturePack.java
[ "public class QueryInformation {\n\tpublic boolean includeSourceNormalSearch;\n\tpublic boolean includeSourceWikiSearch;\n\tpublic boolean includeSourceSnippets;\n\tpublic Double webTotalNS;\n\tpublic List<String> allBoldsNS;\n\tpublic HashMap<Integer, Integer> idToRankNS;\n\tpublic List<Pair<String, Integer>> boldsAndRankNS;\n\tpublic int resultsCountNS;\n\tpublic double webTotalWS;\n\tpublic List<Pair<String, Integer>> boldsAndRankWS;\n\tpublic HashMap<Integer, Integer> idToRankWS;\n\tpublic HashMap<Tag, List<String>> entityToBoldsSA;\n\tpublic HashMap<Tag, List<String>> entityToMentionsSA;\n\tpublic HashMap<Tag, List<Integer>> entityToRanksSA;\n\tpublic HashMap<Tag, List<HashMap<String, Double>>> entityToAdditionalInfosSA;\n\tpublic Set<Tag> candidatesSA;\n\tpublic Set<Tag> candidatesNS;\n\tpublic Set<Tag> candidatesWS;\n\t\n\tprivate Set<Tag> allCandidates = null;\n\t\n\tpublic Set<Tag> allCandidates() {\n\t\tif (allCandidates == null){\n\t\t\tallCandidates= new HashSet<Tag>();\n\t\t\tif (includeSourceSnippets)\n\t\t\t\tallCandidates.addAll(candidatesSA);\n\t\t\tif (includeSourceNormalSearch)\n\t\t\t\tallCandidates.addAll(candidatesNS);\n\t\t\tif (includeSourceWikiSearch)\n\t\t\t\tallCandidates.addAll(candidatesWS);\n\t\t}\n\t\treturn allCandidates;\n\t}\n}", "public class SmaphUtils {\n\tprivate final static Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());\n\tpublic static final String BASE_DBPEDIA_URI = \"http://dbpedia.org/resource/\";\n\tpublic static final String BASE_WIKIPEDIA_URI = \"http://en.wikipedia.org/wiki/\";\n\tpublic static final String WIKITITLE_ENDPAR_REGEX = \"\\\\s*\\\\([^\\\\)]*\\\\)\\\\s*$\";\n\n\t/**\n\t * For each word of bold, finds the word in query that has the minimum edit\n\t * distance, normalized by the word length. Returns the average of those\n\t * distances.\n\t * \n\t * @param query\n\t * a query.\n\t * @param bold\n\t * a bold.\n\t * @return the averaged normalized word-by-word edit distance of bold\n\t * against query.\n\t */\n\tpublic static double getMinEditDist(String query, String bold) {\n\t\treturn getMinEditDist(query, bold, null);\n\t}\n\n\t/**\n\t * For each word of bold, finds the word in query that has the minimum edit\n\t * distance, normalized by the word length. Put that word in minTokens.\n\t * Returns the average of those distances.\n\t * \n\t * @param query\n\t * a query.\n\t * @param bold\n\t * a bold.\n\t * @param minTokens\n\t * the tokens of query having minimum edit distance.\n\t * @return the averaged normalized word-by-word edit distance of bold\n\t * against query.\n\t */\n\tpublic static double getMinEditDist(String query, String bold,\n\t\t\tList<String> minTokens) {\n\t\tList<String> tokensQ = tokenize(query);\n\t\tList<String> tokensB = tokenize(bold);\n\n\t\tif (tokensB.size() == 0 || tokensQ.size() == 0)\n\t\t\treturn 1;\n\n\t\tfloat avgMinDist = 0;\n\t\tfor (String tokenB : tokensB) {\n\t\t\tfloat minDist = Float.MAX_VALUE;\n\t\t\tString bestQToken = null;\n\t\t\tfor (String tokenQ : tokensQ) {\n\t\t\t\tfloat relLev = getNormEditDistance(tokenB, tokenQ);\n\t\t\t\tif (relLev < minDist) {\n\t\t\t\t\tminDist = relLev;\n\t\t\t\t\tbestQToken = tokenQ;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (minTokens != null)\n\t\t\t\tminTokens.add(bestQToken);\n\t\t\tavgMinDist += minDist;\n\t\t}\n\t\treturn avgMinDist / tokensB.size();\n\t}\n\n\t/**\n\t * @param tokenB\n\t * a word.\n\t * @param tokenQ\n\t * another word.\n\t * @return the normalized edit distance between tokenB and tokenQ.\n\t */\n\tpublic static float getNormEditDistance(String tokenB, String tokenQ) {\n\t\tif (tokenQ.isEmpty() || tokenB.isEmpty())\n\t\t\treturn 1;\n\t\tint lev = StringUtils.getLevenshteinDistance(tokenB, tokenQ);\n\t\treturn (float) lev / (float) Math.max(tokenB.length(), tokenQ.length());\n\t}\n\n\tpublic static float getNormEditDistanceLC(String tokenB, String tokenQ) {\n\t\ttokenB = tokenB.replaceAll(\"\\\\W+\", \" \").toLowerCase();\n\t\ttokenQ = tokenQ.replaceAll(\"\\\\W+\", \" \").toLowerCase();\n\t\treturn getNormEditDistance(tokenB, tokenQ);\n\t}\n\n\tpublic static double weightedGeometricAverage(double[] vals, double[] weights) {\n\t\tif (vals.length != weights.length)\n\t\t\tthrow new IllegalArgumentException();\n\n\t\tdouble num = 0;\n\t\tdouble denum = 0;\n\n\t\tfor (int i = 0; i < vals.length; i++) {\n\t\t\tnum += Math.log(vals[i]) * weights[i];\n\t\t\tdenum += weights[i];\n\t\t}\n\n\t\treturn Math.exp(num / denum);\n\t}\n\n\t/**\n\t * @param title\n\t * the title of a Wikipedia page.\n\t * @return true iff the title is that of a regular page.\n\t */\n\tpublic static boolean acceptWikipediaTitle(String title) {\n\t\t// TODO: this can definitely be done in a cleaner way.\n\t\treturn !(title.startsWith(\"Talk:\") || title.startsWith(\"Special:\")\n\t\t\t\t|| title.startsWith(\"Portal:\")\n\t\t\t\t|| title.startsWith(\"Wikipedia:\")\n\t\t\t\t|| title.startsWith(\"Template:\")\n\t\t\t\t|| title.startsWith(\"Wikipedia_talk:\")\n\t\t\t\t|| title.startsWith(\"File:\") || title.startsWith(\"User:\")\n\t\t\t\t|| title.startsWith(\"Category:\") || title.startsWith(\"List\") || title\n\t\t\t\t.contains(\"(disambiguation)\"));\n\t}\n\n\t/**\n\t * @param ftrCount\n\t * the number of features.\n\t * @param excludedFeatures\n\t * the features that have to be excluded from the feature list.\n\t * @return a vector containing all feature ids from 1 to ftrCount\n\t * (included), except those in excludedFeatures.\n\t */\n\tpublic static int[] getAllFtrVect(int ftrCount, int[] excludedFeatures) {\n\t\tArrays.sort(excludedFeatures);\n\t\tVector<Integer> res = new Vector<>();\n\t\tfor (int i = 1; i < ftrCount + 1; i++)\n\t\t\tif (Arrays.binarySearch(excludedFeatures, i) < 0)\n\t\t\t\tres.add(i);\n\t\treturn ArrayUtils.toPrimitive(res.toArray(new Integer[] {}));\n\t}\n\n\t/**\n\t * @param ftrCount\n\t * the number of features.\n\t * @return a vector containing all feature ids from 1 to ftrCount (included.\n\t */\n\tpublic static int[] getAllFtrVect(int ftrCount) {\n\t\treturn getAllFtrVect(ftrCount, new int[0]);\n\t}\n\n\t/**\n\t * @param base\n\t * @param ftrId\n\t * @return a new feature vector composed by base with the addition of ftrId.\n\t */\n\tpublic static int[] addFtrVect(int[] base, int ftrId) {\n\t\tif (base == null)\n\t\t\treturn new int[] { ftrId };\n\t\telse {\n\t\t\tif (ArrayUtils.contains(base, ftrId))\n\t\t\t\tthrow new IllegalArgumentException(\"Trying to add a feature to a vector that already contains it.\");\n\t\t\tint[] newVect = new int[base.length + 1];\n\t\t\tSystem.arraycopy(base, 0, newVect, 0, base.length);\n\t\t\tnewVect[newVect.length - 1] = ftrId;\n\t\t\tArrays.sort(newVect);\n\t\t\treturn newVect;\n\t\t}\n\t}\n\n\t/**\n\t * @param features\n\t * @param ftrToRemove\n\t * @return a new feature vector composed by base without ftrId.\n\t */\n\tpublic static int[] removeFtrVect(int[] features, int ftrToRemove) {\n\t\tint[] newFtrVect = new int[features.length -1];\n\t\tint j=0;\n\t\tfor (int i=0; i<features.length; i++)\n\t\t\tif (features[i] == ftrToRemove)\n\t\t\t\tcontinue;\n\t\t\telse\n\t\t\t\tnewFtrVect[j++] = features[i];\n\t\tif (j != newFtrVect.length)\n\t\t\tthrow new IllegalArgumentException(\"Feature \"+ ftrToRemove+\" is not present and cannot be removed.\");\n\t\tArrays.sort(newFtrVect);\n\t\treturn newFtrVect;\n\t}\n\n\t/**\n\t * @param ftrVectorStr a list of comma-separated integers (e.g. 1,5,6,7)\n\t * @return a feature vector with features provided as input.\n\t */\n\tpublic static int[] strToFeatureVector(String ftrVectorStr) {\n\t\tif (ftrVectorStr.isEmpty())\n\t\t\treturn new int[] {};\n\t\tString[] tokens = ftrVectorStr.split(\",\");\n\t\tint[] ftrVect = new int[tokens.length];\n\t\tfor (int j = 0; j < tokens.length; j++)\n\t\t\tftrVect[j] = Integer.parseInt(tokens[j]);\n\t\tArrays.sort(ftrVect);\n\t\treturn ftrVect;\n\t}\n\n\t/**\n\t * Turns a list of pairs <b,r>, where b is a bold and r is the position in\n\t * which the bold occurred, to the list of bolds and the hashmap between a\n\t * position and the list of bolds occurring in that position.\n\t * \n\t * @param boldAndRanks\n\t * a list of pairs <b,r>, where b is a bold and r is the position\n\t * in which the bold occurred.\n\t * @param positions\n\t * where to store the mapping between a position (rank) and all\n\t * bolds that appear in that position.\n\t * @param bolds\n\t * where to store the bolds.\n\t */\n\tpublic static void mapRankToBoldsLC(\n\t\t\tList<Pair<String, Integer>> boldAndRanks,\n\t\t\tHashMap<Integer, HashSet<String>> positions, HashSet<String> bolds) {\n\n\t\tfor (Pair<String, Integer> boldAndRank : boldAndRanks) {\n\t\t\tString spot = boldAndRank.first.toLowerCase();\n\t\t\tint rank = boldAndRank.second;\n\t\t\tif (bolds != null)\n\t\t\t\tbolds.add(spot);\n\t\t\tif (positions != null) {\n\t\t\t\tif (!positions.containsKey(rank))\n\t\t\t\t\tpositions.put(rank, new HashSet<String>());\n\t\t\t\tpositions.get(rank).add(spot);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * Turns a list of pairs <b,r>, where b is a bold and r is the position in\n\t * which the bold occurred, to a mapping from a bold to the positions in\n\t * which the bolds occurred.\n\t * \n\t * @param boldAndRanks\n\t * a list of pairs <b,r>, where b is a bold and r is the position\n\t * in which the bold occurred.\n\t * @return a mapping from a bold to the positions in which the bold\n\t * occurred.\n\t */\n\tpublic static HashMap<String, HashSet<Integer>> findPositionsLC(\n\t\t\tList<Pair<String, Integer>> boldAndRanks) {\n\t\tHashMap<String, HashSet<Integer>> positions = new HashMap<>();\n\t\tfor (Pair<String, Integer> boldAndRank : boldAndRanks) {\n\t\t\tString bold = boldAndRank.first.toLowerCase();\n\t\t\tint rank = boldAndRank.second;\n\t\t\tif (!positions.containsKey(bold))\n\t\t\t\tpositions.put(bold, new HashSet<Integer>());\n\t\t\tpositions.get(bold).add(rank);\n\t\t}\n\t\treturn positions;\n\t}\n\n\t/**\n\t * Given a string, replaces all words with their stemmed version.\n\t * \n\t * @param str\n\t * a string.\n\t * @param stemmer\n\t * the stemmer.\n\t * @return str with all words stemmed.\n\t */\n\tprivate static String stemString(String str, EnglishStemmer stemmer) {\n\t\tString stemmedString = \"\";\n\t\tString[] words = str.split(\"\\\\s+\");\n\t\tfor (int i = 0; i < words.length; i++) {\n\t\t\tString word = words[i];\n\t\t\tstemmer.setCurrent(word);\n\t\t\tstemmer.stem();\n\t\t\tstemmedString += stemmer.getCurrent();\n\t\t\tif (i != words.length)\n\t\t\t\tstemmedString += \" \";\n\t\t}\n\t\treturn stemmedString;\n\t}\n\n\t/**\n\t * Compress a string with GZip.\n\t * \n\t * @param str\n\t * the string.\n\t * @return the compressed string.\n\t * @throws IOException\n\t * if something went wrong during compression.\n\t */\n\tpublic static byte[] compress(String str) throws IOException {\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\tGZIPOutputStream gzip = new GZIPOutputStream(out);\n\t\tgzip.write(str.getBytes(\"utf-8\"));\n\t\tgzip.close();\n\t\treturn out.toByteArray();\n\t}\n\n\t/**\n\t * Decompress a GZipped string.\n\t * \n\t * @param compressed\n\t * the sequence of bytes\n\t * @return the decompressed string.\n\t * @throws IOException\n\t * if something went wrong during decompression.\n\t */\n\tpublic static String decompress(byte[] compressed) throws IOException {\n\t\tGZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(\n\t\t\t\tcompressed));\n\t\treturn new String(IOUtils.toByteArray(gis), \"utf-8\");\n\t}\n\n\tpublic static List<String> tokenize(String text) {\n\t\tint start = -1;\n\t\tVector<String> tokens = new Vector<>();\n\t\tfor (int i = 0; i < text.length(); i++) {\n\t\t\tif (Character.isWhitespace(text.charAt(i))) {\n\t\t\t\tif (start != -1) {\n\t\t\t\t\ttokens.add(text.substring(start, i));\n\t\t\t\t\tstart = -1;\n\t\t\t\t}\n\t\t\t} else if (start == -1)\n\t\t\t\tstart = i;\n\t\t}\n\t\tif (start != -1)\n\t\t\ttokens.add(text.substring(start));\n\n\t\treturn tokens;\n\t}\n\n\tpublic static List<Pair<Integer, Integer>> findTokensPosition(String text) {\n\t\ttext = text.replaceAll(\"\\\\W\", \" \").replaceAll(\"\\\\s\", \" \");\n\t\tList<Pair<Integer, Integer>> positions = new Vector<>();\n\t\tint idx = 0;\n\t\twhile (idx < text.length()) {\n\t\t\twhile (idx < text.length() && text.charAt(idx) == ' ')\n\t\t\t\tidx++;\n\t\t\tif (idx == text.length())\n\t\t\t\tbreak;\n\t\t\tint start = idx;\n\t\t\twhile (idx < text.length() && text.charAt(idx) != ' ')\n\t\t\t\tidx++;\n\t\t\tint end = idx;\n\t\t\tpositions.add(new Pair<>(start, end));\n\t\t}\n\t\treturn positions;\n\t}\n\n\tpublic static List<String> findSegmentsStrings(String text) {\n\t\tVector<String> words = new Vector<String>();\n\t\tfor (Pair<Integer, Integer> startEnd : findTokensPosition(text))\n\t\t\twords.add(text.substring(startEnd.first, startEnd.second));\n\t\tVector<String> segments = new Vector<String>();\n\t\tfor (int start = 0; start < words.size(); start++) {\n\t\t\tfor (int end = 0; end < words.size(); end++){\n\t\t\t\tif (start <= end) {\n\t\t\t\t\tString segment = \"\";\n\t\t\t\t\tfor (int i = start; i <= end; i++) {\n\t\t\t\t\t\tsegment += words.get(i);\n\t\t\t\t\t\tif (i != end)\n\t\t\t\t\t\t\tsegment += \" \";\n\t\t\t\t\t}\n\t\t\t\t\tsegments.add(segment);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn segments;\n\t}\n\n\tpublic static List<Pair<Integer, Integer>> findSegments(String text) {\n\t\tList<Pair<Integer, Integer>> tokens = findTokensPosition(text);\n\t\tList<Pair<Integer, Integer>> segments = new Vector<>();\n\t\tfor (int n= 1; n<=tokens.size(); n++)\n\t\t\tfor (int i=0;i<=tokens.size()-n;i++)\n\t\t\t\tsegments.add(new Pair<Integer, Integer>(tokens.get(i).first, tokens.get(i+n-1).second));\n\t\treturn segments;\n\t}\n\n\tprivate static void addBIOToken(int n, char token, String sequence,\n\t\t\tList<String> sequences, int limit) {\n\t\tif (limit >= 0 && sequences.size() >= limit)\n\t\t\treturn;\n\t\tsequence += token;\n\t\tif (n > 0) {\n\t\t\taddBIOToken(n - 1, 'B', sequence, sequences, limit);\n\t\t\tif (token != 'O')\n\t\t\t\taddBIOToken(n - 1, 'I', sequence, sequences, limit);\n\t\t\taddBIOToken(n - 1, 'O', sequence, sequences, limit);\n\t\t} else\n\t\t\tsequences.add(sequence);\n\t}\n\n\tpublic static List<String> getBioSequences(int n, int limit) {\n\t\tList<String> sequences = new Vector<>();\n\t\taddBIOToken(n - 1, 'B', \"\", sequences, limit);\n\t\taddBIOToken(n - 1, 'O', \"\", sequences, limit);\n\t\treturn sequences;\n\t}\n\n\tpublic static List<List<Pair<Integer, Integer>>> getSegmentations(\n\t\t\tString query, int maxBioSequence) {\n\t\tList<Pair<Integer, Integer>> qTokens = findTokensPosition(query);\n\t\tList<List<Pair<Integer, Integer>>> segmentations = new Vector<>();\n\t\tList<String> bioSequences = getBioSequences(qTokens.size(),\n\t\t\t\tmaxBioSequence);\n\t\tfor (String bioSequence : bioSequences) {\n\t\t\tint start = -1;\n\t\t\tint end = -1;\n\t\t\tList<Pair<Integer, Integer>> segmentation = new Vector<>();\n\t\t\tfor (int i = 0; i < qTokens.size(); i++) {\n\t\t\t\tPair<Integer, Integer> token = qTokens.get(i);\n\t\t\t\tif (start >= 0\n\t\t\t\t\t\t&& (bioSequence.charAt(i) == 'B' || bioSequence\n\t\t\t\t\t\t.charAt(i) == 'O')) {\n\t\t\t\t\tsegmentation.add(new Pair<Integer, Integer>(start, end));\n\t\t\t\t\tstart = -1;\n\t\t\t\t}\n\t\t\t\tif (bioSequence.charAt(i) == 'B'\n\t\t\t\t\t\t|| bioSequence.charAt(i) == 'I') {\n\t\t\t\t\tif (start == -1)\n\t\t\t\t\t\tstart = token.first;\n\t\t\t\t\tend = token.second;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (start != -1)\n\t\t\t\tsegmentation.add(new Pair<Integer, Integer>(start, end));\n\t\t\tsegmentations.add(segmentation);\n\t\t}\n\t\treturn segmentations;\n\t}\n\n\tpublic static HashMap<Tag, String[]> getEntitiesToBoldsList(\n\t\t\tHashMap<Tag, List<String>> tagToBolds, Set<Tag> entityToKeep) {\n\t\tHashMap<Tag, String[]> res = new HashMap<>();\n\t\tfor (Tag t : tagToBolds.keySet())\n\t\t\tif (entityToKeep == null || entityToKeep.contains(t))\n\t\t\t\tres.put(t, tagToBolds.get(t).toArray(new String[]{}));\n\t\treturn res;\n\t}\n\n\tpublic static HashMap<Tag, String> getEntitiesToTitles(\n\t\t\tSet<Tag> acceptedEntities, WikipediaInterface wikiApi) {\n\t\tHashMap<Tag, String> res = new HashMap<>();\n\t\tfor (Tag t : acceptedEntities)\n\t\t\ttry {\n\t\t\t\tres.put(t, wikiApi.getTitlebyId(t.getConcept()));\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\treturn res;\n\t}\n\n\tpublic static int getNonAlphanumericCharCount(String str) {\n\t\tint count = 0;\n\t\tfor (char c : str.toCharArray())\n\t\t\tif (!((c >= 'a' &&c <= 'z') || (c >= 'A' &&c <= 'Z') || (c >= '0' &&c <= '9') || c == ' '))\n\t\t\t\tcount ++;\n\t\treturn count;\n\t}\n\n\tpublic static class ComparePairsByFirstElement<E extends Serializable, T extends Comparable<T> & Serializable> implements Comparator<Pair<T, E>> {\n\t\t@Override\n\t\tpublic int compare(Pair<T, E> o1, Pair<T, E> o2) {\n\t\t\treturn o1.first.compareTo(o2.first);\n\t\t}\n\t}\n\n\tpublic static class ComparePairsBySecondElement<E extends Serializable, T extends Comparable<T> & Serializable> implements Comparator<Pair<E, T>> {\n\t\t@Override\n\t\tpublic int compare(Pair<E, T> o1, Pair<E, T> o2) {\n\t\t\treturn o1.second.compareTo(o2.second);\n\t\t}\n\t}\n\n\t/**\n\t * @param tokensA\n\t * @param tokensB\n\t * @return true if tokensA is a strict sublist of tokensB (i.e. |tokensA| < |tokensB| and there are two indexes i and j s.t. tokensA.equals(tokensB.subList(i, j))).\n\t */\n\tpublic static boolean isSubToken(List<String> tokensA, List<String> tokensB){\n\t\tif (tokensA.size() >= tokensB.size())\n\t\t\treturn false;\n\t\tfor (int i=0 ; i<=tokensB.size() - tokensA.size(); i++)\n\t\t\tif (tokensA.equals(tokensB.subList(i, i+tokensA.size())))\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\n\t/**\n\t * @param bolds\n\t * a list of bolds\n\t * @param bold\n\t * a bold\n\t * @return the proportion between the number of times bold appears in the\n\t * list and the number of times in which shorter bolds having at\n\t * least one word in common appear in the list.\n\t */\n\tpublic static double getFragmentation(List<String> bolds, String bold) {\n\t\tint boldCount = 0;\n\t\tint fragmentsCount = 0;\n\t\tList<String> tokensBold = tokenize(stemString(bold, new EnglishStemmer()));\n\n\t\tfor (String b : bolds) {\n\t\t\tList<String> tokensB = tokenize(stemString(b, new EnglishStemmer()));\n\t\t\tif (tokensBold.equals(tokensB))\n\t\t\t\tboldCount++;\n\t\t\telse {\n\t\t\t\tif (isSubToken(tokensB, tokensBold))\n\t\t\t\t\tfragmentsCount ++;\n\t\t\t\t/*if (tokensB.size() < tokensBold.size()) {\n\t\t\t\t\tboolean found = false;\n\t\t\t\t\tfor (String tokenB : tokensB)\n\t\t\t\t\t\tfor (String tokenBold : tokensBold)\n\t\t\t\t\t\t\tif (tokenB.equals(tokenBold)) {\n\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\tif (found)\n\t\t\t\t\t\tfragmentsCount++;\n\t\t\t\t}*/\n\t\t\t}\n\t\t}\n\t\tif (boldCount == 0)\n\t\t\treturn 0.0;\n\t\treturn (double) boldCount / (double) (Math.pow(fragmentsCount, 1.4) + boldCount);\n\t}\n\n\t/**\n\t * @param bolds\n\t * a list of bolds\n\t * @param bold\n\t * a bold\n\t * @return the proportion between the number of times bold appears in the\n\t * list and the number of times in which longer bolds containing all\n\t * words of bold appear in the list.\n\t */\n\tpublic static double getAggregation(List<String> bolds, String bold) {\n\t\tint boldCount = 0;\n\t\tint fragmentsCount = 0;\n\t\tList<String> tokensBold = tokenize(stemString(bold, new EnglishStemmer()));\n\n\t\tfor (String b : bolds) {\n\t\t\tList<String> tokensB = tokenize(stemString(b, new EnglishStemmer()));\n\t\t\tif (tokensBold.equals(tokensB))\n\t\t\t\tboldCount++;\n\t\t\telse {\n\t\t\t\tif (isSubToken(tokensBold, tokensB))\n\t\t\t\t\tfragmentsCount ++;\n\t\t\t\t/*if (tokensB.size() > tokensBold.size()) {\n\t\t\t\t\tboolean cover = true;\n\t\t\t\t\tfor (String tokenBold : tokensBold)\n\t\t\t\t\t\tif (!tokensB.contains(tokenBold)){\n\t\t\t\t\t\t\tcover = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tif (cover)\n\t\t\t\t\t\tfragmentsCount++;\n\t\t\t\t}*/\n\t\t\t}\n\t\t}\n\t\tif (boldCount == 0)\n\t\t\treturn 0.0;\n\t\treturn (double) boldCount / (double) (Math.pow(fragmentsCount, 1.4) + boldCount);\n\t}\n\n\n\tpublic static List<String> boldPairsToListLC(\n\t\t\tList<Pair<String, Integer>> boldAndRanks) {\n\t\tList<String> res = new Vector<>();\n\t\tfor (Pair<String, Integer> boldAndRank : boldAndRanks)\n\t\t\tres.add(boldAndRank.first.toLowerCase());\n\t\treturn res;\n\t}\n\n\n\n\tpublic static Triple<Double, Double, Double> getMinMaxAvg(List<Double> values) {\n\t\tif (values.isEmpty())\n\t\t\treturn new ImmutableTriple<Double, Double, Double>(0.0, 0.0, 0.0);\n\n\t\tdouble minVal = Double.POSITIVE_INFINITY;\n\t\tdouble maxVal = Double.NEGATIVE_INFINITY;\n\t\tdouble avgVal = 0.0;\n\t\tfor (double v : values) {\n\t\t\tminVal = Math.min(v, minVal);\n\t\t\tmaxVal = Math.max(v, maxVal);\n\t\t\tavgVal += v / values.size();\n\t\t}\n\n\t\treturn new ImmutableTriple<Double, Double, Double>(minVal, maxVal,\n\t\t\t\tavgVal);\n\t}\n\n\tpublic static HashSet<ScoredAnnotation> collapseBinding(\n\t\t\tHashSet<ScoredAnnotation> binding) {\n\t\tif (binding.size() <= 1)\n\t\t\treturn binding;\n\n\t\tHashSet<ScoredAnnotation> res = new HashSet<>();\n\t\tVector<ScoredAnnotation> bindingOrdered = new Vector<>(binding);\n\t\tCollections.sort(bindingOrdered);\n\t\tScoredAnnotation firstEqual = bindingOrdered.get(0);\n\t\tfloat score = 0f;\n\t\tint equalCount = 0;\n\t\tfor (int i = 0; i < bindingOrdered.size(); i++) {\n\t\t\tScoredAnnotation nextAnn = (i == bindingOrdered.size() - 1) ? null\n\t\t\t\t\t: bindingOrdered.get(i + 1);\n\t\t\tScoredAnnotation annI = bindingOrdered.get(i);\n\t\t\tscore += annI.getScore();\n\t\t\tequalCount++;\n\t\t\tif (nextAnn == null\n\t\t\t\t\t|| nextAnn.getConcept() != firstEqual.getConcept()) {\n\t\t\t\tres.add(new ScoredAnnotation(firstEqual.getPosition(), annI\n\t\t\t\t\t\t.getPosition()\n\t\t\t\t\t\t+ annI.getLength()\n\t\t\t\t\t\t- firstEqual.getPosition(), firstEqual.getConcept(),\n\t\t\t\t\t\tscore / equalCount));\n\t\t\t\tfirstEqual = nextAnn;\n\t\t\t\tscore = 0;\n\t\t\t\tequalCount = 0;\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n\tpublic static <T> List<T> sorted(Collection<T> c, Comparator<T> comp) {\n\t\tList<T> list = new ArrayList<T>(c);\n\t\tCollections.sort(list, comp);\n\t\treturn list;\n\t}\n\tpublic static <T extends Comparable<? super T>> List<T> sorted(Collection<T> c) {\n\t\treturn sorted(c, null);\n\t}\n\n\tpublic static String removeTrailingParenthetical(String title) {\n\t\treturn title.replaceAll(WIKITITLE_ENDPAR_REGEX, \"\");\n\t}\n\n\tpublic static JSONObject httpQueryJson(String urlAddr) {\n\t\tString resultStr = null;\n\t\ttry {\n\t\t\tURL url = new URL(urlAddr);\n\t\t\tHttpURLConnection conn = (HttpURLConnection) url.openConnection();\n\t\t\tconn.setRequestMethod(\"GET\");\n\n\t\t\tif (conn.getResponseCode() != 200) {\n\t\t\t\tScanner s = new Scanner(conn.getErrorStream())\n\t\t\t\t.useDelimiter(\"\\\\A\");\n\t\t\t\tLOG.error(\"Got HTTP error {}. Message is: {}\",\n\t\t\t\t\t\tconn.getResponseCode(), s.next());\n\t\t\t\ts.close();\n\t\t\t}\n\n\t\t\tScanner s = new Scanner(conn.getInputStream())\n\t\t\t.useDelimiter(\"\\\\A\");\n\t\t\tresultStr = s.hasNext() ? s.next() : \"\";\n\n\t\t\treturn new JSONObject(resultStr);\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static double computeAvgRank(List<Integer> positions, int resultsCount) {\n\t\tif (resultsCount==0) return 1;\n\t\tfloat avg = 0;\n\t\tfor (int pos : positions)\n\t\t\tavg += (float)pos/(float)resultsCount;\n\t\tavg += resultsCount - positions.size();\n\n\t\tavg /= resultsCount;\n\t\treturn avg;\n\t}\n\n\tpublic static double getFrequency(int occurrences, int resultsCount) {\n\t\treturn (float) occurrences / (float) resultsCount;\n\t}\n\n\tpublic static <T1, T2> HashMap<T1, T2> inverseMap(HashMap<T2, T1> map) {\n\t\treturn (HashMap<T1, T2>) map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));\n\t}\n\n\tprivate static void populateBindingsRec(List<Tag> chosenCandidates, List<List<Tag>> candidates, List<List<Tag>> bindings,\n\t\t\tint maxBindings) {\n\t\tif (maxBindings > 0 && bindings.size() >= maxBindings)\n\t\t\treturn;\n\t\tif (chosenCandidates.size() == candidates.size()) {\n\t\t\tbindings.add(new Vector<Tag>(chosenCandidates));\n\t\t\treturn;\n\t\t}\n\t\tList<Tag> candidatesToExpand = candidates.get(chosenCandidates.size());\n\t\tfor (Tag candidate : candidatesToExpand) {\n\t\t\tList<Tag> nextChosenCandidates = new Vector<>(chosenCandidates);\n\t\t\tnextChosenCandidates.add(candidate);\n\t\t\tpopulateBindingsRec(nextChosenCandidates, candidates, bindings, maxBindings);\n\t\t}\n\t}\n\n\t/**\n\t * @param candidates for each segment, the list of candidates it may be linked to\n\t * @param maxBindings the maximum number of returned bindings (ignored if less than 1)\n\t * @return the possible bindings for a single segmentations\n\t */\n\tpublic static List<List<Tag>> getBindings(List<List<Tag>> candidates, int maxBindings) {\n\t\tList<List<Tag>> bindings = new Vector<List<Tag>>();\n\t\tList<Tag> chosenCandidates = new Vector<Tag>();\n\t\tpopulateBindingsRec(chosenCandidates, candidates, bindings, maxBindings);\n\t\treturn bindings;\n\t}\n\n\tpublic static String getDBPediaURI(String title) {\n\t\treturn BASE_DBPEDIA_URI + WikipediaInterface.normalize(title);\n\t}\n\n\tpublic static String getWikipediaURI(String title) {\n\t\ttry {\n\t\t\treturn BASE_WIKIPEDIA_URI + URLEncoder.encode(title, \"utf8\").replace(\"+\", \"%20\");\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static void exportToNif(A2WDataset ds, String baseUri, WikipediaInterface wikiApi, OutputStream outputStream) {\n\t\tList<org.aksw.gerbil.transfer.nif.Document> documents = new Vector<>();\n\n\t\tfor (int i = 0; i < ds.getSize(); i++) {\n\t\t\tString text = ds.getTextInstanceList().get(i);\n\t\t\torg.aksw.gerbil.transfer.nif.Document d = new DocumentImpl(text, baseUri + \"/doc\" + i);\n\n\t\t\tfor (it.unipi.di.acube.batframework.data.Annotation a : ds.getA2WGoldStandardList().get(i)) {\n\t\t\t\tString title;\n\t\t\t\ttry {\n\t\t\t\t\ttitle = wikiApi.getTitlebyId(a.getConcept());\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tthrow new RuntimeException(e);\n\t\t\t\t}\n\t\t\t\td.addMarking(new NamedEntity(a.getPosition(), a.getLength(), getDBPediaURI(title)));\n\t\t\t}\n\t\t\tdocuments.add(d);\n\t\t}\n\t\tNIFWriter writer = new TurtleNIFWriter();\n\t\twriter.writeNIF(documents, outputStream);\n\t}\n}", "public class WATRelatednessComputer implements Serializable {\n\tprivate final static Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());\n\tprivate static final long serialVersionUID = 1L;\n\tprivate static WATRelatednessComputer instance = new WATRelatednessComputer();\n\tprivate Object2DoubleOpenHashMap<Pair<Integer,Integer>> cacheJaccard = new Object2DoubleOpenHashMap<>();\n\tprivate Object2DoubleOpenHashMap<Pair<Integer,Integer>> cacheMW = new Object2DoubleOpenHashMap<>();\n\tprivate Object2DoubleOpenHashMap<String> cacheLp = new Object2DoubleOpenHashMap<>();\n\tprivate static long flushCounter = 0;\n\tprivate static final int FLUSH_EVERY = 1000;\n\tprivate static final String URL_TEMPLATE_JACCARD = \"%s/relatedness/graph?gcube-token=%s&ids=%d&ids=%d&relatedness=jaccard\";\n\tprivate static final String URL_TEMPLATE_MW = \"%s/relatedness/graph?gcube-token=%s&ids=%d&ids=%d&relatedness=mw\";\n\tprivate static final String URL_TEMPLATE_SPOT = \"%s/sf/sf?gcube-token=%s&text=%s\";\n\tprivate static String baseUri = \"https://wat.d4science.org/wat\";\n\tprivate static String gcubeToken = null;\n\tprivate static String resultsCacheFilename = null;\n\t\n\tpublic static void setBaseUri(String watBaseUri){\n\t\tbaseUri = watBaseUri;\n\t}\n\t\n\tpublic static void setGcubeToken(String watGcubeToken){\n\t\tgcubeToken = watGcubeToken;\n\t}\n\t\n\tprivate synchronized void increaseFlushCounter()\n\t\t\tthrows FileNotFoundException, IOException {\n\t\tflushCounter++;\n\t\tif ((flushCounter % FLUSH_EVERY) == 0)\n\t\t\tflush();\n\t}\n\n\tpublic static synchronized void flush() throws FileNotFoundException,\n\t\t\tIOException {\n\t\tif (flushCounter > 0 && resultsCacheFilename != null) {\n\t\t\tLOG.info(\"Flushing relatedness cache... \");\n\t\t\tnew File(resultsCacheFilename).createNewFile();\n\t\t\tObjectOutputStream oos = new ObjectOutputStream(\n\t\t\t\t\tnew FileOutputStream(resultsCacheFilename));\n\t\t\toos.writeObject(instance);\n\t\t\toos.close();\n\t\t\tLOG.info(\"Flushing relatedness cache done.\");\n\t\t}\n\t}\n\t\n\tpublic static void setCache(String cacheFilename)\n\t\t\tthrows FileNotFoundException, IOException, ClassNotFoundException {\n\t\tif (resultsCacheFilename != null\n\t\t\t\t&& resultsCacheFilename.equals(cacheFilename))\n\t\t\treturn;\n\t\tLOG.info(\"Loading relatedness cache...\");\n\t\tresultsCacheFilename = cacheFilename;\n\t\tif (new File(resultsCacheFilename).exists()) {\n\t\t\tObjectInputStream ois = new ObjectInputStream(new FileInputStream(\n\t\t\t\t\tresultsCacheFilename));\n\t\t\tinstance = (WATRelatednessComputer) ois.readObject();\n\t\t\tois.close();\n\t\t}\n\t}\n\n\tprivate double queryJsonRel(int wid1, int wid2, String urlTemplate) {\n\t\tString url = String.format(urlTemplate, baseUri, gcubeToken, wid1, wid2);\n\t\tLOG.info(url);\n\t\tJSONObject obj = SmaphUtils.httpQueryJson(url);\n\t\ttry {\n\t\t\tincreaseFlushCounter();\n\t\t\tdouble rel = obj.getJSONArray(\"pairs\").getJSONObject(0).getDouble(\"relatedness\");\n\t\t\tLOG.debug(\" -> \" + rel);\n\t\t\treturn rel;\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tprivate double getGenericRelatedness(int wid1, int wid2, Object2DoubleOpenHashMap<Pair<Integer,Integer>> cache, String url){\n\t\tif (wid2 < wid1) {\n\t\t\tint tmp = wid2;\n\t\t\twid2 = wid1;\n\t\t\twid2 = tmp;\n\t\t}\n\t\tPair <Integer,Integer> p = new Pair<Integer,Integer>(wid1,wid2);\n\t\tif (!cache.containsKey(p))\n\t\t\tcache.put(p, queryJsonRel(wid1, wid2, url));\n\t\t\t\n\t\treturn cache.getDouble(p);\n\t}\n\t\n\tpublic static double getJaccardRelatedness(int wid1, int wid2) {\n\t\tif (wid1 == wid2) return 1.0;\n\t\treturn instance.getGenericRelatedness(wid1, wid2, instance.cacheJaccard, URL_TEMPLATE_JACCARD);\n\t}\n\n\tpublic static double getMwRelatedness(int wid1, int wid2) {\n\t\tif (wid1 == wid2) return 1.0;\n\t\treturn instance.getGenericRelatedness(wid1, wid2, instance.cacheMW, URL_TEMPLATE_MW);\n\t}\n\n\tpublic static double getLp(String anchor) {\n\t\tif (!instance.cacheLp.containsKey(anchor))\n\t\t\tinstance.cacheLp.put(anchor, queryJsonLp(anchor));\n\t\treturn instance.cacheLp.get(anchor);\n\t}\n\n\tprivate static double queryJsonLp(String anchor) {\n\t\tString url;\n\t\ttry {\n\t\t\turl = String.format(URL_TEMPLATE_SPOT, baseUri, gcubeToken, URLEncoder.encode(anchor, \"utf-8\"));\n\t\t} catch (UnsupportedEncodingException e1) {\n\t\t\te1.printStackTrace();\n\t\t\tthrow new RuntimeException(e1);\n\t\t}\n\t\t\n\t\tLOG.debug(\"Querying {}\", url);\n\t\t\n\t\tJSONObject obj = SmaphUtils.httpQueryJson(url);\n\t\t\n\t\ttry {\n\t\t\tinstance.increaseFlushCounter();\n\t\t\treturn obj.getDouble(\"link_probability\");\n\t\t} catch (Exception e1) {\n\t\t\te1.printStackTrace();\n\t\t\tthrow new RuntimeException(e1);\n\t\t}\n\t}\n\n}", "public class EntityToAnchors {\n\tpublic static final String DEFAULT_INPUT = \"./data/anchors.tsv\";\n\tpublic static final String DATASET_FILENAME = \"./mapdb/e2a.db\";\n\n\tprivate DB db;\n\t/**\n\t * entity -> anchor-IDs\n\t */\n\tprivate HTreeMap<Integer, int[]> entityToAnchorIDs;\n\t\n\t/**\n\t * entity -> frequencies of anchor-ID for entity\n\t */\n\tprivate HTreeMap<Integer,int[]> entityToFreqs;\n\t\n\t/**\n\t * From anchor to anchor-ID\n\t */\n\tprivate HTreeMap<String, Integer> anchorToAid;\n\t\n\t/**\n\t * From anchor-ID to snchor\n\t */\n\tprivate HTreeMap<Integer, String> aidToAnchor;\n\t\n\t/**\n\t * anchor-ID -> how many times the anchor has been seen \n\t */\n\tprivate HTreeMap<Integer, Integer> anchorToOccurrences;\t\n\t\n\tprivate static Logger logger = LoggerFactory.getLogger(EntityToAnchors.class.getName());\n\n\tpublic static EntityToAnchors fromDB(String datasetFilename) {\n\t\tlogger.info(\"Opening E2A database.\");\n\t\tDB db = DBMaker.fileDB(datasetFilename).fileMmapEnable().readOnly().closeOnJvmShutdown().make();\n\t\tEntityToAnchors e2a = new EntityToAnchors(db);\n\t\tlogger.info(\"Loading E2A database done.\");\n\t\treturn e2a;\n\t}\n\n\tprivate EntityToAnchors(DB db) {\n\t\tthis.db = db;\n\t\tentityToAnchorIDs = db.hashMap(\"entityToAnchorIDs\", Serializer.INTEGER, Serializer.INT_ARRAY).createOrOpen();\n\t\tentityToFreqs = db.hashMap(\"entityToFreqs\", Serializer.INTEGER, Serializer.INT_ARRAY).createOrOpen();\n\t\tanchorToAid = db.hashMap(\"anchorToAid\", Serializer.STRING, Serializer.INTEGER).createOrOpen();\n\t\taidToAnchor = db.hashMap(\"aidToAnchor\", Serializer.INTEGER, Serializer.STRING).createOrOpen();\n\t\tanchorToOccurrences = db.hashMap(\"anchorToOccurrences\", Serializer.INTEGER, Serializer.INTEGER).createOrOpen();\n\t}\n\n\tprivate static void createDB(String file) throws FileNotFoundException,\n\t\t\tIOException {\n\t\t\n\t\tInputStream inputStream = new FileInputStream(file);\n\t\tBufferedReader buffered = new BufferedReader(new InputStreamReader(\n\t\t\t\tinputStream, \"UTF-8\"));\n\n\t\tlogger.info(\"Building database...\");\n\t\tEntityToAnchors mdb = new EntityToAnchors(DBMaker.fileDB(DATASET_FILENAME).fileMmapEnable().closeOnJvmShutdown().make());\n\n\t\tlong count = 0;\n\t\tlong processedMbs = 0;\n\t\tInt2ObjectOpenHashMap<Int2IntArrayMap> entityToAnchorIDToFreqBuffer = new Int2ObjectOpenHashMap<Int2IntArrayMap>();\n\t\t\n\t\tint lastAnchorId = 0;\n\t\tString line = null;\n\t\twhile ((line = buffered.readLine()) != null) {\n\t\t\tcount += line.length();\n\t\t\tif (count > processedMbs * (10 * 1024 * 1024))\n\t\t\t\tlogger.info(String.format(\"Read %d MiB.\", 10*(processedMbs++)));\n\t\t\t\n\t\t\tString[] tokens = line.split(\"\\t\");\n\t\t\tif (tokens.length != 3){\n\t\t\t\tbuffered.close();\n\t\t\t\tthrow new RuntimeException(\"Read line: [\" + line + \"] should have three tokens.\");\n\t\t\t}\n\t\t\t\n\t\t\tString anchor = tokens[0].toLowerCase();\n\t\t\tint freq = Integer.parseInt(tokens[2]);\n\n\t\t\tif (!mdb.anchorToAid.containsKey(anchor)){\n\t\t\t\tmdb.anchorToAid.put(anchor, lastAnchorId);\n\t\t\t\tmdb.aidToAnchor.put(lastAnchorId, anchor);\n\t\t\t\tlastAnchorId++;\n\t\t\t}\n\t\t\t\t\n\t\t\tInteger aId = mdb.anchorToAid.get(anchor);\n\t\t\t\n\t\t\tint pageId = Integer.parseInt(tokens[1]);\n\n\t\t\tInt2IntArrayMap aidToFreqMap = entityToAnchorIDToFreqBuffer.get(pageId);\n\t\t\tif (aidToFreqMap == null){\n\t\t\t\taidToFreqMap = new Int2IntArrayMap();\n\t\t\t\tentityToAnchorIDToFreqBuffer.put(pageId, aidToFreqMap);\n\t\t\t}\n\t\t\tif (!aidToFreqMap.containsKey(aId))\n\t\t\t\taidToFreqMap.put(aId.intValue(), freq);\n\t\t\telse\n\t\t\t\taidToFreqMap.put(aId.intValue(), freq + aidToFreqMap.get(aId)); //increase the occurrence for anchor by freq (this should only happen for anchors with different case, same content.)\n\t\t\t\n\t\t\tif (!mdb.anchorToOccurrences.containsKey(aId))\n\t\t\t\tmdb.anchorToOccurrences.put(aId, 0);\n\t\t\tmdb.anchorToOccurrences.put(aId, mdb.anchorToOccurrences.get(aId) + freq);\n\t\t}\n\t\tbuffered.close();\n\t\tlogger.info(String.format(\"Finished reading %s (%.1f MBs)\", file, count / 1024.0 / 1024.0));\n\t\t\n\t\tlogger.info(\"Copying entity-to-anchor mappings in db...\");\n\t\tint c = 0;\n\t\tfor ( int id : entityToAnchorIDToFreqBuffer.keySet()){\n\t\t\tif (++c % 1000000 == 0)\n\t\t\t\tlogger.info(String.format(\"Copied %d entity-to-anchor mappings.\", c));\n\t\t\tInt2IntArrayMap anchorToFreq = entityToAnchorIDToFreqBuffer.get(id);\n\t\t\tint[] anchors = new int[anchorToFreq.size()];\n\t\t\tint[] frequencies = new int[anchorToFreq.size()];\n\t\t\tint idx=0;\n\t\t\tfor (Entry<Integer, Integer> p : anchorToFreq.entrySet()){\n\t\t\t\tanchors[idx] = p.getKey();\n\t\t\t\tfrequencies[idx] = p.getValue();\n\t\t\t\tidx++;\n\t\t\t}\n\t\t\tmdb.entityToAnchorIDs.put(id, anchors);\n\t\t\tmdb.entityToFreqs.put(id, frequencies);\n\t\t}\n\t\t\n\t\tlogger.info(\"Committing changes...\");\n\t\tmdb.db.commit();\n\n\t\tlogger.info(\"Closing db...\");\n\t\tmdb.db.close();\n\t}\n\t\n\tpublic String idToAnchor(int aId){\n\t\tString anchor = aidToAnchor.get(Integer.valueOf(aId));\n\t\tif (anchor == null)\n\t\t\tthrow new RuntimeException(\"Anchor-ID \"+aId+\"not present.\");\n\t\treturn anchor;\n\t}\n\t\n\tpublic boolean containsId(int id){\n\t\treturn entityToAnchorIDs.containsKey(id);\n\t}\n\n\tpublic List<Pair<String, Integer>> getAnchors(int id, double keepFreq) {\n\t\tif (!containsId(id))\n\t\t\tthrow new RuntimeException(\"Anchors for page id=\" + id\n\t\t\t\t\t+ \" not found.\");\n\t\tint[] anchors = entityToAnchorIDs.get(id);\n\t\tint[] freqs = entityToFreqs.get(id);\n\n\t\tint totalFreq = 0;\n\t\tList<Pair<Integer, Integer>> anchorsAndFreq = new Vector<>();\n\t\tfor (int i=0; i<anchors.length; i++){\n\t\t\ttotalFreq += freqs[i];\n\t\t\tanchorsAndFreq.add(new Pair<Integer, Integer>(anchors[i], freqs[i]));\n\t\t}\n\n\t\tCollections.sort(anchorsAndFreq, new SmaphUtils.ComparePairsBySecondElement<Integer, Integer>());\n\n\t\tint gathered = 0;\n\t\tList<Pair<String, Integer>> res = new Vector<Pair<String, Integer>>();\n\t\tfor (int i = anchorsAndFreq.size() - 1; i >= 0; i--)\n\t\t\tif (gathered >= keepFreq * totalFreq)\n\t\t\t\tbreak;\n\t\t\telse {\n\t\t\t\tint aid = anchorsAndFreq.get(i).first;\n\t\t\t\tint freq = anchorsAndFreq.get(i).second;\n\t\t\t\tres.add(new Pair<String, Integer>(idToAnchor(aid), freq));\n\t\t\t\tgathered += freq;\n\t\t\t}\n\t\treturn res;\n\t}\n\n\tpublic List<Pair<String, Integer>> getAnchors(int id) {\n\t\tif (!containsId(id))\n\t\t\tthrow new RuntimeException(\"Anchors for page id=\" + id\n\t\t\t\t\t+ \" not found.\");\n\t\tint[] anchors = entityToAnchorIDs.get(id);\n\t\tint[] freqs = entityToFreqs.get(id);\n\t\t\n\t\tList<Pair<String, Integer>> res = new Vector<Pair<String,Integer>>();\n\t\tfor (int i=0; i<anchors.length; i++)\n\t\t\tres.add(new Pair<String, Integer>(idToAnchor(anchors[i]), freqs[i]));\n\t\treturn res;\n\t}\n\t\n\tpublic int getAnchorGlobalOccurrences(String anchor){\n\t\tInteger aId = anchorToAid.get(anchor);\n\t\tif (aId == null)\n\t\t\tthrow new RuntimeException(\"Anchor \"+anchor+\"not present.\");\n\t\treturn anchorToOccurrences.get(aId);\n\t}\n\t\n\tpublic double getCommonness(String anchor, int entity){\n\t\tif (!anchorToAid.containsKey(anchor))\n\t\t\treturn 0.0;\n\t\treturn ((double)getFrequency(anchor, entity)) / getAnchorGlobalOccurrences(anchor);\n\t}\n\n\tpublic double getCommonness(String anchor, int entity, int occurrences){\n\t\treturn ((double) occurrences) / getAnchorGlobalOccurrences(anchor);\n\t}\n\n\tprivate int getFrequency(String anchor, int entity) {\n\t\tif (!containsId(entity))\n\t\t\tthrow new RuntimeException(\"Anchors for page id=\" + entity\n\t\t\t\t\t+ \" not found.\");\n\t\tif (!anchorToAid.containsKey(anchor))\n\t\t\tthrow new RuntimeException(\"Anchors \"+anchor+\" not present.\");\n\t\tint aid = anchorToAid.get(anchor);\n\t\t\n\t\tint[] anchors = entityToAnchorIDs.get(entity);\n\t\tint[] freqs = entityToFreqs.get(entity);\n\t\t\n\t\tfor (int i=0; i<anchors.length; i++)\n\t\t\tif (anchors[i] == aid)\n\t\t\t\treturn freqs[i];\n\t\treturn 0;\n\t}\n\n\tpublic void dumpJson(String file) throws IOException, JSONException {\n\t\tFileWriter fw = new FileWriter(file);\n\t\tJSONWriter wr = new JSONWriter(fw);\n\t\twr.object();\n\t\tfor (int pageid : entityToAnchorIDs.getKeys()) {\n\t\t\twr.key(Integer.toString(pageid)).array();\n\t\t\tList<Pair<String, Integer>> anchorAndFreqs = getAnchors(pageid);\n\t\t\tfor (Pair<String, Integer> p: anchorAndFreqs)\n\t\t\t\twr.object().key(p.first).value(p.second).endObject();\n\t\t\twr.endArray();\n\t\t}\n\t\twr.endObject();\n\t\tfw.close();\n\t}\n\n\tpublic static void main(String[] args) throws Exception{\n\t\tlogger.info(\"Creating E2A database... \");\n\t\tcreateDB(args.length > 0 ? args[0] : DEFAULT_INPUT);\n\t\tlogger.info(\"Done.\");\n\t}\n}", "public class WikipediaToFreebase {\n\tprivate Map<String, String> map;\n\tprivate Map<String, String> labels;\n\n\tpublic static WikipediaToFreebase open(String file) {\n\t\treturn new WikipediaToFreebase(file);\n\t}\n\n\tprivate WikipediaToFreebase(String file) {\n\t\tDB db = DBMaker.fileDB(file).fileMmapEnable().readOnly().closeOnJvmShutdown().make();\n\t\tmap = db.hashMap(\"index\", Serializer.STRING, Serializer.STRING).createOrOpen();\n\t\tlabels = db.hashMap(\"label\", Serializer.STRING, Serializer.STRING).createOrOpen();\n\t}\n\n\tpublic String getLabel(String wikiid) {\n\t\twikiid = wikiid.replaceAll(\" \", \"_\");\n\t\tString freebase = map.get(wikiid);\n\t\tif (freebase == null)\n\t\t\treturn null;\n\n\t\tString label = labels.get(freebase);\n\t\treturn label;\n\t}\n\n\tpublic boolean hasEntity(String wikilabel) {\n\t\twikilabel = wikilabel.replaceAll(\" \", \"_\");\n\t\treturn map.containsKey(wikilabel);\n\t}\n\n\tpublic String getFreebaseId(String wikilabel) {\n\t\twikilabel = wikilabel.replaceAll(\" \", \"_\");\n\t\tString freebase = map.get(wikilabel);\n\t\treturn freebase;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tWikipediaToFreebase w2f = new WikipediaToFreebase(\"mapdb/freebase.db\");\n\t\tSystem.out.println(w2f.getFreebaseId(\"Diego_Maradona\"));\n\t\tSystem.out.println(w2f.getLabel(\"Diego_Maradona\"));\n\t\tSystem.out.println(w2f.getFreebaseId(\"East Ridge High School (Minnesota)\"));\n\t\tSystem.out.println(w2f.getLabel(\"East Ridge High School (Minnesota)\"));\n\t}\n\n}" ]
import it.unipi.di.acube.batframework.data.Annotation; import it.unipi.di.acube.batframework.utils.Pair; import it.unipi.di.acube.batframework.utils.WikipediaInterface; import it.unipi.di.acube.smaph.QueryInformation; import it.unipi.di.acube.smaph.SmaphUtils; import it.unipi.di.acube.smaph.WATRelatednessComputer; import it.unipi.di.acube.smaph.datasets.wikiAnchors.EntityToAnchors; import it.unipi.di.acube.smaph.datasets.wikitofreebase.WikipediaToFreebase; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Vector; import org.apache.commons.lang3.tuple.Triple;
package it.unipi.di.acube.smaph.learn.featurePacks; public class BindingFeaturePack extends FeaturePack<HashSet<Annotation>> { private static final long serialVersionUID = 1L; private static String[] ftrNames = null; public BindingFeaturePack( HashSet<Annotation> binding, String query, QueryInformation qi, WikipediaInterface wikiApi, WikipediaToFreebase w2f, EntityToAnchors e2a, HashMap<Annotation, HashMap<String, Double>> debugAnnotationFeatures, HashMap<String, Double> debugBindingFeatures){ super(getFeatures(binding, query, qi, wikiApi, w2f, e2a, debugAnnotationFeatures, debugBindingFeatures)); } public BindingFeaturePack() { super(null); } @Override public String[] getFeatureNames() { return getFeatureNamesStatic(); } public static String[] getFeatureNamesStatic() { if (ftrNames == null) { List<String> ftrNamesVect = new Vector<>(); for (String ftrName : AnnotationFeaturePack .getFeatureNamesStatic()) if (ftrName.startsWith("found_")) { ftrNamesVect.add("count_" + ftrName); } else { ftrNamesVect.add("min_" + ftrName); ftrNamesVect.add("max_" + ftrName); ftrNamesVect.add("avg_" + ftrName); } ftrNamesVect.add("min_relatedness"); ftrNamesVect.add("max_relatedness"); ftrNamesVect.add("avg_relatedness"); ftrNamesVect.add("query_tokens"); ftrNamesVect.add("annotation_count"); ftrNamesVect.add("covered_tokens"); ftrNamesVect.add("min_relatedness_mw"); ftrNamesVect.add("max_relatedness_mw"); ftrNamesVect.add("avg_relatedness_mw"); ftrNamesVect.add("segments_lp_sum"); ftrNamesVect.add("segments_lp_avg"); ftrNamesVect.add("webtotal"); ftrNamesVect.add("bolds_number"); ftrNamesVect.add("distinct_bolds"); ftrNamesVect.add("bolds_query_mined_avg"); ftrNames = ftrNamesVect.toArray(new String[] {}); } return ftrNames; } @Override public void checkFeatures(HashMap<String, Double> features) { String[] ftrNames = getFeatureNames(); for (String ftrName : features.keySet()) if (!Arrays.asList(ftrNames).contains(ftrName)) throw new RuntimeException("Feature " + ftrName + " does not exist!"); } /** * Given a list of feature vectors, return a single * feature vector (in hashmap form). This vector will contain the max, * min, and avg of for [0,1] features and the sum for counting features. * * @param allFtrVects * @return a single representation */ private static HashMap<String, Double> collapseFeatures( List<HashMap<String, Double>> allFtrVects) { // count feature presence HashMap<String, Integer> ftrCount = new HashMap<>(); for (HashMap<String, Double> ftrVectToMerge : allFtrVects) for (String ftrName : ftrVectToMerge.keySet()) { if (!ftrCount.containsKey(ftrName)) ftrCount.put(ftrName, 0); ftrCount.put(ftrName, ftrCount.get(ftrName) + 1); } // compute min, max, avg, count HashMap<String, Double> entitySetFeatures = new HashMap<>(); // Initialize sources count features to 0.0 for (String ftrName : new EntityFeaturePack().getFeatureNames()) if (ftrName.startsWith("found_")) { String key = "count_" + ftrName; entitySetFeatures.put(key, 0.0); } for (HashMap<String, Double> ftrVectToMerge : allFtrVects) { for (String ftrName : ftrVectToMerge.keySet()) { if (ftrName.startsWith("found_")) { String key = "count_" + ftrName; entitySetFeatures.put(key, entitySetFeatures.get(key) + ftrVectToMerge.get(ftrName)); } else { if (!entitySetFeatures.containsKey("min_" + ftrName)) entitySetFeatures.put("min_" + ftrName, Double.POSITIVE_INFINITY); if (!entitySetFeatures.containsKey("max_" + ftrName)) entitySetFeatures.put("max_" + ftrName, Double.NEGATIVE_INFINITY); if (!entitySetFeatures.containsKey("avg_" + ftrName)) entitySetFeatures.put("avg_" + ftrName, 0.0); double ftrValue = ftrVectToMerge.get(ftrName); entitySetFeatures.put("min_" + ftrName, Math.min( entitySetFeatures.get("min_" + ftrName), ftrValue)); entitySetFeatures.put("max_" + ftrName, Math.max( entitySetFeatures.get("max_" + ftrName), ftrValue)); entitySetFeatures.put("avg_" + ftrName, entitySetFeatures.get("avg_" + ftrName) + ftrValue / ftrCount.get(ftrName)); } } } return entitySetFeatures; } private static HashMap<String, Double> getFeatures( HashSet<Annotation> binding, String query, QueryInformation qi, WikipediaInterface wikiApi, WikipediaToFreebase w2f, EntityToAnchors e2a, HashMap<Annotation, HashMap<String, Double>> debugAnnotationFeatures, HashMap<String, Double> debugBindingFeatures) { List<HashMap<String, Double>> allAnnotationsFeatures = new Vector<>(); for (Annotation ann : binding) { HashMap<String, Double> annFeatures = AnnotationFeaturePack .getFeaturesStatic(ann, query, qi, wikiApi, w2f, e2a); allAnnotationsFeatures.add(annFeatures); if (debugAnnotationFeatures != null) debugAnnotationFeatures.put(ann, annFeatures); } /* HashSet<Tag> selectedEntities = new HashSet<>(); for (Annotation ann : binding) selectedEntities.add(new Tag(ann.getConcept())); List<HashMap<String, Double>> allEntitiesFeatures = new Vector<>(); for (Tag t : selectedEntities) allEntitiesFeatures.addAll(qi.entityToFtrVects.get(t)); */ HashMap<String, Double> bindingFeatures = collapseFeatures( allAnnotationsFeatures); /*Vector<Double> mutualInfos = new Vector<>(); for (Annotation a : binding) { Tag t = new Tag(a.getConcept()); double minED = 1.0; if (entitiesToBolds.containsKey(t)) for (String bold : entitiesToBolds.get(t)) minED = Math.min(SmaphUtils.getMinEditDist( query.substring(a.getPosition(), a.getPosition() + a.getLength()), bold), minED); mutualInfos.add(mutualInfo); } */ /*Triple<Double, Double, Double> minMaxAvgMI = getMinMaxAvg(mutualInfos); features.put("min_mutual_info", minMaxAvgMI.getLeft()); features.put("avg_mutual_info", minMaxAvgMI.getRight()); features.put("max_mutual_info", minMaxAvgMI.getMiddle());*/ bindingFeatures.put("query_tokens", (double) SmaphUtils.tokenize(query).size()); bindingFeatures.put("annotation_count", (double) binding.size()); int coveredTokens = 0; for (Annotation a: binding) coveredTokens += SmaphUtils.tokenize(query.substring(a.getPosition(), a.getPosition()+a.getLength())).size(); bindingFeatures.put("covered_tokens", (double)coveredTokens/(double) SmaphUtils.tokenize(query).size()); /* Add relatedness among entities (only if there are more than two entities)*/ Vector<Double> relatednessPairsJaccard = new Vector<>(); Vector<Double> relatednessPairsMW = new Vector<>(); for (Annotation a1 : binding) for (Annotation a2 : binding) if (a1.getConcept() != a2.getConcept()){
relatednessPairsJaccard.add(WATRelatednessComputer.getJaccardRelatedness(a1.getConcept(), a2.getConcept()));
2
addradio/mpeg-audio-streams
src/main/java/net/addradio/codec/mpeg/audio/MPEGAudioFrameOutputStream.java
[ "public final class BitRateCodec {\n\n /**\n * decode.\n *\n * @param frame\n * {@link MPEGAudioFrame}\n * @param value\n * {@code int}\n * @return {@link BitRate}\n * @throws MPEGAudioCodecException\n * if bit rate could not be decoded.\n */\n public static final BitRate decode(final MPEGAudioFrame frame, final int value) throws MPEGAudioCodecException {\n if (value > 15) {\n throw new MPEGAudioCodecException(\"bitrate has to be a flag value between 0 and 15 (incl.) but was [\" //$NON-NLS-1$\n + value + \"]\"); //$NON-NLS-1$\n }\n switch (frame.getLayer()) {\n case I:\n switch (value) {\n case 0b0000:\n return BitRate.free;\n case 0b0001:\n return BitRate._32;\n case 0b0010:\n return BitRate._64;\n case 0b0011:\n return BitRate._96;\n case 0b0100:\n return BitRate._128;\n case 0b0101:\n return BitRate._160;\n case 0b0110:\n return BitRate._192;\n case 0b0111:\n return BitRate._224;\n case 0b1000:\n return BitRate._256;\n case 0b1001:\n return BitRate._288;\n case 0b1010:\n return BitRate._320;\n case 0b1011:\n return BitRate._352;\n case 0b1100:\n return BitRate._384;\n case 0b1101:\n return BitRate._416;\n case 0b1110:\n return BitRate._448;\n case 0b1111:\n return BitRate.reserved;\n default:\n break;\n }\n break;\n case II:\n switch (value) {\n case 0b0000:\n return BitRate.free;\n case 0b0001:\n return BitRate._32;\n case 0b0010:\n return BitRate._48;\n case 0b0011:\n return BitRate._56;\n case 0b0100:\n return BitRate._64;\n case 0b0101:\n return BitRate._80;\n case 0b0110:\n return BitRate._96;\n case 0b0111:\n return BitRate._112;\n case 0b1000:\n return BitRate._128;\n case 0b1001:\n return BitRate._160;\n case 0b1010:\n return BitRate._192;\n case 0b1011:\n return BitRate._224;\n case 0b1100:\n return BitRate._256;\n case 0b1101:\n return BitRate._320;\n case 0b1110:\n return BitRate._384;\n case 0b1111:\n return BitRate.reserved;\n default:\n break;\n }\n break;\n case III:\n switch (frame.getVersion()) {\n case MPEG_1:\n switch (value) {\n case 0b0000:\n return BitRate.free;\n case 0b0001:\n return BitRate._32;\n case 0b0010:\n return BitRate._40;\n case 0b0011:\n return BitRate._48;\n case 0b0100:\n return BitRate._56;\n case 0b0101:\n return BitRate._64;\n case 0b0110:\n return BitRate._80;\n case 0b0111:\n return BitRate._96;\n case 0b1000:\n return BitRate._112;\n case 0b1001:\n return BitRate._128;\n case 0b1010:\n return BitRate._160;\n case 0b1011:\n return BitRate._192;\n case 0b1100:\n return BitRate._224;\n case 0b1101:\n return BitRate._256;\n case 0b1110:\n return BitRate._320;\n case 0b1111:\n return BitRate.reserved;\n default:\n break;\n }\n break;\n case MPEG_2_LSF:\n case MPEG_2_5:\n // SEBASTIAN take care of this, table for mpeg2 can be\n // absolutely wrong\n switch (value) {\n case 0b0000:\n return BitRate.free;\n case 0b0001:\n return BitRate._8;\n case 0b0010:\n return BitRate._16;\n case 0b0011:\n return BitRate._24;\n case 0b0100:\n return BitRate._32;\n case 0b0101:\n return BitRate._40;\n case 0b0110:\n return BitRate._48;\n case 0b0111:\n return BitRate._56;\n case 0b1000:\n return BitRate._64;\n case 0b1001:\n return BitRate._80;\n case 0b1010:\n return BitRate._96;\n case 0b1011:\n return BitRate._112;\n case 0b1100:\n return BitRate._128;\n case 0b1101:\n return BitRate._144;\n case 0b1110:\n return BitRate._160;\n case 0b1111:\n return BitRate.reserved;\n default:\n break;\n }\n break;\n case reserved:\n default:\n break;\n }\n break;\n case reserved:\n default:\n break;\n }\n throw new MPEGAudioCodecException(\n \"Could not decode BitRate [valueToBeDecoded: \" + value + \", frameDecodedSoFar: \" + frame + \"].\"); //$NON-NLS-3$ //$NON-NLS-1$//$NON-NLS-2$\n }\n\n /**\n * encode.\n * @param frame {@link MPEGAudioFrame}\n * @return {@code int}\n * @throws MPEGAudioCodecException if model is ill-formed.\n */\n public static int encode(final MPEGAudioFrame frame) throws MPEGAudioCodecException {\n switch (frame.getLayer()) {\n case I:\n switch (frame.getBitRate()) {\n case free:\n return 0b0000;\n case _32:\n return 0b0001;\n case _64:\n return 0b0010;\n case _96:\n return 0b0011;\n case _128:\n return 0b0100;\n case _160:\n return 0b0101;\n case _192:\n return 0b0110;\n case _224:\n return 0b0111;\n case _256:\n return 0b1000;\n case _288:\n return 0b1001;\n case _320:\n return 0b1010;\n case _352:\n return 0b1011;\n case _384:\n return 0b1100;\n case _416:\n return 0b1101;\n case _448:\n return 0b1110;\n case reserved:\n return 0b1111;\n //$CASES-OMITTED$\n default:\n break;\n }\n break;\n case II:\n switch (frame.getBitRate()) {\n case free:\n return 0b0000;\n case _32:\n return 0b0001;\n case _48:\n return 0b0010;\n case _56:\n return 0b0011;\n case _64:\n return 0b0100;\n case _80:\n return 0b0101;\n case _96:\n return 0b0110;\n case _112:\n return 0b0111;\n case _128:\n return 0b1000;\n case _160:\n return 0b1001;\n case _192:\n return 0b1010;\n case _224:\n return 0b1011;\n case _256:\n return 0b1100;\n case _320:\n return 0b1101;\n case _384:\n return 0b1110;\n case reserved:\n return 0b1111;\n //$CASES-OMITTED$\n default:\n break;\n }\n break;\n case III:\n switch (frame.getVersion()) {\n case MPEG_1:\n switch (frame.getBitRate()) {\n case free:\n return 0b0000;\n case _32:\n return 0b0001;\n case _40:\n return 0b0010;\n case _48:\n return 0b0011;\n case _56:\n return 0b0100;\n case _64:\n return 0b0101;\n case _80:\n return 0b0110;\n case _96:\n return 0b0111;\n case _112:\n return 0b1000;\n case _128:\n return 0b1001;\n case _160:\n return 0b1010;\n case _192:\n return 0b1011;\n case _224:\n return 0b1100;\n case _256:\n return 0b1101;\n case _320:\n return 0b1110;\n case reserved:\n return 0b1111;\n //$CASES-OMITTED$\n default:\n break;\n }\n break;\n case MPEG_2_LSF:\n case MPEG_2_5:\n // SEBASTIAN take care of this, table for mpeg2 can be\n // absolutely wrong\n switch (frame.getBitRate()) {\n case free:\n return 0b0000;\n case _8:\n return 0b0001;\n case _16:\n return 0b0010;\n case _24:\n return 0b0011;\n case _32:\n return 0b0100;\n case _40:\n return 0b0101;\n case _48:\n return 0b0110;\n case _56:\n return 0b0111;\n case _64:\n return 0b1000;\n case _80:\n return 0b1001;\n case _96:\n return 0b1010;\n case _112:\n return 0b1011;\n case _128:\n return 0b1100;\n case _144:\n return 0b1101;\n case _160:\n return 0b1110;\n case reserved:\n return 0b1111;\n //$CASES-OMITTED$\n default:\n break;\n }\n break;\n case reserved:\n default:\n break;\n }\n break;\n case reserved:\n default:\n break;\n }\n throw new MPEGAudioCodecException(\"Could not encode frame [frame: \" + frame + \"].\"); //$NON-NLS-1$//$NON-NLS-2$\n }\n\n /**\n * BitRateCodec constructor.\n */\n private BitRateCodec() {\n }\n\n}", "public class MPEGAudioCodecException extends Exception {\n\n /** {@code long} serialVersionUID */\n private static final long serialVersionUID = -886020228709751481L;\n\n /**\n * MPEGAudioCodecException constructor.\n */\n public MPEGAudioCodecException() {\n }\n\n /**\n * MPEGAudioCodecException constructor.\n *\n * @param message\n * {@link String}\n */\n public MPEGAudioCodecException(final String message) {\n super(message);\n }\n\n /**\n * MPEGAudioCodecException constructor.\n *\n * @param message\n * {@link String}\n * @param cause\n * {@link Throwable}\n */\n public MPEGAudioCodecException(final String message, final Throwable cause) {\n super(message, cause);\n }\n\n /**\n * MPEGAudioCodecException constructor.\n *\n * @param message\n * {@link String}\n * @param cause\n * {@link Throwable}\n * @param enableSuppression\n * {@code boolean}\n * @param writableStackTrace\n * {@code boolean}\n */\n public MPEGAudioCodecException(final String message, final Throwable cause, final boolean enableSuppression,\n final boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n\n /**\n * MPEGAudioCodecException constructor.\n *\n * @param cause\n * {@link Throwable}\n */\n public MPEGAudioCodecException(final Throwable cause) {\n super(cause);\n }\n\n}", "public final class ModeExtensionCodec {\r\n\r\n /**\r\n * decode.\r\n * @param frame {@link MPEGAudioFrame}\r\n * @param value {@code int}\r\n * @return {@link ModeExtension}\r\n * @throws MPEGAudioCodecException if value could not be decoded.\r\n */\r\n public static final ModeExtension decode(final MPEGAudioFrame frame, final int value)\r\n throws MPEGAudioCodecException {\r\n switch (frame.getMode()) {\r\n case JointStereo:\r\n switch (frame.getLayer()) {\r\n case I:\r\n case II:\r\n switch (value) {\r\n case 0b00:\r\n return ModeExtension.SubBands4To31;\r\n case 0b01:\r\n return ModeExtension.SubBands8To31;\r\n case 0b10:\r\n return ModeExtension.SubBands12To31;\r\n case 0b11:\r\n return ModeExtension.SubBands16To31;\r\n default:\r\n break;\r\n }\r\n break;\r\n case III:\r\n switch (value) {\r\n case 0b00:\r\n return ModeExtension.IntensityStereo_Off__MSStereo_Off;\r\n case 0b01:\r\n return ModeExtension.IntensityStereo_On__MSStereo_Off;\r\n case 0b10:\r\n return ModeExtension.IntensityStereo_Off__MSStereo_On;\r\n case 0b11:\r\n return ModeExtension.IntensityStereo_On__MSStereo_On;\r\n default:\r\n break;\r\n }\r\n break;\r\n case reserved:\r\n default:\r\n break;\r\n }\r\n throw new MPEGAudioCodecException(\"Could not decode ModeExtension [valueToBeDecoded: \" + value + \"].\"); //$NON-NLS-1$ //$NON-NLS-2$\r\n case DualChannel:\r\n case SingleChannel:\r\n case Stereo:\r\n default:\r\n break;\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * encode.\r\n * @param frame {@link MPEGAudioFrame}\r\n * @return {@code int}\r\n * @throws MPEGAudioCodecException if model is ill-formed.\r\n */\r\n public static int encode(final MPEGAudioFrame frame) throws MPEGAudioCodecException {\r\n switch (frame.getMode()) {\r\n case JointStereo:\r\n switch (frame.getLayer()) {\r\n case I:\r\n case II:\r\n switch (frame.getModeExtension()) {\r\n case SubBands4To31:\r\n return 0b00;\r\n case SubBands8To31:\r\n return 0b01;\r\n case SubBands12To31:\r\n return 0b10;\r\n case SubBands16To31:\r\n return 0b11;\r\n //$CASES-OMITTED$\r\n default:\r\n break;\r\n }\r\n break;\r\n case III:\r\n switch (frame.getModeExtension()) {\r\n case IntensityStereo_Off__MSStereo_Off:\r\n return 0b00;\r\n case IntensityStereo_On__MSStereo_Off:\r\n return 0b01;\r\n case IntensityStereo_Off__MSStereo_On:\r\n return 0b10;\r\n case IntensityStereo_On__MSStereo_On:\r\n return 0b11;\r\n //$CASES-OMITTED$\r\n default:\r\n break;\r\n }\r\n break;\r\n case reserved:\r\n default:\r\n break;\r\n }\r\n throw new MPEGAudioCodecException(\"Could not encode ModeExtension [frame: \" + frame + \"].\"); //$NON-NLS-1$ //$NON-NLS-2$\r\n //$FALL-THROUGH$\r\n case DualChannel:\r\n case SingleChannel:\r\n case Stereo:\r\n default:\r\n break;\r\n }\r\n return 0;\r\n }\r\n\r\n}\r", "public final class SamplingRateCodec {\n\n /**\n * decode.\n *\n * @param frame\n * {@link MPEGAudioFrame}\n * @param value\n * {@code int}\n * @return {@link SamplingRate}\n * @throws MPEGAudioCodecException\n * if value could not be decoded.\n */\n public static final SamplingRate decode(final MPEGAudioFrame frame, final int value)\n throws MPEGAudioCodecException {\n switch (frame.getVersion()) {\n case MPEG_1:\n switch (value) {\n case 0b00:\n return SamplingRate._44100;\n case 0b01:\n return SamplingRate._48000;\n case 0b10:\n return SamplingRate._32000;\n case 0b11:\n return SamplingRate.reserved;\n default:\n break;\n }\n break;\n case MPEG_2_LSF:\n switch (value) {\n case 0b00:\n return SamplingRate._22050;\n case 0b01:\n return SamplingRate._24000;\n case 0b10:\n return SamplingRate._16000;\n case 0b11:\n return SamplingRate.reserved;\n default:\n break;\n }\n break;\n case MPEG_2_5:\n switch (value) {\n case 0b00:\n return SamplingRate._11025;\n case 0b01:\n return SamplingRate._12000;\n case 0b10:\n return SamplingRate._8000;\n case 0b11:\n return SamplingRate.reserved;\n default:\n break;\n }\n break;\n case reserved:\n default:\n break;\n\n }\n throw new MPEGAudioCodecException(\"Could not decode SamplingRate [valueToBeDecoded: \" + value //$NON-NLS-1$\n + \"].\"); //$NON-NLS-1$\n }\n\n /**\n * encode.\n * @param frame {@link MPEGAudioFrame}\n * @return {@code int}\n * @throws MPEGAudioCodecException if model is ill-formed.\n */\n public static int encode(final MPEGAudioFrame frame) throws MPEGAudioCodecException {\n switch (frame.getVersion()) {\n case MPEG_1:\n switch (frame.getSamplingRate()) {\n case _44100:\n return 0b00;\n case _48000:\n return 0b01;\n case _32000:\n return 0b10;\n case reserved:\n return 0b11;\n //$CASES-OMITTED$\n default:\n break;\n }\n break;\n case MPEG_2_LSF:\n switch (frame.getSamplingRate()) {\n case _22050:\n return 0b00;\n case _24000:\n return 0b01;\n case _16000:\n return 0b10;\n case reserved:\n return 0b11;\n //$CASES-OMITTED$\n default:\n break;\n }\n break;\n case MPEG_2_5:\n switch (frame.getSamplingRate()) {\n case _11025:\n return 0b00;\n case _12000:\n return 0b01;\n case _8000:\n return 0b10;\n case reserved:\n return 0b11;\n //$CASES-OMITTED$\n default:\n break;\n }\n break;\n case reserved:\n default:\n break;\n\n }\n throw new MPEGAudioCodecException(\"Could not encode frame [frame: \" + frame //$NON-NLS-1$\n + \"].\"); //$NON-NLS-1$\n }\n\n /**\n * SamplingRateCodec constructor.\n */\n private SamplingRateCodec() {\n }\n\n}", "public interface MPEGAudioContent {\r\n\r\n /**\r\n * isID3Tag.\r\n * @return {@code true} if content is an ID3Tag\r\n */\r\n boolean isID3Tag();\r\n\r\n /**\r\n * isMPEGAudioFrame.\r\n * @return {@code true} if content is a {@link MPEGAudioFrame}\r\n */\r\n boolean isMPEGAudioFrame();\r\n\r\n}", "public class MPEGAudioFrame implements MPEGAudioContent {\r\n\r\n /** {@code int} CRC_SIZE_IN_BYTES. */\r\n public static final int CRC_SIZE_IN_BYTES = 2;\r\n\r\n /** {@code int} HEADER_SIZE_IN_BYTES. */\r\n public static final int HEADER_SIZE_IN_BYTES = 4;\r\n\r\n /** {@code int} SYNC_WORD_PATTERN */\r\n public static final int SYNC_WORD_PATTERN = 0x7FF;\r\n\r\n /**\r\n * calculateAverageBitRate.\r\n * @param durationMillisVal {@code long}\r\n * @param payloadLengthInBytes {@code long}\r\n * @return {@code double}\r\n */\r\n public static final double calculateAverageBitRate(final long durationMillisVal, final long payloadLengthInBytes) {\r\n return (payloadLengthInBytes * 8d * 1000) / durationMillisVal;\r\n }\r\n\r\n /**\r\n * calculateDuration.\r\n * @param bitRateInBps {@code int}\r\n * @param payloadLengthInBytes {@code int}\r\n * @return {@code double}\r\n */\r\n public static final double calculateDuration(final int bitRateInBps, final int payloadLengthInBytes) {\r\n return (payloadLengthInBytes * 8d * 1000) / bitRateInBps;\r\n }\r\n\r\n /** {@code boolean} _private. */\r\n private boolean _private = false;\r\n\r\n /** {@code int[][]} allocations. */\r\n private int[][] allocations;\r\n\r\n /** {@link BitRate} bitRate. */\r\n private BitRate bitRate;\r\n\r\n /** {@code boolean} copyright. */\r\n private boolean copyright = false;\r\n\r\n /** {@code byte[]} crc. */\r\n private byte[] crc;\r\n\r\n /** {@link Emphasis} emphasis. */\r\n private Emphasis emphasis;\r\n\r\n /** {@code boolean} errorProtected. */\r\n private boolean errorProtected = false;\r\n\r\n /** {@code int[][]} globalGain */\r\n private int[][] globalGain;\r\n\r\n /** {@link Layer} layer. */\r\n private Layer layer;\r\n\r\n /** {@code int} mainDataBegin */\r\n private int mainDataBegin;\r\n\r\n /** {@link Mode} mode. */\r\n private Mode mode;\r\n\r\n /** {@link ModeExtension} modeExtension. */\r\n private ModeExtension modeExtension;\r\n\r\n /** {@code boolean} original. */\r\n private boolean original = false;\r\n\r\n /** {@code boolean} padding. */\r\n private boolean padding = false;\r\n\r\n /** {@code byte[]} payload. */\r\n private byte[] payload;\r\n\r\n /** {@code int[][][]} samples. */\r\n private int[][][] samples;\r\n\r\n /** {@link SamplingRate} samplingRate. */\r\n private SamplingRate samplingRate;\r\n\r\n /** {@code int[][]} scaleFactors. */\r\n private int[][] scaleFactors;\r\n\r\n /** {@link Version} version. */\r\n private Version version;\r\n\r\n /**\r\n * calculateDurationMillis.\r\n * @return {@code long} duration of frame in milliseconds or\r\n * {@code -1} if duration could not be calculated due to decoding issues..\r\n */\r\n public long calculateDurationMillis() {\r\n final int frameLength = getFrameLength();\r\n if (frameLength < 0) {\r\n return -1;\r\n }\r\n return Math.round(calculateDuration(getBitRate().getValueInBps(), frameLength));\r\n }\r\n\r\n /**\r\n * equals.\r\n * @see java.lang.Object#equals(java.lang.Object)\r\n * @param obj {@link Object}\r\n * @return {@code boolean}\r\n */\r\n @Override\r\n public boolean equals(final Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (obj == null) {\r\n return false;\r\n }\r\n if (!(obj instanceof MPEGAudioFrame)) {\r\n return false;\r\n }\r\n final MPEGAudioFrame other = (MPEGAudioFrame) obj;\r\n if (this._private != other._private) {\r\n return false;\r\n }\r\n if (this.bitRate != other.bitRate) {\r\n return false;\r\n }\r\n if (this.copyright != other.copyright) {\r\n return false;\r\n }\r\n if (!Arrays.equals(this.crc, other.crc)) {\r\n return false;\r\n }\r\n if (this.emphasis != other.emphasis) {\r\n return false;\r\n }\r\n if (this.errorProtected != other.errorProtected) {\r\n return false;\r\n }\r\n if (!Arrays.deepEquals(this.globalGain, other.globalGain)) {\r\n return false;\r\n }\r\n if (this.layer != other.layer) {\r\n return false;\r\n }\r\n if (this.mode != other.mode) {\r\n return false;\r\n }\r\n if (this.modeExtension != other.modeExtension) {\r\n return false;\r\n }\r\n if (this.original != other.original) {\r\n return false;\r\n }\r\n if (this.padding != other.padding) {\r\n return false;\r\n }\r\n if (this.samplingRate != other.samplingRate) {\r\n return false;\r\n }\r\n if (this.version != other.version) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * getAllocations.\r\n * @return {@code int[][]} the allocations.\r\n */\r\n public int[][] getAllocations() {\r\n return this.allocations;\r\n }\r\n\r\n /**\r\n * getBitrate.\r\n * @return {@link BitRate} the bitRate.\r\n */\r\n public BitRate getBitRate() {\r\n return this.bitRate;\r\n }\r\n\r\n /**\r\n * getCrc.\r\n * @return {@code byte[]} the crc.\r\n */\r\n public byte[] getCrc() {\r\n return this.crc;\r\n }\r\n\r\n /**\r\n * getEmphasis.\r\n * @return {@link Emphasis} the emphasis.\r\n */\r\n public Emphasis getEmphasis() {\r\n return this.emphasis;\r\n }\r\n\r\n /**\r\n * getFrameLength.\r\n * @return {@code int} the frame length in bytes incl. header and crc or\r\n * {@code -1} if length of frame is not available (due to decoding issues.).\r\n */\r\n public int getFrameLength() {\r\n if (getPayload() == null) {\r\n return -1;\r\n }\r\n return getPayload().length + MPEGAudioFrame.HEADER_SIZE_IN_BYTES\r\n + (isErrorProtected() ? MPEGAudioFrame.CRC_SIZE_IN_BYTES : 0);\r\n }\r\n\r\n /**\r\n * @return the {@code int[][]} globalGain\r\n */\r\n public int[][] getGlobalGain() {\r\n return this.globalGain;\r\n }\r\n\r\n /**\r\n * getLayer.\r\n * @return {@link Layer} the layer.\r\n */\r\n public Layer getLayer() {\r\n return this.layer;\r\n }\r\n\r\n /**\r\n * @return the {@code int} mainDataBegin\r\n */\r\n public int getMainDataBegin() {\r\n return this.mainDataBegin;\r\n }\r\n\r\n /**\r\n * getChannelMode.\r\n * @return {@link Mode} the mode.\r\n */\r\n public Mode getMode() {\r\n return this.mode;\r\n }\r\n\r\n /**\r\n * getModeExtension.\r\n * @return {@link ModeExtension} the modeExtension.\r\n */\r\n public ModeExtension getModeExtension() {\r\n return this.modeExtension;\r\n }\r\n\r\n /**\r\n * @return the payload\r\n */\r\n public byte[] getPayload() {\r\n return this.payload;\r\n }\r\n\r\n /**\r\n * getSamples.\r\n * @return <code>int[][][]</code> the samples.\r\n */\r\n public int[][][] getSamples() {\r\n return this.samples;\r\n }\r\n\r\n /**\r\n * getSamplingrate.\r\n * @return {@link SamplingRate} the samplingRate.\r\n */\r\n public SamplingRate getSamplingRate() {\r\n return this.samplingRate;\r\n }\r\n\r\n /**\r\n * getScaleFactors.\r\n * @return {@code int[][]} the scaleFactors.\r\n */\r\n public int[][] getScaleFactors() {\r\n return this.scaleFactors;\r\n }\r\n\r\n /**\r\n * getVersion.\r\n * @return {@link Version} the version.\r\n */\r\n public Version getVersion() {\r\n return this.version;\r\n }\r\n\r\n /**\r\n * hashCode.\r\n * @see java.lang.Object#hashCode()\r\n * @return {@code int}\r\n */\r\n @Override\r\n public int hashCode() {\r\n final int prime = 31;\r\n int result = 1;\r\n result = (prime * result) + (this._private ? 1231 : 1237);\r\n result = (prime * result) + ((this.bitRate == null) ? 0 : this.bitRate.hashCode());\r\n result = (prime * result) + (this.copyright ? 1231 : 1237);\r\n result = (prime * result) + Arrays.hashCode(this.crc);\r\n result = (prime * result) + ((this.emphasis == null) ? 0 : this.emphasis.hashCode());\r\n result = (prime * result) + (this.errorProtected ? 1231 : 1237);\r\n result = (prime * result) + Arrays.deepHashCode(this.globalGain);\r\n result = (prime * result) + ((this.layer == null) ? 0 : this.layer.hashCode());\r\n result = (prime * result) + ((this.mode == null) ? 0 : this.mode.hashCode());\r\n result = (prime * result) + ((this.modeExtension == null) ? 0 : this.modeExtension.hashCode());\r\n result = (prime * result) + (this.original ? 1231 : 1237);\r\n result = (prime * result) + (this.padding ? 1231 : 1237);\r\n result = (prime * result) + ((this.samplingRate == null) ? 0 : this.samplingRate.hashCode());\r\n result = (prime * result) + ((this.version == null) ? 0 : this.version.hashCode());\r\n return result;\r\n }\r\n\r\n /**\r\n * isCopyright.\r\n * @return {@code boolean} the copyright.\r\n */\r\n public boolean isCopyright() {\r\n return this.copyright;\r\n }\r\n\r\n /**\r\n * isErrorProtected.\r\n * @return {@code boolean} the errorProtected.\r\n */\r\n public boolean isErrorProtected() {\r\n return this.errorProtected;\r\n }\r\n\r\n /**\r\n * isID3Tag.\r\n * @see net.addradio.codec.mpeg.audio.model.MPEGAudioContent#isID3Tag()\r\n * @return {@code boolean false} always.\r\n */\r\n @Override\r\n public boolean isID3Tag() {\r\n return false;\r\n }\r\n\r\n /**\r\n * isMPEGAudioFrame.\r\n * @see net.addradio.codec.mpeg.audio.model.MPEGAudioContent#isMPEGAudioFrame()\r\n * @return {@code boolean true} always.\r\n */\r\n @Override\r\n public boolean isMPEGAudioFrame() {\r\n return true;\r\n }\r\n\r\n /**\r\n * isOriginal.\r\n * @return {@code boolean} the original.\r\n */\r\n public boolean isOriginal() {\r\n return this.original;\r\n }\r\n\r\n /**\r\n * isPadding.\r\n * @return {@code boolean} the padding.\r\n */\r\n public boolean isPadding() {\r\n return this.padding;\r\n }\r\n\r\n /**\r\n * isPrivate.\r\n * @return {@code boolean} the _private.\r\n */\r\n public boolean isPrivate() {\r\n return this._private;\r\n }\r\n\r\n /**\r\n * setAllocations.\r\n * @param allocationsRef {@code int[][]} the allocations to set.\r\n */\r\n public void setAllocations(final int[][] allocationsRef) {\r\n this.allocations = allocationsRef;\r\n }\r\n\r\n /**\r\n * setBitRate.\r\n * @param bitrateRef\r\n * {@link BitRate} the bitRate to set.\r\n */\r\n public void setBitRate(final BitRate bitrateRef) {\r\n this.bitRate = bitrateRef;\r\n }\r\n\r\n /**\r\n * setCopyright.\r\n * @param copyrightVal\r\n * {@code boolean} the copyright to set.\r\n */\r\n public void setCopyright(final boolean copyrightVal) {\r\n this.copyright = copyrightVal;\r\n }\r\n\r\n /**\r\n * setCrc.\r\n * @param crcRef {@code byte[]} the crc to set.\r\n */\r\n public void setCrc(final byte[] crcRef) {\r\n this.crc = crcRef;\r\n }\r\n\r\n /**\r\n * setEmphasis.\r\n * @param emphasisRef\r\n * {@link Emphasis} the emphasis to set.\r\n */\r\n public void setEmphasis(final Emphasis emphasisRef) {\r\n this.emphasis = emphasisRef;\r\n }\r\n\r\n /**\r\n * setErrorProtected.\r\n * @param errorProtectedVal\r\n * {@code boolean} the errorProtected to set.\r\n */\r\n public void setErrorProtected(final boolean errorProtectedVal) {\r\n this.errorProtected = errorProtectedVal;\r\n }\r\n\r\n /**\r\n * @param globalGainRef {@code int[][]} the globalGain to set\r\n */\r\n public void setGlobalGain(final int[][] globalGainRef) {\r\n this.globalGain = globalGainRef;\r\n }\r\n\r\n /**\r\n * setLayer.\r\n * @param layerRef\r\n * {@link Layer} the layer to set.\r\n */\r\n public void setLayer(final Layer layerRef) {\r\n this.layer = layerRef;\r\n }\r\n\r\n /**\r\n * @param mainDataBeginVal {@code int} the mainDataBegin to set\r\n */\r\n public void setMainDataBegin(final int mainDataBeginVal) {\r\n this.mainDataBegin = mainDataBeginVal;\r\n }\r\n\r\n /**\r\n * setChannelMode.\r\n * @param channelModeRef\r\n * {@link Mode} the mode to set.\r\n */\r\n public void setMode(final Mode channelModeRef) {\r\n this.mode = channelModeRef;\r\n }\r\n\r\n /**\r\n * setModeExtension.\r\n * @param modeExtensionRef\r\n * {@link ModeExtension} the modeExtension to set.\r\n */\r\n public void setModeExtension(final ModeExtension modeExtensionRef) {\r\n this.modeExtension = modeExtensionRef;\r\n }\r\n\r\n /**\r\n * setOriginal.\r\n * @param originalVal\r\n * {@code boolean} the original to set.\r\n */\r\n public void setOriginal(final boolean originalVal) {\r\n this.original = originalVal;\r\n }\r\n\r\n /**\r\n * setPadding.\r\n * @param paddingVal\r\n * {@code boolean} the padding to set.\r\n */\r\n public void setPadding(final boolean paddingVal) {\r\n this.padding = paddingVal;\r\n }\r\n\r\n /**\r\n * setPayload.\r\n * @param payloadRef {@code byte[]} the payload to set.\r\n */\r\n public void setPayload(final byte[] payloadRef) {\r\n this.payload = payloadRef;\r\n }\r\n\r\n /**\r\n * setPrivate.\r\n * @param privateVal\r\n * {@code boolean} the _private to set.\r\n */\r\n public void setPrivate(final boolean privateVal) {\r\n this._private = privateVal;\r\n }\r\n\r\n /**\r\n * setSamples.\r\n * @param samplesRef {@code int[][]} the samples to set.\r\n */\r\n public void setSamples(final int[][][] samplesRef) {\r\n this.samples = samplesRef;\r\n }\r\n\r\n /**\r\n * setSamplingRate.\r\n * @param samplingRateRef\r\n * {@link SamplingRate} the samplingRate to set.\r\n */\r\n public void setSamplingRate(final SamplingRate samplingRateRef) {\r\n this.samplingRate = samplingRateRef;\r\n }\r\n\r\n /**\r\n * setScalefactors.\r\n * @param scalefactorsRef {@code int[][]} the scaleFactors to set.\r\n */\r\n public void setScalefactors(final int[][] scalefactorsRef) {\r\n this.scaleFactors = scalefactorsRef;\r\n }\r\n\r\n /**\r\n * setVersion.\r\n * @param versionRef\r\n * {@link Version} the version to set.\r\n */\r\n public void setVersion(final Version versionRef) {\r\n this.version = versionRef;\r\n }\r\n\r\n /**\r\n * toString.\r\n * @return {@link String}\r\n * @see java.lang.Object#toString()\r\n */\r\n @Override\r\n public String toString() {\r\n final StringBuilder builder = new StringBuilder();\r\n builder.append(MPEGAudioFrame.class.getSimpleName() + \" [version=\"); //$NON-NLS-1$\r\n builder.append(this.version);\r\n builder.append(\", layer=\"); //$NON-NLS-1$\r\n builder.append(this.layer);\r\n builder.append(\", errorProtected=\"); //$NON-NLS-1$\r\n builder.append(this.errorProtected);\r\n builder.append(\", bitRate=\"); //$NON-NLS-1$\r\n builder.append(this.bitRate);\r\n builder.append(\", samplingRate=\"); //$NON-NLS-1$\r\n builder.append(this.samplingRate);\r\n builder.append(\", padding=\"); //$NON-NLS-1$\r\n builder.append(this.padding);\r\n builder.append(\", _private=\"); //$NON-NLS-1$\r\n builder.append(this._private);\r\n builder.append(\", mode=\"); //$NON-NLS-1$\r\n builder.append(this.mode);\r\n builder.append(\", modeExtension=\"); //$NON-NLS-1$\r\n builder.append(this.modeExtension);\r\n builder.append(\", copyright=\"); //$NON-NLS-1$\r\n builder.append(this.copyright);\r\n builder.append(\", original=\"); //$NON-NLS-1$\r\n builder.append(this.original);\r\n builder.append(\", emphasis=\"); //$NON-NLS-1$\r\n builder.append(this.emphasis);\r\n builder.append(\", globalGain=\"); //$NON-NLS-1$\r\n builder.append(Arrays.deepToString(this.globalGain));\r\n builder.append(\"]\"); //$NON-NLS-1$\r\n return builder.toString();\r\n }\r\n\r\n}\r", "public class BitInputStream extends InputStream {\n\n /** {@code int} MAX_OFFSET */\n static final int MAX_OFFSET = 7;\n\n /** {@code int} bitInByteOffset */\n private int bitInByteOffset = -1;\n\n /** {@link InputStream} inner */\n private InputStream inner;\n\n /** {@code int} lastByte */\n private int lastByte;\n\n /** {@link Object} lock */\n private final Object lock = new Object();\n\n /**\n * BitInputStream constructor.\n * @param innerRef\n * {@link InputStream}\n */\n public BitInputStream(final InputStream innerRef) {\n setInner(innerRef);\n }\n\n /**\n * available.\n * @see java.io.InputStream#available()\n * @return {@code int}\n * @throws IOException\n * in case of bad IO situations.\n */\n @Override\n public int available() throws IOException {\n return this.inner.available();\n }\n\n /**\n * close.\n * @see java.io.InputStream#close()\n * @throws IOException\n * in case of bad IO situations.\n */\n @Override\n public void close() throws IOException {\n this.lastByte = 0;\n this.bitInByteOffset = -1;\n this.inner.close();\n }\n\n /**\n * getInner.\n * @return {@link InputStream} the inner.\n */\n public InputStream getInner() {\n return this.inner;\n }\n\n /**\n * innerRead.\n * @return {@code int} read from inner stream.\n * @throws IOException due to IO problems or if end of stream has been reached.\n */\n private int innerRead() throws IOException {\n final int read = this.inner.read();\n // System.out.println(\"read byte: 0x\" + Integer.toHexString(read));\n if (read < 0) {\n throw new EndOfStreamException();\n }\n return read;\n }\n\n /**\n * isByteAligned.\n * @return {@code boolean true} if read pointer is aligned to byte boundaries.\n */\n public boolean isByteAligned() {\n return this.bitInByteOffset < 0;\n }\n\n /**\n * isNextBitOne. Reads just one bit and checks whether it is 0b1 or not.\n *\n * @return {@code boolean true} only if the next bit is 0b1.\n * @throws IOException due to IO problems.\n */\n public boolean isNextBitOne() throws IOException {\n return readBit() == 1;\n }\n\n /**\n * isNextBitOne. Reads just one bit and checks whether it is 0b0 or not.\n *\n * @return {@code boolean true} only if the next bit is 0b0.\n * @throws IOException due to IO problems.\n */\n public boolean isNextBitZero() throws IOException {\n return readBit() == 0;\n }\n\n /**\n * read.\n * @see java.io.InputStream#read()\n * @return {@code int}\n * @throws IOException\n * in case of bad IO situations.\n */\n @Override\n public int read() throws IOException {\n synchronized (this.lock) {\n if (isByteAligned()) {\n return innerRead();\n }\n }\n return readBits(8);\n }\n\n /**\n * readBit.\n * @return {@code int} the read bit.\n * @throws IOException\n * in case of bad IO situations.\n */\n public int readBit() throws IOException {\n synchronized (this.lock) {\n if (isByteAligned()) {\n this.bitInByteOffset = BitInputStream.MAX_OFFSET;\n this.lastByte = innerRead();\n }\n final int returnVal = (this.lastByte & (0x1 << this.bitInByteOffset)) >> this.bitInByteOffset;\n this.bitInByteOffset--;\n // System.out.println(\"read bit: 0b\" + Integer.toBinaryString(returnVal));\n return returnVal;\n }\n }\n\n /**\n * readBits.\n * @param numberOfBitsToRead\n * <code>int</code>\n * @return <code>int</code> the value of the read bits;\n * @throws IOException\n * in case of bad IO situations.\n */\n public int readBits(final int numberOfBitsToRead) throws IOException {\n int returnVal = 0;\n for (int offset = numberOfBitsToRead - 1; offset > -1; offset--) {\n returnVal |= readBit() << offset;\n }\n // System.out.println(\"read bits: 0b\" + Integer.toBinaryString(returnVal));\n return returnVal;\n }\n\n /**\n * readFully.\n * @param toFill\n * <code>byte[]</code>\n * @throws IOException\n * in case of bad IO situations.\n */\n public void readFully(final byte[] toFill) throws IOException {\n for (int i = 0; i < toFill.length; i++) {\n toFill[i] = (byte) read();\n }\n }\n\n /**\n * readInt.\n * @param numOfBytes {@code int} to be read.\n * @return {@code int}\n * @throws IOException due to IO problems.\n */\n public int readInt(final int numOfBytes) throws IOException {\n // SEBASTIAN check for max bytes\n int value = 0;\n for (int i = numOfBytes - 1; i > -1; i--) {\n value |= (read() << (i * 8));\n }\n return value;\n }\n\n /**\n * setInner.\n * @param innerRef\n * {@link InputStream} the inner to set.\n */\n public void setInner(final InputStream innerRef) {\n this.inner = innerRef;\n }\n\n /**\n * skipBit.\n * @throws IOException due to bad IO situations.\n */\n public void skipBit() throws IOException {\n skipBits(1);\n }\n\n // @Override\n // public long skip(long n) throws IOException {\n // // TODO Auto-generated method stub\n // return super.skip(n);\n // }\n\n /**\n * skipBits.\n * @param numberOfBitsToSkip {@code int}\n * @throws IOException in case of bad IO situations.\n */\n public void skipBits(final int numberOfBitsToSkip) throws IOException {\n // SEBASTIAN implement more efficiently\n readBits(numberOfBitsToSkip);\n }\n\n}", "public class BitOutputStream extends OutputStream {\n\n /** {@code int} bitInByteOffset */\n private int bitInByteOffset = BitInputStream.MAX_OFFSET;\n\n /** {@code int} currentByte */\n private int currentByte;\n\n /** {@link OutputStream} inner */\n private OutputStream inner;\n\n /** {@link Object} lock */\n private final Object lock = new Object();\n\n /**\n * BitOutputStream constructor.\n *\n * @param innerRef\n * {@link OutputStream}\n */\n public BitOutputStream(final OutputStream innerRef) {\n setInner(innerRef);\n }\n\n /**\n * close.\n *\n * @see java.io.OutputStream#close()\n * @throws IOException\n * in case of bad IO situations.\n */\n @Override\n public void close() throws IOException {\n this.inner.close();\n }\n\n /**\n * flush.\n *\n * @see java.io.OutputStream#flush()\n * @throws IOException\n * in case of bad IO situations.\n */\n @Override\n public void flush() throws IOException {\n this.inner.flush();\n }\n\n /**\n * getInner.\n *\n * @return {@link OutputStream} the inner.\n */\n public OutputStream getInner() {\n return this.inner;\n }\n\n /**\n * setInner.\n *\n * @param innerRef\n * {@link OutputStream} the inner to set.\n */\n public void setInner(final OutputStream innerRef) {\n this.inner = innerRef;\n }\n\n /**\n * write.\n *\n * @see java.io.OutputStream#write(int)\n * @param b\n * {@code int}\n * @throws IOException\n * in case of bad IO situations.\n */\n @Override\n public void write(final int b) throws IOException {\n synchronized (this.lock) {\n if (this.bitInByteOffset == BitInputStream.MAX_OFFSET) {\n this.inner.write(b);\n } else {\n writeBits(b, 8);\n }\n }\n }\n\n /**\n * writeBit.\n *\n * @param i\n * {@code int}\n * @throws IOException\n * in case of bad IO situations.\n */\n public void writeBit(final int i) throws IOException {\n synchronized (this.lock) {\n this.currentByte |= i << this.bitInByteOffset;\n this.bitInByteOffset--;\n if (this.bitInByteOffset < 0) {\n this.inner.write(this.currentByte);\n this.currentByte = 0;\n this.bitInByteOffset = BitInputStream.MAX_OFFSET;\n }\n }\n }\n\n /**\n * writeBits.\n *\n * @param i\n * {@code int}\n * @param numberOfBitsToWrite\n * {@code int}\n * @throws IOException\n * in case of bad IO situations.\n */\n public void writeBits(final int i, final int numberOfBitsToWrite) throws IOException {\n for (int offset = numberOfBitsToWrite - 1; offset > -1; offset--) {\n writeBit(((i & (0x1 << offset)) >> offset));\n }\n }\n\n}", "public class BitStreamDecorator extends OutputStream {\n\n /** {@link BitInputStream} inBIS */\n private final BitInputStream inBIS;\n\n /** {@link BitOutputStream} outBOS */\n private final BitOutputStream outBOS;\n\n /**\n * BitStreamDecorator constructor.\n * @param inBISRef {@link BitInputStream}\n * @param outBOSRef {@link BitOutputStream}\n */\n public BitStreamDecorator(final BitInputStream inBISRef, final BitOutputStream outBOSRef) {\n this.inBIS = inBISRef;\n this.outBOS = outBOSRef;\n }\n\n /**\n * skipBit.\n * @throws IOException due to IO problems.\n */\n public void skipBit() throws IOException {\n this.outBOS.writeBit(this.inBIS.readBit());\n }\n\n /**\n * skipBits.\n * @param numOfBitsToSkip {@code int}\n * @throws IOException due to IO problems.\n */\n public void skipBits(final int numOfBitsToSkip) throws IOException {\n this.outBOS.writeBits(this.inBIS.readBits(numOfBitsToSkip), numOfBitsToSkip);\n }\n\n /**\n * skipBytes.\n * @param i {@code int}\n * @throws IOException due to IO problems.\n */\n public void skipBytes(final int i) throws IOException {\n // SEBASTIAN improve\n for (int j = i; j > 0; j--) {\n this.outBOS.write(this.inBIS.read());\n }\n }\n\n /**\n * @param b {@code byte[]}\n * @throws IOException due to IO problems.\n * @see java.io.OutputStream#write(byte[])\n */\n @Override\n public void write(final byte[] b) throws IOException {\n this.outBOS.write(b);\n // SEBASTIAN improve by use of skip()\n this.inBIS.skipBits(b.length * 8);\n }\n\n /**\n * @param b {@code byte[]}\n * @param off {@link InternalError}\n * @param len {@code int}\n * @throws IOException due to IO problems.\n * @see java.io.OutputStream#write(byte[], int, int)\n */\n @Override\n public void write(final byte[] b, final int off, final int len) throws IOException {\n this.outBOS.write(b, off, len);\n // SEBASTIAN improve by use of skip()\n this.inBIS.skipBits(len * 8);\n }\n\n /**\n * @param b {@link InternalError}\n * @throws IOException due to IO problems.\n * @see net.addradio.streams.BitOutputStream#write(int)\n */\n @Override\n public void write(final int b) throws IOException {\n this.outBOS.write(b);\n // SEBASTIAN improve by use of skip()\n this.inBIS.skipBits(8);\n }\n\n /**\n * @param i {@code int}\n * @throws IOException due to IO problems.\n * @see net.addradio.streams.BitOutputStream#writeBit(int)\n */\n public void writeBit(final int i) throws IOException {\n this.outBOS.writeBit(i);\n this.inBIS.skipBit();\n }\n\n /**\n * @param i {@code int}\n * @param numberOfBitsToWrite {@code int}\n * @throws IOException due to IO problems.\n * @see net.addradio.streams.BitOutputStream#writeBits(int, int)\n */\n public void writeBits(final int i, final int numberOfBitsToWrite) throws IOException {\n this.outBOS.writeBits(i, numberOfBitsToWrite);\n this.inBIS.skipBits(numberOfBitsToWrite);\n }\n\n}" ]
import net.addradio.streams.BitInputStream; import net.addradio.streams.BitOutputStream; import net.addradio.streams.BitStreamDecorator; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.addradio.codec.mpeg.audio.codecs.BitRateCodec; import net.addradio.codec.mpeg.audio.codecs.MPEGAudioCodecException; import net.addradio.codec.mpeg.audio.codecs.ModeExtensionCodec; import net.addradio.codec.mpeg.audio.codecs.SamplingRateCodec; import net.addradio.codec.mpeg.audio.model.MPEGAudioContent; import net.addradio.codec.mpeg.audio.model.MPEGAudioFrame;
/** * Class: MPEGAudioFrameOutputStream<br/> * <br/> * Created: 20.10.2017<br/> * Filename: MPEGAudioFrameOutputStream.java<br/> * Version: $Revision: $<br/> * <br/> * last modified on $Date: $<br/> * by $Author: $<br/> * <br/> * @author <a href="mailto:sebastian.weiss@nacamar.de">Sebastian A. Weiss, nacamar GmbH</a> * @version $Author: $ -- $Revision: $ -- $Date: $ * <br/> * (c) Sebastian A. Weiss, nacamar GmbH 2012 - All rights reserved. */ package net.addradio.codec.mpeg.audio; /** * MPEGAudioFrameOutputStream */ public class MPEGAudioFrameOutputStream extends BitOutputStream { /** {@link Logger} LOG. */ @SuppressWarnings("unused") private final static Logger LOG = LoggerFactory.getLogger(MPEGAudioFrameOutputStream.class); /** {@code long} durationSoFar. Overall duration of encoded frames so far in milliseconds. */ private long durationSoFar; /** * MPEGAudioFrameOutputStream constructor. * * @param innerRef * {@link OutputStream} */ public MPEGAudioFrameOutputStream(final OutputStream innerRef) { super(innerRef); this.durationSoFar = 0; } /** * @return the {@code long} durationSoFar. Overall duration of encoded frames so far in milliseconds. */ public long getDurationSoFar() { return this.durationSoFar; } /** * writeFrame. * @param frame {@link MPEGAudioContent} * @return {@code int} number of bytes written. * @throws IOException due to IO problems. * @throws MPEGAudioCodecException if encoding encountered a bad model state. */
public int writeFrame(final MPEGAudioContent frame) throws IOException, MPEGAudioCodecException {
1
xedin/sasi
src/java/org/apache/cassandra/db/index/sasi/memory/IndexMemtable.java
[ "public class SSTableAttachedSecondaryIndex extends PerRowSecondaryIndex implements INotificationConsumer\n{\n private static final Logger logger = LoggerFactory.getLogger(SSTableAttachedSecondaryIndex.class);\n\n private IndexMetrics metrics;\n\n private final ConcurrentMap<ByteBuffer, ColumnIndex> indexedColumns;\n private final AtomicReference<IndexMemtable> globalMemtable = new AtomicReference<>(new IndexMemtable(this));\n\n private AbstractType<?> keyValidator;\n private boolean isInitialized;\n\n public SSTableAttachedSecondaryIndex()\n {\n indexedColumns = new NonBlockingHashMap<>();\n }\n\n public void init()\n {\n if (!(StorageService.getPartitioner() instanceof Murmur3Partitioner))\n throw new UnsupportedOperationException(\"SASI supported only with Murmur3Partitioner.\");\n\n isInitialized = true;\n\n metrics = new IndexMetrics(baseCfs);\n\n // init() is called by SIM only on the instance that it will keep around, but will call addColumnDef on any instance\n // that it happens to create (and subsequently/immediately throw away)\n track(columnDefs);\n\n baseCfs.getDataTracker().subscribe(this);\n }\n\n @VisibleForTesting\n public void addColumnDef(ColumnDefinition columnDef)\n {\n super.addColumnDef(columnDef);\n track(Collections.singleton(columnDef));\n }\n\n private void track(Set<ColumnDefinition> columns)\n {\n // if SI hasn't been initialized that means that this instance\n // was created for validation purposes only, so we don't have do anything here.\n // And only reason baseCfs would be null is if coming through the CFMetaData.validate() path, which only\n // checks that the SI 'looks' legit, but then throws away any created instances - fml, this 2I api sux\n if (!isInitialized || baseCfs == null)\n return;\n\n if (keyValidator == null)\n keyValidator = baseCfs.metadata.getKeyValidator();\n\n Set<SSTableReader> sstables = baseCfs.getDataTracker().getSSTables();\n NavigableMap<SSTableReader, Map<ByteBuffer, ColumnIndex>> toRebuild = new TreeMap<>(new Comparator<SSTableReader>()\n {\n @Override\n public int compare(SSTableReader a, SSTableReader b)\n {\n return Integer.compare(a.descriptor.generation, b.descriptor.generation);\n }\n });\n\n for (ColumnDefinition column : columns)\n {\n ColumnIndex index = indexedColumns.get(column.name);\n if (index == null)\n {\n ColumnIndex newIndex = new ColumnIndex(keyValidator, column, getComparator(column));\n index = indexedColumns.putIfAbsent(column.name, newIndex);\n\n if (index != null)\n continue;\n\n // on restart, sstables are loaded into DataTracker before 2I are hooked up (and init() invoked),\n // so we need to explicitly load sstables per index.\n for (SSTableReader sstable : newIndex.init(sstables))\n {\n Map<ByteBuffer, ColumnIndex> perSSTable = toRebuild.get(sstable);\n if (perSSTable == null)\n toRebuild.put(sstable, (perSSTable = new HashMap<>()));\n\n perSSTable.put(column.name, newIndex);\n }\n }\n }\n\n // schedule rebuild of the missing indexes. Property affects both existing and newly (re-)created\n // indexes since SecondaryIndex API makes no distinction between them.\n if (Boolean.parseBoolean(System.getProperty(\"cassandra.sasi.rebuild_on_start\", \"true\")))\n CompactionManager.instance.submitIndexBuild(new IndexBuilder(toRebuild));\n }\n\n public AbstractType<?> getKeyValidator()\n {\n return keyValidator;\n }\n\n public AbstractType<?> getDefaultValidator()\n {\n return baseCfs.metadata.getDefaultValidator();\n }\n\n public AbstractType<?> getComparator(ColumnDefinition column)\n {\n return baseCfs.metadata.getColumnDefinitionComparator(column);\n }\n\n public Map<ByteBuffer, ColumnIndex> getIndexes()\n {\n return indexedColumns;\n }\n\n public ColumnIndex getIndex(ByteBuffer columnName)\n {\n return indexedColumns.get(columnName);\n }\n\n private void updateView(Collection<SSTableReader> toRemove, Collection<SSTableReader> toAdd, Collection<ColumnDefinition> columns)\n {\n for (ColumnDefinition column : columns)\n {\n ColumnIndex columnIndex = indexedColumns.get(column.name);\n if (columnIndex == null)\n {\n track(Collections.singleton(column));\n continue;\n }\n\n columnIndex.update(toRemove, toAdd);\n }\n }\n\n public boolean isIndexBuilt(ByteBuffer columnName)\n {\n return true;\n }\n\n public void validateOptions() throws ConfigurationException\n {\n for (ColumnIndex index : indexedColumns.values())\n index.validate();\n }\n\n public String getIndexName()\n {\n return \"RowLevel_SASI_\" + baseCfs.getColumnFamilyName();\n }\n\n public ColumnFamilyStore getIndexCfs()\n {\n return null;\n }\n\n public long getLiveSize()\n {\n return globalMemtable.get().estimateSize();\n }\n\n public void reload()\n {\n invalidateMemtable();\n }\n\n public void index(ByteBuffer key, ColumnFamily cf)\n {\n // avoid adding already expired or deleted columns to the index\n if (cf == null || cf.isMarkedForDelete())\n return;\n\n globalMemtable.get().index(key, cf.iterator());\n }\n\n /**\n * parent class to eliminate the index rebuild\n *\n * @return a future that does and blocks on nothing\n */\n public Future<?> buildIndexAsync()\n {\n return Futures.immediateCheckedFuture(null);\n }\n\n @Override\n public void buildIndexes(Collection<SSTableReader> sstablesToRebuild, Set<String> indexNames)\n {\n NavigableMap<SSTableReader, Map<ByteBuffer, ColumnIndex>> sstables = new TreeMap<>(new Comparator<SSTableReader>()\n {\n @Override\n public int compare(SSTableReader a, SSTableReader b)\n {\n return Integer.compare(a.descriptor.generation, b.descriptor.generation);\n }\n });\n\n Map<ByteBuffer, ColumnIndex> indexes = new HashMap<>();\n for (ColumnIndex index : indexedColumns.values())\n {\n Iterator<String> iterator = indexNames.iterator();\n\n while (iterator.hasNext())\n {\n String indexName = iterator.next();\n if (index.getIndexName().equals(indexName))\n {\n index.dropData(FBUtilities.timestampMicros());\n\n ColumnDefinition indexToBuild = index.getDefinition();\n indexes.put(indexToBuild.name, index);\n iterator.remove();\n break;\n }\n }\n }\n\n if (indexes.isEmpty())\n return;\n\n for (SSTableReader sstable : sstablesToRebuild)\n sstables.put(sstable, indexes);\n\n try\n {\n FBUtilities.waitOnFuture(CompactionManager.instance.submitIndexBuild(new IndexBuilder(sstables)));\n }\n catch (Exception e)\n {\n logger.error(\"Failed index build task\", e);\n }\n }\n\n public void delete(DecoratedKey key)\n {\n // called during 'nodetool cleanup' - can punt on impl'ing this\n }\n\n public void removeIndex(ByteBuffer columnName)\n {\n ColumnIndex index = indexedColumns.remove(columnName);\n if (index != null)\n index.dropData(FBUtilities.timestampMicros());\n }\n\n public void invalidate()\n {\n invalidate(true, FBUtilities.timestampMicros());\n }\n\n public void invalidate(boolean invalidateMemtable, long truncateUntil)\n {\n if (invalidateMemtable)\n invalidateMemtable();\n\n for (ColumnIndex index : indexedColumns.values())\n index.dropData(truncateUntil);\n }\n\n private void invalidateMemtable()\n {\n globalMemtable.getAndSet(new IndexMemtable(this));\n }\n\n public void truncateBlocking(long truncatedAt)\n {\n invalidate(false, truncatedAt);\n }\n\n public void forceBlockingFlush()\n {\n //nop, as this 2I will flush with the owning CF's sstable, so we don't need this extra work\n }\n\n public Collection<Component> getIndexComponents()\n {\n ImmutableList.Builder<Component> components = ImmutableList.builder();\n for (ColumnIndex index : indexedColumns.values())\n components.add(index.getComponent());\n\n return components.build();\n }\n\n public SSTableWriterListener getWriterListener(Descriptor descriptor, Source source)\n {\n return newWriter(descriptor, indexedColumns, source);\n }\n\n public IndexMemtable getMemtable()\n {\n return globalMemtable.get();\n }\n\n protected PerSSTableIndexWriter newWriter(Descriptor descriptor, Map<ByteBuffer, ColumnIndex> indexes, Source source)\n {\n return new PerSSTableIndexWriter(keyValidator, descriptor, source, indexes);\n }\n\n public void handleNotification(INotification notification, Object sender)\n {\n // unfortunately, we can only check the type of notification via instanceof :(\n if (notification instanceof SSTableAddedNotification)\n {\n SSTableAddedNotification notif = (SSTableAddedNotification) notification;\n updateView(Collections.<SSTableReader>emptyList(), Collections.singletonList(notif.added), getColumnDefs());\n }\n else if (notification instanceof SSTableListChangedNotification)\n {\n SSTableListChangedNotification notif = (SSTableListChangedNotification) notification;\n updateView(notif.removed, notif.added, getColumnDefs());\n }\n else if (notification instanceof MemtableRenewedNotification)\n {\n invalidateMemtable();\n }\n }\n\n protected SecondaryIndexSearcher createSecondaryIndexSearcher(Set<ByteBuffer> columns)\n {\n return new LocalSecondaryIndexSearcher(baseCfs.indexManager, columns);\n }\n\n protected class LocalSecondaryIndexSearcher extends SecondaryIndexSearcher\n {\n protected LocalSecondaryIndexSearcher(SecondaryIndexManager indexManager, Set<ByteBuffer> columns)\n {\n super(indexManager, columns);\n }\n\n public List<Row> search(ExtendedFilter filter)\n {\n metrics.markRequest();\n\n long startTime = System.nanoTime();\n\n try\n {\n return filter != null && !filter.getClause().isEmpty()\n ? new QueryPlan(SSTableAttachedSecondaryIndex.this, filter, DatabaseDescriptor.getRangeRpcTimeout()).execute()\n : Collections.<Row>emptyList();\n }\n catch (Exception e)\n {\n metrics.markFailure();\n\n if (e instanceof TimeQuotaExceededException)\n metrics.markTimeout();\n else\n logger.warn(\"error occurred while searching SASI indexes; ignoring\", e);\n\n return Collections.emptyList();\n }\n finally\n {\n metrics.updateLatency(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);\n }\n }\n\n public boolean isIndexing(List<IndexExpression> clause)\n {\n // this is a bit weak, currently just checks for the success of one column, not all\n // however, parent SIS.isIndexing only cares if one predicate is covered ... grrrr!!\n for (IndexExpression expression : clause)\n {\n if (indexedColumns.containsKey(expression.column_name))\n return true;\n }\n return false;\n }\n }\n\n private class IndexBuilder extends IndexBuildTask\n {\n private final SortedMap<SSTableReader, Map<ByteBuffer, ColumnIndex>> sstables;\n\n private long bytesProcessed = 0;\n private final long totalSizeInBytes;\n\n public IndexBuilder(SortedMap<SSTableReader, Map<ByteBuffer, ColumnIndex>> sstables)\n {\n long totalIndexBytes = 0;\n for (SSTableReader sstable : sstables.keySet())\n totalIndexBytes += getPrimaryIndexLength(sstable);\n\n this.sstables = sstables;\n this.totalSizeInBytes = totalIndexBytes;\n }\n\n @Override\n public void build()\n {\n for (Map.Entry<SSTableReader, Map<ByteBuffer, ColumnIndex>> e : sstables.entrySet())\n {\n SSTableReader sstable = e.getKey();\n Map<ByteBuffer, ColumnIndex> indexes = e.getValue();\n\n if (!sstable.acquireReference())\n {\n bytesProcessed += getPrimaryIndexLength(sstable);\n continue;\n }\n\n try\n {\n PerSSTableIndexWriter indexWriter = newWriter(sstable.descriptor.asTemporary(true), indexes, Source.COMPACTION);\n\n long previousKeyPosition = 0;\n try (KeyIterator keys = new KeyIterator(sstable.descriptor))\n {\n while (keys.hasNext())\n {\n if (isStopRequested())\n throw new CompactionInterruptedException(getCompactionInfo());\n\n final DecoratedKey key = keys.next();\n final long keyPosition = keys.getKeyPosition();\n\n indexWriter.startRow(key, keyPosition);\n try (SSTableSliceIterator row = new SSTableSliceIterator(sstable, key, ColumnSlice.ALL_COLUMNS_ARRAY, false))\n {\n while (row.hasNext())\n {\n OnDiskAtom atom = row.next();\n if (atom != null && atom instanceof Column)\n indexWriter.nextColumn((Column) atom);\n }\n }\n catch (IOException ex)\n {\n throw new FSReadError(ex, sstable.getFilename());\n }\n\n bytesProcessed += keyPosition - previousKeyPosition;\n previousKeyPosition = keyPosition;\n }\n\n completeSSTable(indexWriter, sstable, indexes.values());\n }\n }\n finally\n {\n sstable.releaseReference();\n }\n }\n }\n\n @Override\n public CompactionInfo getCompactionInfo()\n {\n return new CompactionInfo(baseCfs.metadata, OperationType.INDEX_BUILD, bytesProcessed, totalSizeInBytes);\n }\n\n private long getPrimaryIndexLength(SSTable sstable)\n {\n File primaryIndex = new File(sstable.getIndexFilename());\n return primaryIndex.exists() ? primaryIndex.length() : 0;\n }\n\n private void completeSSTable(PerSSTableIndexWriter indexWriter, SSTableReader sstable, Collection<ColumnIndex> indexes)\n {\n indexWriter.complete();\n\n for (ColumnIndex index : indexes)\n {\n File tmpIndex = new File(index.getPath(indexWriter.getDescriptor()));\n if (!tmpIndex.exists()) // no data was inserted into the index for given sstable\n continue;\n\n FileUtils.renameWithConfirm(tmpIndex, new File(index.getPath(sstable.descriptor)));\n index.update(Collections.<SSTableReader>emptyList(), Collections.singletonList(sstable));\n }\n }\n }\n}", "public class ColumnIndex\n{\n private static final String FILE_NAME_FORMAT = \"SI_%s.db\";\n\n private final ColumnDefinition column;\n private final AbstractType<?> comparator;\n private final IndexMode mode;\n\n private final Component component;\n private final DataTracker tracker;\n\n public ColumnIndex(AbstractType<?> keyValidator, ColumnDefinition column, AbstractType<?> comparator)\n {\n this.column = column;\n this.comparator = comparator;\n this.mode = IndexMode.getMode(column);\n this.tracker = new DataTracker(keyValidator, this);\n this.component = new Component(Component.Type.SECONDARY_INDEX, String.format(FILE_NAME_FORMAT, column.getIndexName()));\n }\n\n public void validate() throws ConfigurationException\n {\n mode.validate(column.getIndexOptions());\n }\n\n /**\n * Initialize this column index with specific set of SSTables.\n *\n * @param sstables The sstables to be used by index initially.\n *\n * @return A collection of sstables which don't have this specific index attached to them.\n */\n public Iterable<SSTableReader> init(Set<SSTableReader> sstables)\n {\n return tracker.update(Collections.<SSTableReader>emptySet(), sstables);\n }\n\n public void update(Collection<SSTableReader> oldSSTables, Collection<SSTableReader> newSSTables)\n {\n tracker.update(oldSSTables, newSSTables);\n }\n\n public ColumnDefinition getDefinition()\n {\n return column;\n }\n\n public AbstractType<?> getValidator()\n {\n return column.getValidator();\n }\n\n public Component getComponent()\n {\n return component;\n }\n\n public IndexMode getMode()\n {\n return mode;\n }\n\n public String getColumnName()\n {\n return comparator.getString(column.name);\n }\n\n public String getIndexName()\n {\n return column.getIndexName();\n }\n\n public AbstractAnalyzer getAnalyzer()\n {\n AbstractAnalyzer analyzer = mode.getAnalyzer(getValidator());\n analyzer.init(column.getIndexOptions(), column.getValidator());\n return analyzer;\n }\n\n public View getView()\n {\n return tracker.getView();\n }\n\n public void dropData(long truncateUntil)\n {\n tracker.dropData(truncateUntil);\n }\n\n public boolean isIndexed()\n {\n return mode != IndexMode.NOT_INDEXED;\n }\n\n public boolean isLiteral()\n {\n AbstractType<?> validator = getValidator();\n return isIndexed() ? mode.isLiteral : (validator instanceof UTF8Type || validator instanceof AsciiType);\n }\n\n public String getPath(Descriptor sstable)\n {\n return sstable.filenameFor(component);\n }\n}", "public abstract class Token implements CombinedValue<Long>, Iterable<DecoratedKey>\n{\n protected final long token;\n\n public Token(long token)\n {\n this.token = token;\n }\n\n @Override\n public Long get()\n {\n return token;\n }\n\n @Override\n public int compareTo(CombinedValue<Long> o)\n {\n return Longs.compare(token, ((Token) o).token);\n }\n}", "public class Expression\n{\n private static final Logger logger = LoggerFactory.getLogger(Expression.class);\n\n public enum Op\n {\n EQ, NOT_EQ, RANGE\n }\n\n private final QueryController controller;\n\n public final AbstractAnalyzer analyzer;\n\n public final ColumnIndex index;\n public final AbstractType<?> validator;\n public final boolean isLiteral;\n\n @VisibleForTesting\n protected Op operation;\n\n public Bound lower, upper;\n public List<ByteBuffer> exclusions = new ArrayList<>();\n\n public Expression(Expression other)\n {\n this(other.controller, other.index);\n operation = other.operation;\n }\n\n public Expression(QueryController controller, ColumnIndex columnIndex)\n {\n this.controller = controller;\n this.index = columnIndex;\n this.analyzer = columnIndex.getAnalyzer();\n this.validator = columnIndex.getValidator();\n this.isLiteral = columnIndex.isLiteral();\n }\n\n @VisibleForTesting\n public Expression(ByteBuffer name, AbstractType<?> validator)\n {\n this(null, new ColumnIndex(UTF8Type.instance, ColumnDefinition.regularDef(name, validator, 0), UTF8Type.instance));\n }\n\n public Expression setLower(Bound newLower)\n {\n lower = newLower == null ? null : new Bound(newLower.value, newLower.inclusive);\n return this;\n }\n\n public Expression setUpper(Bound newUpper)\n {\n upper = newUpper == null ? null : new Bound(newUpper.value, newUpper.inclusive);\n return this;\n }\n\n public Expression setOp(Op op)\n {\n this.operation = op;\n return this;\n }\n\n public Expression add(IndexOperator op, ByteBuffer value)\n {\n boolean lowerInclusive = false, upperInclusive = false;\n switch (op)\n {\n case EQ:\n lower = new Bound(value, true);\n upper = lower;\n operation = Op.EQ;\n break;\n\n case NOT_EQ:\n // index expressions are priority sorted\n // and NOT_EQ is the lowest priority, which means that operation type\n // is always going to be set before reaching it in case of RANGE or EQ.\n if (operation == null)\n {\n operation = Op.NOT_EQ;\n lower = new Bound(value, true);\n upper = lower;\n }\n else\n exclusions.add(value);\n break;\n\n case LTE:\n upperInclusive = true;\n case LT:\n operation = Op.RANGE;\n upper = new Bound(value, upperInclusive);\n break;\n\n case GTE:\n lowerInclusive = true;\n case GT:\n operation = Op.RANGE;\n lower = new Bound(value, lowerInclusive);\n break;\n }\n\n return this;\n }\n\n public Expression addExclusion(ByteBuffer value)\n {\n exclusions.add(value);\n return this;\n }\n\n public boolean contains(ByteBuffer value)\n {\n if (!TypeUtil.isValid(value, validator))\n {\n int size = value.remaining();\n if ((value = TypeUtil.tryUpcast(value, validator)) == null)\n {\n logger.error(\"Can't cast value for {} to size accepted by {}, value size is {} bytes.\",\n index.getColumnName(),\n validator,\n size);\n return false;\n }\n }\n\n if (lower != null)\n {\n // suffix check\n if (isLiteral)\n {\n if (!validateStringValue(value, lower.value))\n return false;\n }\n else\n {\n // range or (not-)equals - (mainly) for numeric values\n int cmp = validator.compare(lower.value, value);\n\n // in case of (NOT_)EQ lower == upper\n if (operation == Op.EQ || operation == Op.NOT_EQ)\n return cmp == 0;\n\n if (cmp > 0 || (cmp == 0 && !lower.inclusive))\n return false;\n }\n }\n\n if (upper != null && lower != upper)\n {\n // string (prefix or suffix) check\n if (isLiteral)\n {\n if (!validateStringValue(value, upper.value))\n return false;\n }\n else\n {\n // range - mainly for numeric values\n int cmp = validator.compare(upper.value, value);\n if (cmp < 0 || (cmp == 0 && !upper.inclusive))\n return false;\n }\n }\n\n // as a last step let's check exclusions for the given field,\n // this covers EQ/RANGE with exclusions.\n for (ByteBuffer term : exclusions)\n {\n if (isLiteral && validateStringValue(value, term))\n return false;\n else if (validator.compare(term, value) == 0)\n return false;\n }\n\n return true;\n }\n\n private boolean validateStringValue(ByteBuffer columnValue, ByteBuffer requestedValue)\n {\n analyzer.reset(columnValue.duplicate());\n while (analyzer.hasNext())\n {\n ByteBuffer term = analyzer.next();\n if (ByteBufferUtil.contains(term, requestedValue))\n return true;\n }\n\n return false;\n }\n\n public Op getOp()\n {\n return operation;\n }\n\n public void checkpoint()\n {\n if (controller == null)\n return;\n\n controller.checkpoint();\n }\n\n public boolean hasLower()\n {\n return lower != null;\n }\n\n public boolean hasUpper()\n {\n return upper != null;\n }\n\n public boolean isLowerSatisfiedBy(OnDiskIndex.DataTerm term)\n {\n if (!hasLower())\n return true;\n\n int cmp = term.compareTo(validator, lower.value, false);\n return cmp > 0 || cmp == 0 && lower.inclusive;\n }\n\n public boolean isUpperSatisfiedBy(OnDiskIndex.DataTerm term)\n {\n if (!hasUpper())\n return true;\n\n int cmp = term.compareTo(validator, upper.value, false);\n return cmp < 0 || cmp == 0 && upper.inclusive;\n }\n\n public boolean isIndexed()\n {\n return index.isIndexed();\n }\n\n @Override\n public String toString()\n {\n return String.format(\"Expression{name: %s, op: %s, lower: (%s, %s), upper: (%s, %s), exclusions: %s}\",\n index.getColumnName(),\n operation,\n lower == null ? \"null\" : validator.getString(lower.value),\n lower != null && lower.inclusive,\n upper == null ? \"null\" : validator.getString(upper.value),\n upper != null && upper.inclusive,\n Iterators.toString(Iterators.transform(exclusions.iterator(), new Function<ByteBuffer, String>()\n {\n @Override\n public String apply(ByteBuffer exclusion)\n {\n return validator.getString(exclusion);\n }\n })));\n }\n\n @Override\n public int hashCode()\n {\n return new HashCodeBuilder().append(index.getColumnName())\n .append(operation)\n .append(validator)\n .append(lower).append(upper)\n .append(exclusions).build();\n }\n\n @Override\n public boolean equals(Object other)\n {\n if (!(other instanceof Expression))\n return false;\n\n if (this == other)\n return true;\n\n Expression o = (Expression) other;\n\n return Objects.equals(index.getColumnName(), o.index.getColumnName())\n && validator.equals(o.validator)\n && operation == o.operation\n && Objects.equals(lower, o.lower)\n && Objects.equals(upper, o.upper)\n && exclusions.equals(o.exclusions);\n }\n\n\n public static class Bound\n {\n public final ByteBuffer value;\n public final boolean inclusive;\n\n public Bound(ByteBuffer value, boolean inclusive)\n {\n this.value = value;\n this.inclusive = inclusive;\n }\n\n @Override\n public boolean equals(Object other)\n {\n if (!(other instanceof Bound))\n return false;\n\n Bound o = (Bound) other;\n return value.equals(o.value) && inclusive == o.inclusive;\n }\n }\n}", "public abstract class RangeIterator<K extends Comparable<K>, T extends CombinedValue<K>> extends AbstractIterator<T> implements Closeable\n{\n private final K min, max;\n private final long count;\n private K current;\n\n protected RangeIterator(Builder.Statistics<K, T> statistics)\n {\n this(statistics.min, statistics.max, statistics.tokenCount);\n }\n\n public RangeIterator(RangeIterator<K, T> range)\n {\n this(range == null ? null : range.min, range == null ? null : range.max, range == null ? -1 : range.count);\n }\n\n public RangeIterator(K min, K max, long count)\n {\n this.min = min;\n this.current = min;\n this.max = max;\n this.count = count;\n }\n\n public final K getMinimum()\n {\n return min;\n }\n\n public final K getCurrent()\n {\n return current;\n }\n\n public final K getMaximum()\n {\n return max;\n }\n\n public final long getCount()\n {\n return count;\n }\n\n /**\n * When called, this iterators current position should\n * be skipped forwards until finding either:\n * 1) an element equal to or bigger than next\n * 2) the end of the iterator\n *\n * @param nextToken value to skip the iterator forward until matching\n *\n * @return The next current token after the skip was performed\n */\n public final T skipTo(K nextToken)\n {\n if (min == null || max == null)\n return endOfData();\n\n if (current.compareTo(nextToken) >= 0)\n return next == null ? recomputeNext() : next;\n\n if (max.compareTo(nextToken) < 0)\n return endOfData();\n\n performSkipTo(nextToken);\n return recomputeNext();\n }\n\n protected abstract void performSkipTo(K nextToken);\n\n protected T recomputeNext()\n {\n return tryToComputeNext() ? peek() : endOfData();\n }\n\n @Override\n protected boolean tryToComputeNext()\n {\n boolean hasNext = super.tryToComputeNext();\n current = hasNext ? next.get() : getMaximum();\n return hasNext;\n }\n\n public static abstract class Builder<K extends Comparable<K>, D extends CombinedValue<K>>\n {\n public enum IteratorType\n {\n UNION, INTERSECTION\n }\n\n @VisibleForTesting\n protected final Statistics<K, D> statistics;\n\n @VisibleForTesting\n protected final PriorityQueue<RangeIterator<K, D>> ranges;\n\n public Builder(IteratorType type)\n {\n statistics = new Statistics<>(type);\n ranges = new PriorityQueue<>(16, new Comparator<RangeIterator<K, D>>()\n {\n @Override\n public int compare(RangeIterator<K, D> a, RangeIterator<K, D> b)\n {\n return a.getCurrent().compareTo(b.getCurrent());\n }\n });\n }\n\n public K getMinimum()\n {\n return statistics.min;\n }\n\n public K getMaximum()\n {\n return statistics.max;\n }\n\n public long getTokenCount()\n {\n return statistics.tokenCount;\n }\n\n public int rangeCount()\n {\n return ranges.size();\n }\n\n public Builder<K, D> add(RangeIterator<K, D> range)\n {\n if (range == null || range.getMinimum() == null || range.getMaximum() == null)\n return this;\n\n ranges.add(range);\n statistics.update(range);\n\n return this;\n }\n\n public Builder<K, D> add(List<RangeIterator<K, D>> ranges)\n {\n if (ranges == null || ranges.isEmpty())\n return this;\n\n for (RangeIterator<K, D> range : ranges)\n add(range);\n\n return this;\n }\n\n public final RangeIterator<K, D> build()\n {\n switch (rangeCount())\n {\n case 0:\n return null;\n\n case 1:\n return ranges.poll();\n\n default:\n return buildIterator();\n }\n }\n\n protected abstract RangeIterator<K, D> buildIterator();\n\n public static class Statistics<K extends Comparable<K>, D extends CombinedValue<K>>\n {\n protected final IteratorType iteratorType;\n\n protected K min, max;\n protected long tokenCount;\n\n // iterator with the least number of items\n protected RangeIterator<K, D> minRange;\n // iterator with the most number of items\n protected RangeIterator<K, D> maxRange;\n\n // tracks if all of the added ranges overlap, which is useful in case of intersection,\n // as it gives direct answer as to such iterator is going to produce any results.\n protected boolean isOverlapping = true;\n\n public Statistics(IteratorType iteratorType)\n {\n this.iteratorType = iteratorType;\n }\n\n /**\n * Update statistics information with the given range.\n *\n * Updates min/max of the combined range, token count and\n * tracks range with the least/most number of tokens.\n *\n * @param range The range to update statistics with.\n */\n public void update(RangeIterator<K, D> range)\n {\n switch (iteratorType)\n {\n case UNION:\n min = min == null || min.compareTo(range.getMinimum()) > 0 ? range.getMinimum() : min;\n max = max == null || max.compareTo(range.getMaximum()) < 0 ? range.getMaximum() : max;\n break;\n\n case INTERSECTION:\n // minimum of the intersection is the biggest minimum of individual iterators\n min = min == null || min.compareTo(range.getMinimum()) < 0 ? range.getMinimum() : min;\n // maximum of the intersection is the smallest maximum of individual iterators\n max = max == null || max.compareTo(range.getMaximum()) > 0 ? range.getMaximum() : max;\n break;\n\n default:\n throw new IllegalStateException(\"Unknown iterator type: \" + iteratorType);\n }\n\n // check if new range is disjoint with already added ranges, which means that this intersection\n // is not going to produce any results, so we can cleanup range storage and never added anything to it.\n isOverlapping &= isOverlapping(min, max, range);\n\n minRange = minRange == null ? range : min(minRange, range);\n maxRange = maxRange == null ? range : max(maxRange, range);\n\n tokenCount += range.getCount();\n\n }\n\n private RangeIterator<K, D> min(RangeIterator<K, D> a, RangeIterator<K, D> b)\n {\n return a.getCount() > b.getCount() ? b : a;\n }\n\n private RangeIterator<K, D> max(RangeIterator<K, D> a, RangeIterator<K, D> b)\n {\n return a.getCount() > b.getCount() ? a : b;\n }\n\n public boolean isDisjoint()\n {\n return !isOverlapping;\n }\n\n public double sizeRatio()\n {\n return minRange.getCount() * 1d / maxRange.getCount();\n }\n }\n }\n\n @VisibleForTesting\n protected static <K extends Comparable<K>, D extends CombinedValue<K>> boolean isOverlapping(RangeIterator<K, D> a, RangeIterator<K, D> b)\n {\n return isOverlapping(a.getCurrent(), a.getMaximum(), b);\n }\n\n @VisibleForTesting\n protected static <K extends Comparable<K>, D extends CombinedValue<K>> boolean isOverlapping(K min, K max, RangeIterator<K, D> b)\n {\n return min.compareTo(b.getMaximum()) <= 0 && b.getCurrent().compareTo(max) <= 0;\n }\n}", "public class TypeUtil\n{\n public static boolean isValid(ByteBuffer term, AbstractType<?> validator)\n {\n try\n {\n validator.validate(term);\n return true;\n }\n catch (MarshalException e)\n {\n return false;\n }\n }\n\n public static ByteBuffer tryUpcast(ByteBuffer term, AbstractType<?> validator)\n {\n if (term.remaining() == 0)\n return null;\n\n try\n {\n if (validator instanceof Int32Type && term.remaining() == 2)\n {\n return Int32Type.instance.decompose((int) term.getShort(term.position()));\n }\n else if (validator instanceof LongType)\n {\n long upcastToken;\n\n switch (term.remaining())\n {\n case 2:\n upcastToken = (long) term.getShort(term.position());\n break;\n\n case 4:\n upcastToken = (long) Int32Type.instance.compose(term);\n break;\n\n default:\n upcastToken = Long.valueOf(UTF8Type.instance.getString(term));\n }\n\n return LongType.instance.decompose(upcastToken);\n }\n else if (validator instanceof DoubleType && term.remaining() == 4)\n {\n return DoubleType.instance.decompose((double) FloatType.instance.compose(term));\n }\n\n // maybe it was a string after all\n return validator.fromString(UTF8Type.instance.getString(term));\n }\n catch (Exception e)\n {\n return null;\n }\n }\n}" ]
import org.cliffc.high_scale_lib.NonBlockingHashMap; import org.github.jamm.MemoryMeter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentMap; import org.apache.cassandra.db.Column; import org.apache.cassandra.db.index.SSTableAttachedSecondaryIndex; import org.apache.cassandra.db.index.sasi.conf.ColumnIndex; import org.apache.cassandra.db.index.sasi.disk.Token; import org.apache.cassandra.db.index.sasi.plan.Expression; import org.apache.cassandra.db.index.sasi.utils.RangeIterator; import org.apache.cassandra.db.index.sasi.utils.TypeUtil; import org.apache.cassandra.db.marshal.AbstractType;
/* * 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.cassandra.db.index.sasi.memory; public class IndexMemtable { private static final Logger logger = LoggerFactory.getLogger(IndexMemtable.class); private final MemoryMeter meter; private final ConcurrentMap<ByteBuffer, MemIndex> indexes; private final SSTableAttachedSecondaryIndex backend; public IndexMemtable(final SSTableAttachedSecondaryIndex backend) { this.indexes = new NonBlockingHashMap<>(); this.backend = backend; this.meter = new MemoryMeter().omitSharedBufferOverhead().withTrackerProvider(new Callable<Set<Object>>() { public Set<Object> call() throws Exception { // avoid counting this once for each row Set<Object> set = Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()); set.add(backend.getBaseCfs().metadata); return set; } }); } public long estimateSize() { long deepSize = 0; for (MemIndex index : indexes.values()) deepSize += index.estimateSize(meter); return deepSize; } public void index(ByteBuffer key, Iterator<Column> row) { final long now = System.currentTimeMillis(); while (row.hasNext()) { Column column = row.next(); if (column.isMarkedForDelete(now)) continue;
ColumnIndex columnIndex = backend.getIndex(column.name());
1
hoijui/JavaOSC
modules/core/src/main/java/com/illposed/osc/transport/udp/UDPTransport.java
[ "public final class LibraryInfo {\n\n\tprivate static final String MANIFEST_FILE = \"/META-INF/MANIFEST.MF\";\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static final String UNKNOWN_VALUE = \"<unknown>\";\n\tprivate static final char MANIFEST_CONTINUATION_LINE_INDICATOR = ' ';\n\t/** 1 key + 1 value = 2 parts of a key-value pair */\n\tprivate static final int KEY_PLUS_VALUE_COUNT = 2;\n\tprivate static final Set<Package> UNINTERESTING_PKGS;\n\tprivate final Properties manifestProperties;\n\n\tstatic {\n\t\tfinal Set<Package> tmpUninterestingPkgs = new HashSet<>();\n\t\ttmpUninterestingPkgs.add(Package.getPackage(\"java.lang\"));\n\t\ttmpUninterestingPkgs.add(Package.getPackage(\"java.util\"));\n\t\t// NOTE We need to do it like this, because otherwise \"java.awt\" can not be found\n\t\t// by this classes class-loader.\n\t\tfinal Class<?> javaAwtColorClass = getAwtColor();\n\t\tif (javaAwtColorClass != null) {\n\t\t\ttmpUninterestingPkgs.add(javaAwtColorClass.getPackage());\n\t\t}\n\t\ttmpUninterestingPkgs.add(OSCImpulse.class.getPackage());\n\t\tUNINTERESTING_PKGS = Collections.unmodifiableSet(tmpUninterestingPkgs);\n\t}\n\n\tpublic LibraryInfo() throws IOException {\n\n\t\tthis.manifestProperties = readJarManifest();\n\t}\n\n\tprivate static Properties parseManifestFile(final InputStream manifestIn) throws IOException {\n\n\t\tfinal Properties manifestProps = new Properties();\n\n\t\ttry (final BufferedReader manifestBufferedIn = new BufferedReader(new InputStreamReader(manifestIn,\n\t\t\t\tStandardCharsets.UTF_8)))\n\t\t{\n\t\t\tString manifestLine = manifestBufferedIn.readLine();\n\t\t\tString currentKey = null;\n\t\t\tfinal StringBuilder currentValue = new StringBuilder(80);\n\t\t\t// NOTE one property can be specified on multiple lines.\n\t\t\t// This is done by prepending all but the first line with white-space, for example:\n\t\t\t// \"My-Key: hello, this is my very long property value, which is sp\"\n\t\t\t// \" lit over multiple lines, and because we also want to show the \"\n\t\t\t// \" third line, we write a little more.\"\n\t\t\twhile (manifestLine != null) {\n\t\t\t\t// filter out empty lines and comments\n\t\t\t\t// NOTE Is there really a comment syntax defined for manifest files?\n\t\t\t\tif (!manifestLine.trim().isEmpty() && !manifestLine.startsWith(\"[#%]\")) {\n\t\t\t\t\tif (manifestLine.charAt(0) == MANIFEST_CONTINUATION_LINE_INDICATOR) {\n\t\t\t\t\t\t// remove the initial space and add it to the already read value\n\t\t\t\t\t\tcurrentValue.append(manifestLine.substring(1));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (currentKey != null) {\n\t\t\t\t\t\t\tmanifestProps.setProperty(currentKey, currentValue.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfinal String[] keyAndValue = manifestLine.split(\": \", KEY_PLUS_VALUE_COUNT);\n\t\t\t\t\t\tif (keyAndValue.length < KEY_PLUS_VALUE_COUNT) {\n\t\t\t\t\t\t\tthrow new IOException(\"Invalid manifest line: \\\"\" + manifestLine + '\"');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentKey = keyAndValue[0];\n\t\t\t\t\t\tcurrentValue.setLength(0);\n\t\t\t\t\t\tcurrentValue.append(keyAndValue[1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmanifestLine = manifestBufferedIn.readLine();\n\t\t\t}\n\t\t\tif (currentKey != null) {\n\t\t\t\tmanifestProps.setProperty(currentKey, currentValue.toString());\n\t\t\t}\n\t\t}\n\n\t\treturn manifestProps;\n\t}\n\n\tprivate static Properties readJarManifest() throws IOException {\n\n\t\tProperties mavenProps;\n\n\t\ttry (final InputStream manifestFileIn = LibraryInfo.class.getResourceAsStream(MANIFEST_FILE)) {\n\t\t\tif (manifestFileIn == null) {\n\t\t\t\tthrow new IOException(\"Failed locating resource in the classpath: \" + MANIFEST_FILE);\n\t\t\t}\n\t\t\tmavenProps = parseManifestFile(manifestFileIn);\n\t\t}\n\n\t\treturn mavenProps;\n\t}\n\n\t// Public API\n\t/**\n\t * Returns this application JARs {@link #MANIFEST_FILE} properties.\n\t * @return the contents of the manifest file as {@code String} to {@code String} mapping\n\t */\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic Properties getManifestProperties() {\n\t\treturn manifestProperties;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic String getVersion() {\n\t\treturn getManifestProperties().getProperty(\"Bundle-Version\", UNKNOWN_VALUE);\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic String getOscSpecificationVersion() {\n\t\treturn getManifestProperties().getProperty(\"Supported-OSC-Version\", UNKNOWN_VALUE);\n\t}\n\n\tpublic String getLicense() {\n\t\treturn getManifestProperties().getProperty(\"Bundle-License\", UNKNOWN_VALUE);\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic boolean isArrayEncodingSupported() {\n\t\treturn true;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic boolean isArrayDecodingSupported() {\n\t\treturn true;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic List<ArgumentHandler> getEncodingArgumentHandlers() {\n\t\treturn new ArrayList<>(getDecodingArgumentHandlers().values());\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic Map<Character, ArgumentHandler> getDecodingArgumentHandlers() {\n\t\treturn new OSCSerializerAndParserBuilder().getIdentifierToTypeMapping();\n\t}\n\n\tprivate static String extractPrettyClassName(final Class javaClass) {\n\n\t\tfinal String prettyClassName;\n\t\tif (UNINTERESTING_PKGS.contains(javaClass.getPackage())) {\n\t\t\tprettyClassName = javaClass.getSimpleName();\n\t\t} else {\n\t\t\tprettyClassName = javaClass.getCanonicalName();\n\t\t}\n\t\treturn prettyClassName;\n\t}\n\n\tprivate static String extractTypeClassOrMarkerValue(final ArgumentHandler type) {\n\n\t\tfinal String classOrMarkerValue;\n\t\tif (type.isMarkerOnly()) {\n\t\t\ttry {\n\t\t\t\tfinal Object markerValue = type.parse(null);\n\t\t\t\tfinal String markerValueStr = (markerValue == null) ? \"null\"\n\t\t\t\t\t\t: markerValue.toString();\n\t\t\t\tclassOrMarkerValue = extractPrettyClassName(type.getJavaClass())\n\t\t\t\t\t\t+ ':' + markerValueStr;\n\t\t\t} catch (OSCParseException ex) {\n\t\t\t\tthrow new IllegalStateException(\"Developer error; This should never happen\", ex);\n\t\t\t}\n\t\t} else {\n\t\t\tclassOrMarkerValue = extractPrettyClassName(type.getJavaClass());\n\t\t}\n\n\t\treturn classOrMarkerValue;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"unused\")\n\tpublic String createManifestPropertiesString() {\n\n\t\tfinal StringBuilder info = new StringBuilder(1024);\n\n\t\tfor (final Map.Entry<Object, Object> manifestEntry : getManifestProperties().entrySet()) {\n\t\t\tfinal String key = (String) manifestEntry.getKey();\n\t\t\tfinal String value = (String) manifestEntry.getValue();\n\t\t\tinfo\n\t\t\t\t\t.append(String.format(\"%32s\", key))\n\t\t\t\t\t.append(\" -> \")\n\t\t\t\t\t.append(value)\n\t\t\t\t\t.append('\\n');\n\t\t}\n\n\t\treturn info.toString();\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic String createLibrarySummary() {\n\n\t\tfinal StringBuilder summary = new StringBuilder(1024);\n\n\t\tsummary\n\t\t\t\t.append(\"\\nName: \").append(getManifestProperties().getProperty(\"Bundle-Name\", UNKNOWN_VALUE))\n\t\t\t\t.append(\"\\nDescription: \").append(getManifestProperties().getProperty(\"Bundle-Description\", UNKNOWN_VALUE))\n\t\t\t\t.append(\"\\nVersion: \").append(getVersion())\n\t\t\t\t.append(\"\\nOSC-Spec.: \").append(getOscSpecificationVersion())\n\t\t\t\t.append(\"\\nLicense: \").append(getLicense())\n\t\t\t\t.append(\"\\nArgument serialization:\"\n\t\t\t\t\t\t+ \"\\n [Java] -> [OSC]\");\n\t\tif (isArrayEncodingSupported()) {\n\t\t\tsummary.append(\"\\n \")\n\t\t\t\t\t.append(String.format(\"%16s\", extractPrettyClassName(List.class)))\n\t\t\t\t\t.append(\" -> '\")\n\t\t\t\t\t.append(OSCParser.TYPE_ARRAY_BEGIN)\n\t\t\t\t\t.append(\"'...'\")\n\t\t\t\t\t.append(OSCParser.TYPE_ARRAY_END)\n\t\t\t\t\t.append('\\'');\n\t\t}\n\t\tfor (final ArgumentHandler encodingType : getEncodingArgumentHandlers()) {\n\t\t\tsummary.append(\"\\n \")\n\t\t\t\t\t.append(String.format(\"%16s\", extractTypeClassOrMarkerValue(encodingType)))\n\t\t\t\t\t.append(\" -> '\")\n\t\t\t\t\t.append(encodingType.getDefaultIdentifier())\n\t\t\t\t\t.append('\\'');\n\t\t}\n\n\t\tsummary\n\t\t\t\t.append(\"\\nArgument parsing:\"\n\t\t\t\t\t\t+ \"\\n [OSC] -> [Java]\");\n\t\tif (isArrayDecodingSupported()) {\n\t\t\tsummary.append(\"\\n '\")\n\t\t\t\t\t.append(OSCParser.TYPE_ARRAY_BEGIN)\n\t\t\t\t\t.append(\"'...'\")\n\t\t\t\t\t.append(OSCParser.TYPE_ARRAY_END)\n\t\t\t\t\t.append(\"' -> \")\n\t\t\t\t\t.append(extractPrettyClassName(List.class));\n\t\t}\n\t\tfor (final Map.Entry<Character, ArgumentHandler> decodingType : getDecodingArgumentHandlers().entrySet()) {\n\t\t\tsummary.append(\"\\n '\")\n\t\t\t\t\t.append(decodingType.getKey())\n\t\t\t\t\t.append(\"' -> \")\n\t\t\t\t\t.append(extractTypeClassOrMarkerValue(decodingType.getValue()));\n\t\t}\n\n\t\treturn summary.toString();\n\t}\n\n\t/**\n\t * Checks for StandardProtocolFamily Jdk8 compatibility of the runtime.\n\t * E.g. Android API 23 and lower has only a\n\t * java 8 subset without java.net.StandardProtocolFamily\n\t * @return true when the runtime supports java.net.StandardProtocolFamily\n\t * (e.g. Android API 23 and lower)\n\t */\n\tpublic static boolean hasStandardProtocolFamily() {\n\t\ttry {\n\t\t\tClass.forName(\"java.net.StandardProtocolFamily\");\n\t\t\treturn true;\n\t\t} catch (ClassNotFoundException ignore) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Checks if java.awt.Color is available.\n\t * It's not available on Android for example.\n\t * Some headless servers might also lack this class.\n\t * @return true when the runtime supports java.awt.Color\n\t * (e.g. Android)\n\t */\n\tstatic Class<?> getAwtColor() {\n\t\ttry {\n\t\t\treturn Class.forName(\"java.awt.Color\");\n\t\t} catch (ClassNotFoundException ignore) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic static void main(final String[] args) throws IOException {\n\n\t\tfinal Logger log = LoggerFactory.getLogger(LibraryInfo.class);\n\t\tif (log.isInfoEnabled()) {\n\t\t\tfinal LibraryInfo libraryInfo = new LibraryInfo();\n\t\t\tlog.info(libraryInfo.createLibrarySummary());\n//\t\t\tlog.info(libraryInfo.createManifestPropertiesString());\n\t\t}\n\t}\n}", "public interface OSCPacket extends Serializable {\n\n}", "public class OSCParseException extends Exception {\n\tprivate final ByteBuffer data;\n\n\tpublic ByteBuffer getData() {\n\t\treturn data;\n\t}\n\n\tpublic OSCParseException(final String message, final ByteBuffer data) {\n\t\tsuper(message);\n\t\tthis.data = data;\n\t}\n\n\tpublic OSCParseException(final Throwable cause, final ByteBuffer data) {\n\t\tsuper(cause);\n\t\tthis.data = data;\n\t}\n\n\tpublic OSCParseException(\n\t\tfinal String message,\n\t\tfinal Throwable cause,\n\t\tfinal ByteBuffer data)\n\t{\n\t\tsuper(message, cause);\n\t\tthis.data = data;\n\t}\n}", "public class OSCSerializerAndParserBuilder {\n\n\tprivate final Map<String, Object> properties;\n\tprivate final Map<Character, ArgumentHandler> identifierToType;\n\tprivate boolean usingDefaultHandlers;\n\n\tpublic OSCSerializerAndParserBuilder() {\n\n\t\tthis.properties = new HashMap<>();\n\t\tthis.identifierToType = new HashMap<>();\n\t\tthis.usingDefaultHandlers = true;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic Map<Character, ArgumentHandler> getIdentifierToTypeMapping() {\n\t\treturn Collections.unmodifiableMap(identifierToType);\n\t}\n\n\tpublic OSCSerializer buildSerializer(final BytesReceiver output) {\n\n\t\tfinal Map<String, Object> currentProperties = getProperties();\n\t\tfinal List<ArgumentHandler> typeCopies\n\t\t\t\t= new ArrayList<>(identifierToType.size());\n\t\tfor (final ArgumentHandler<?> type : identifierToType.values()) {\n\t\t\tfinal ArgumentHandler<?> typeClone;\n\t\t\ttry {\n\t\t\t\ttypeClone = type.clone();\n\t\t\t} catch (final CloneNotSupportedException ex) {\n\t\t\t\tthrow new IllegalStateException(\"Does not support cloning: \" + type.getClass(), ex);\n\t\t\t}\n\t\t\ttypeClone.setProperties(currentProperties);\n\n\t\t\ttypeCopies.add(typeClone);\n\t\t}\n\n\t\tif (usingDefaultHandlers) {\n\t\t\tfinal List<ArgumentHandler> defaultParserTypes = Activator.createSerializerTypes();\n\t\t\ttypeCopies.addAll(defaultParserTypes);\n\t\t}\n\n\t\treturn new OSCSerializer(typeCopies, currentProperties, output);\n\t}\n\n\tpublic OSCParser buildParser() {\n\n\t\t// first create a shallow copy\n\t\tfinal Map<Character, ArgumentHandler> identifierToTypeCopy\n\t\t\t\t= new HashMap<>(identifierToType.size());\n\t\t// now make it deep & set the properties\n\t\tfinal Map<String, Object> currentProperties = getProperties();\n\t\tfor (final Map.Entry<Character, ArgumentHandler> typeEntry : identifierToType.entrySet()) {\n\t\t\tfinal ArgumentHandler<?> typeClone;\n\t\t\ttry {\n\t\t\t\ttypeClone = typeEntry.getValue().clone();\n\t\t\t} catch (final CloneNotSupportedException ex) {\n\t\t\t\tthrow new IllegalStateException(\"Does not support cloning: \"\n\t\t\t\t\t\t+ typeEntry.getValue().getClass(), ex);\n\t\t\t}\n\t\t\tidentifierToTypeCopy.put(typeEntry.getKey(), typeClone);\n\n\t\t\ttypeClone.setProperties(currentProperties);\n\t\t}\n\n\t\tif (usingDefaultHandlers) {\n\t\t\tfinal Map<Character, ArgumentHandler> defaultParserTypes = Activator.createParserTypes();\n\t\t\tidentifierToTypeCopy.putAll(defaultParserTypes);\n\t\t}\n\n\t\treturn new OSCParser(identifierToTypeCopy, currentProperties);\n\t}\n\n\tpublic OSCSerializerAndParserBuilder setUsingDefaultHandlers(final boolean newUsingDefaultHandlers) {\n\n\t\tthis.usingDefaultHandlers = newUsingDefaultHandlers;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the current set of properties.\n\t * These will be propagated to created serializers and parsers\n\t * and to the argument-handlers.\n\t * @return the set of properties to adhere to\n\t * @see ArgumentHandler#setProperties(Map)\n\t */\n\tpublic Map<String, Object> getProperties() {\n\t\treturn Collections.unmodifiableMap(properties);\n\t}\n\n\t/**\n\t * Sets a new set of properties after clearing the current ones.\n\t * Properties will be propagated to created serializers and parsers\n\t * and to the argument-handlers.\n\t * This will only have an effect for serializers, parsers and argument-handlers\n\t * being created in the future.\n\t * @param newProperties the new set of properties to adhere to\n\t */\n\tpublic OSCSerializerAndParserBuilder setProperties(final Map<String, Object> newProperties) {\n\n\t\tclearProperties();\n\t\taddProperties(newProperties);\n\t\treturn this;\n\t}\n\n\t// Public API\n\t/**\n\t * Adds a new set of properties, extending,\n\t * possibly overriding the current ones.\n\t * Properties will be propagated to created serializers and parsers\n\t * and to the argument-handlers.\n\t * This will only have an effect for serializers, parsers and argument-handlers\n\t * being created in the future.\n\t * @param additionalProperties the new set of properties to adhere to\n\t */\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic OSCSerializerAndParserBuilder addProperties(final Map<String, Object> additionalProperties) {\n\n\t\tproperties.putAll(additionalProperties);\n\t\treturn this;\n\t}\n\n\t// Public API\n\t/**\n\t * Clears all currently stored properties.\n\t * Properties will be propagated to created serializers and parsers\n\t * and to the argument-handlers.\n\t * This will only have an effect for serializers, parsers and argument-handlers\n\t * being created in the future.\n\t */\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic OSCSerializerAndParserBuilder clearProperties() {\n\n\t\tproperties.clear();\n\t\treturn this;\n\t}\n\n\t// Public API\n\tpublic OSCSerializerAndParserBuilder registerArgumentHandler(final ArgumentHandler argumentHandler) {\n\n\t\tregisterArgumentHandler(argumentHandler, argumentHandler.getDefaultIdentifier());\n\t\treturn this;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic OSCSerializerAndParserBuilder registerArgumentHandler(\n\t\t\tfinal ArgumentHandler argumentHandler,\n\t\t\tfinal char typeIdentifier)\n\t{\n\t\tfinal ArgumentHandler previousArgumentHandler = identifierToType.get(typeIdentifier);\n\t\tif (previousArgumentHandler != null) {\n\t\t\tthrow new IllegalStateException(\"Type identifier '\" + typeIdentifier\n\t\t\t\t\t+ \"' is already used for type \"\n\t\t\t\t\t+ previousArgumentHandler.getClass().getCanonicalName());\n\t\t}\n\t\tidentifierToType.put(typeIdentifier, argumentHandler);\n\t\treturn this;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"unused\")\n\tpublic OSCSerializerAndParserBuilder unregisterArgumentHandler(final ArgumentHandler argumentHandler) {\n\n\t\tunregisterArgumentHandler(argumentHandler.getDefaultIdentifier());\n\t\treturn this;\n\t}\n\n\t// Public API\n\t@SuppressWarnings({\"WeakerAccess\", \"UnusedReturnValue\"})\n\tpublic OSCSerializerAndParserBuilder unregisterArgumentHandler(final char typeIdentifier) {\n\n\t\tidentifierToType.remove(typeIdentifier);\n\t\treturn this;\n\t}\n}", "public class OSCSerializeException extends Exception {\n\n\tpublic OSCSerializeException() {\n\t\tsuper();\n\t}\n\n\tpublic OSCSerializeException(final String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic OSCSerializeException(final String message, final Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic OSCSerializeException(final Throwable cause) {\n\t\tsuper(cause);\n\t}\n}", "public interface Transport {\n\n\t/**\n\t * Converts and sends an OSC packet (message or bundle) to the remote address.\n\t * @param packet the bundle or message to be converted and sent\n\t * @throws IOException if we run out of memory while converting,\n\t * or a socket I/O error occurs while sending\n\t * @throws OSCSerializeException if the packet fails to serialize\n\t */\n\tvoid send(final OSCPacket packet) throws IOException, OSCSerializeException;\n\n\t/**\n\t * Receive an OSC packet.\n\t * @return the packet received\n\t * @throws IOException if an I/O error occurs while trying to read from the\n\t * @throws OSCParseException if the packet fails to parse\n\t * channel\n\t */\n\tOSCPacket receive() throws IOException, OSCParseException;\n\n\tboolean isBlocking();\n\n\tvoid connect() throws IOException;\n\n\tvoid disconnect() throws IOException;\n\n\tboolean isConnected();\n\n\t/**\n\t * Close the socket and free-up resources.\n\t * It is recommended that clients call this when they are done with the\n\t * port.\n\t * @throws IOException If an I/O error occurs\n\t */\n\tvoid close() throws IOException;\n}", "public class OSCDatagramChannel extends SelectableChannel {\n\n\tprivate final DatagramChannel underlyingChannel;\n\tprivate final OSCParser parser;\n\tprivate final OSCSerializerAndParserBuilder serializerBuilder;\n\n\tpublic OSCDatagramChannel(\n\t\t\tfinal DatagramChannel underlyingChannel,\n\t\t\tfinal OSCSerializerAndParserBuilder serializerAndParserBuilder\n\t\t\t)\n\t{\n\t\tthis.underlyingChannel = underlyingChannel;\n\t\tOSCParser tmpParser = null;\n\t\tif (serializerAndParserBuilder != null) {\n\t\t\ttmpParser = serializerAndParserBuilder.buildParser();\n\t\t}\n\t\tthis.parser = tmpParser;\n\t\tthis.serializerBuilder = serializerAndParserBuilder;\n\t}\n\n\tpublic OSCPacket read(final ByteBuffer buffer) throws IOException, OSCParseException {\n\n\t\tboolean completed = false;\n\t\tOSCPacket oscPacket;\n\t\ttry {\n\t\t\tbegin();\n\n\t\t\tbuffer.clear();\n\t\t\t// NOTE From the doc of `read()` and `receive()`:\n\t\t\t// \"If there are fewer bytes remaining in the buffer\n\t\t\t// than are required to hold the datagram\n\t\t\t// then the remainder of the datagram is silently discarded.\"\n\t\t\tif (underlyingChannel.isConnected()) {\n\t\t\t\tunderlyingChannel.read(buffer);\n\t\t\t} else {\n\t\t\t\tunderlyingChannel.receive(buffer);\n\t\t\t}\n//\t\t\tfinal int readBytes = buffer.position();\n//\t\t\tif (readBytes == buffer.capacity()) {\n//\t\t\t\t// TODO In this case it is very likely that the buffer was actually too small, and the remainder of the datagram/packet was silently discarded. We might want to give a warning, like throw an exception in this case, but whether this happens should probably be user configurable.\n//\t\t\t}\n\t\t\tbuffer.flip();\n\t\t\tif (buffer.limit() == 0) {\n\t\t\t\tthrow new OSCParseException(\"Received a packet without any data\", buffer);\n\t\t\t} else {\n\t\t\t\toscPacket = parser.convert(buffer);\n\t\t\t\tcompleted = true;\n\t\t\t}\n\t\t} finally {\n\t\t\tend(completed);\n\t\t}\n\n\t\treturn oscPacket;\n\t}\n\n\tpublic void send(final ByteBuffer buffer, final OSCPacket packet, final SocketAddress remoteAddress) throws IOException, OSCSerializeException {\n\n\t\tboolean completed = false;\n\t\ttry {\n\t\t\tbegin();\n\n\t\t\tfinal OSCSerializer serializer = serializerBuilder.buildSerializer(new BufferBytesReceiver(buffer));\n\t\t\tbuffer.rewind();\n\t\t\tserializer.write(packet);\n\t\t\tbuffer.flip();\n\t\t\tif (underlyingChannel.isConnected()) {\n\t\t\t\tunderlyingChannel.write(buffer);\n\t\t\t} else if (remoteAddress == null) {\n\t\t\t\tthrow new IllegalStateException(\"Not connected and no remote address is given\");\n\t\t\t} else {\n\t\t\t\tunderlyingChannel.send(buffer, remoteAddress);\n\t\t\t}\n\t\t\tcompleted = true;\n\t\t} finally {\n\t\t\tend(completed);\n\t\t}\n\t}\n\n\tpublic void write(final ByteBuffer buffer, final OSCPacket packet) throws IOException, OSCSerializeException {\n\n\t\tboolean completed = false;\n\t\ttry {\n\t\t\tbegin();\n\t\t\tif (!underlyingChannel.isConnected()) {\n\t\t\t\tthrow new IllegalStateException(\"Either connect the channel or use write()\");\n\t\t\t}\n\t\t\tsend(buffer, packet, null);\n\t\t\tcompleted = true;\n\t\t} finally {\n\t\t\tend(completed);\n\t\t}\n\t}\n\n\t@Override\n\tpublic SelectorProvider provider() {\n\t\treturn underlyingChannel.provider();\n\t}\n\n\t@Override\n\tpublic boolean isRegistered() {\n\t\treturn underlyingChannel.isRegistered();\n\t}\n\n\t@Override\n\tpublic SelectionKey keyFor(final Selector sel) {\n\t\treturn underlyingChannel.keyFor(sel);\n\t}\n\n\t@Override\n\tpublic SelectionKey register(final Selector sel, final int ops, final Object att) throws ClosedChannelException {\n\t\treturn underlyingChannel.register(sel, ops, att);\n\t}\n\n\t@Override\n\tpublic SelectableChannel configureBlocking(final boolean block) throws IOException {\n\t\treturn underlyingChannel.configureBlocking(block);\n\t}\n\n\t@Override\n\tpublic boolean isBlocking() {\n\t\treturn underlyingChannel.isBlocking();\n\t}\n\n\t@Override\n\tpublic Object blockingLock() {\n\t\treturn underlyingChannel.blockingLock();\n\t}\n\n\t@Override\n\tprotected void implCloseChannel() throws IOException {\n\t\t// XXX is this ok?\n\t\tunderlyingChannel.close();\n\t}\n\n\t@Override\n\tpublic int validOps() {\n\t\treturn underlyingChannel.validOps();\n\t}\n}" ]
import com.illposed.osc.LibraryInfo; import com.illposed.osc.OSCPacket; import com.illposed.osc.OSCParseException; import com.illposed.osc.OSCSerializerAndParserBuilder; import com.illposed.osc.OSCSerializeException; import com.illposed.osc.transport.Transport; import com.illposed.osc.transport.channel.OSCDatagramChannel; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel;
// SPDX-FileCopyrightText: 2004-2019 C. Ramakrishnan / Illposed Software // SPDX-FileCopyrightText: 2021 Robin Vobruba <hoijui.quaero@gmail.com> // // SPDX-License-Identifier: BSD-3-Clause package com.illposed.osc.transport.udp; /** * A {@link Transport} implementation for sending and receiving OSC packets over * a network via UDP. */ public class UDPTransport implements Transport { /** * Buffers were 1500 bytes in size, but were increased to 1536, as this * is a common MTU, and then increased to 65507, as this is the maximum * incoming datagram data size. */ public static final int BUFFER_SIZE = 65507; private final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); private final SocketAddress local; private final SocketAddress remote; private final DatagramChannel channel; private final OSCDatagramChannel oscChannel; public UDPTransport( final SocketAddress local, final SocketAddress remote) throws IOException { this(local, remote, new OSCSerializerAndParserBuilder()); } public UDPTransport( final SocketAddress local, final SocketAddress remote, final OSCSerializerAndParserBuilder serializerAndParserBuilder) throws IOException { this.local = local; this.remote = remote; final DatagramChannel tmpChannel; if ((local instanceof InetSocketAddress) && LibraryInfo.hasStandardProtocolFamily()) { final InetSocketAddress localIsa = (InetSocketAddress) local; final InetSocketAddress remoteIsa = (InetSocketAddress) remote; final Class<?> localClass = localIsa.getAddress().getClass(); final Class<?> remoteClass = remoteIsa.getAddress().getClass(); if (!localClass.equals(remoteClass)) { throw new IllegalArgumentException( "local and remote addresses are not of the same family" + " (IP v4 vs v6)"); } if (localIsa.getAddress() instanceof Inet4Address) { tmpChannel = DatagramChannel.open(StandardProtocolFamily.INET); } else if (localIsa.getAddress() instanceof Inet6Address) { tmpChannel = DatagramChannel.open(StandardProtocolFamily.INET6); } else { throw new IllegalArgumentException( "Unknown address type: " + localIsa.getAddress().getClass().getCanonicalName()); } } else { tmpChannel = DatagramChannel.open(); } this.channel = tmpChannel; if (LibraryInfo.hasStandardProtocolFamily()) { this.channel.setOption(StandardSocketOptions.SO_SNDBUF, BUFFER_SIZE); // NOTE So far, we never saw an issue with the receive-buffer size, // thus we leave it at its default. this.channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); this.channel.setOption(StandardSocketOptions.SO_BROADCAST, true); } else { this.channel.socket().setSendBufferSize(BUFFER_SIZE); // NOTE So far, we never saw an issue with the receive-buffer size, // thus we leave it at its default. this.channel.socket().setReuseAddress(true); this.channel.socket().setBroadcast(true); } this.channel.socket().bind(local); this.oscChannel = new OSCDatagramChannel(channel, serializerAndParserBuilder); } @Override public void connect() throws IOException { if (remote == null) { throw new IllegalStateException( "Can not connect a socket without a remote address specified" ); } channel.connect(remote); } @Override public void disconnect() throws IOException { channel.disconnect(); } @Override public boolean isConnected() { return channel.isConnected(); } /** * Close the socket and free-up resources. * It is recommended that clients call this when they are done with the port. * @throws IOException If an I/O error occurs on the channel */ @Override public void close() throws IOException { channel.close(); } @Override public void send(final OSCPacket packet) throws IOException, OSCSerializeException { oscChannel.send(buffer, packet, remote); } @Override
public OSCPacket receive() throws IOException, OSCParseException {
2
jeperon/freqtrade-java
src/main/java/ch/urbanfox/freqtrade/telegram/command/ForceSellCommandHandler.java
[ "@Component\npublic class FreqTradeMainRunner {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(FreqTradeMainRunner.class);\n\n private State state = State.RUNNING;\n\n @Autowired\n private FreqTradeProperties properties;\n\n @Autowired\n private AnalyzeService analyzeService;\n\n @Autowired\n private FreqTradeExchangeService exchangeService;\n\n @Autowired\n private TradeService tradeService;\n\n @Autowired\n private TelegramService telegramService;\n\n /**\n * Queries the persistence layer for open trades and handles them, otherwise a new trade is created.\n */\n private void process() {\n try {\n // Query trades from persistence layer\n List<TradeEntity> trades = tradeService.findAllOpenTrade();\n if (trades.size() < properties.getMaxOpenTrades()) {\n // Create entity and execute trade\n Optional<TradeEntity> trade = createTrade(properties.getStakeAmount(), \"bittrex\");\n if (trade.isPresent()) {\n tradeService.save(trade.get());\n } else {\n LOGGER.info(\"Got no buy signal...\");\n }\n }\n\n for (TradeEntity trade : trades) {\n // Check if there is already an open order for this trade\n List<LimitOrder> orders = exchangeService.getOpenOrders(new CurrencyPair(trade.getPair()));\n orders = orders.stream()\n .filter(o -> Objects.equals(o.getId(), trade.getOpenOrderId()))\n .collect(Collectors.toList());\n if (!orders.isEmpty()) {\n LOGGER.info(\"There is an open order for: {}\", orders.get(0));\n } else {\n // Update state\n trade.setOpenOrderId(null);\n tradeService.save(trade);\n\n // Check if this trade can be closed\n if (!closeTradeIfFulfilled(trade)) {\n // Check if we can sell our current pair\n handleTrade(trade);\n }\n }\n }\n } catch (IOException | TelegramApiException e) {\n LOGGER.warn(\"Error in process\", e);\n }\n }\n\n /**\n * Checks if the trade is closable, and if so it is being closed.\n *\n * @param trade Trade\n * @return true if trade has been closed else False\n */\n private boolean closeTradeIfFulfilled(TradeEntity trade) {\n // If we don't have an open order and the close rate is already set,\n // we can close this trade.\n if (Objects.nonNull(trade.getCloseProfit())\n && Objects.nonNull(trade.getCloseDate())\n && Objects.nonNull(trade.getCloseRate())\n && Objects.isNull(trade.getOpenOrderId())) {\n trade.setOpen(false);\n tradeService.save(trade);\n LOGGER.info(\"No open orders found and trade is fulfilled. Marking {} as closed ...\", trade);\n return true;\n }\n return false;\n }\n\n /**\n * Executes a sell for the given trade and current rate\n *\n * @param trade Trade instance\n * @param currentRate current rate\n *\n * @throws IOException if any I/O error occurs while contacting the exchange\n * @throws TelegramApiException if any error occur while using the Telegram API\n */\n private void executeSell(TradeEntity trade, BigDecimal currentRate) throws IOException, TelegramApiException {\n // Get available balance\n String currency = trade.getPair().split(\"/\")[1];\n BigDecimal balance = exchangeService.getBalance(Currency.getInstance(currency));\n List<CurrencyPair> whitelist = properties.getPairWhitelist();\n\n BigDecimal profit = tradeService.executeSellOrder(trade, currentRate, balance);\n whitelist.add(new CurrencyPair(trade.getPair()));\n String message = String.format(\"*%s:* Selling [%s](%s) at rate `%s (profit: %s%%)`\",\n trade.getExchange(),\n trade.getPair(),\n exchangeService.getPairDetailUrl(trade.getPair()),\n trade.getCloseRate(),\n profit.round(new MathContext(2)));\n LOGGER.info(message);\n telegramService.sendMessage(message);\n }\n\n /**\n * Based an earlier trade and current price and configuration, decides whether bot should sell\n *\n * @return true if bot should sell at current rate\n */\n private boolean shouldSell(TradeEntity trade, BigDecimal currentRate, LocalDateTime currentTime) {\n BigDecimal currentProfit = currentRate.subtract(trade.getOpenRate()).divide(trade.getOpenRate());\n\n if (Objects.nonNull(properties.getStopLoss()) && currentProfit.compareTo(properties.getStopLoss()) < 0) {\n LOGGER.debug(\"Stop loss hit.\");\n return true;\n }\n\n Set<Map.Entry<Long, BigDecimal>> minimalRois = properties.getMinimalRoi().entrySet();\n List<Pair<Long, BigDecimal>> sortedMinimalRois = minimalRois.stream()\n .map(e -> Pair.of(e.getKey(), e.getValue()))\n .sorted(Comparator.comparing(Pair::getLeft))\n .collect(Collectors.toList());\n for (Pair<Long, BigDecimal> minimalRoi : sortedMinimalRois) {\n Long duration = minimalRoi.getLeft();\n BigDecimal threshold = minimalRoi.getRight();\n // Check if time matches and current rate is above threshold\n Long timeDiff = trade.getOpenDate().until(currentTime, ChronoUnit.SECONDS);\n if (timeDiff > duration && currentProfit.compareTo(threshold) > 0) {\n return true;\n }\n }\n\n LOGGER.debug(\"Threshold not reached. (cur_profit: {}%)\", currentProfit.multiply(BigDecimal.valueOf(100)));\n return false;\n }\n\n /**\n * Sells the current pair if the threshold is reached and updates the trade record.\n *\n * @throws IOException if any I/O error occurs while contacting the exchange\n * @throws TelegramApiException if any error occurs while using Telegram API\n */\n private void handleTrade(TradeEntity trade) throws IOException, TelegramApiException {\n if (!trade.getOpen()) {\n LOGGER.warn(\"attempt to handle closed trade: {}\", trade);\n return;\n }\n\n LOGGER.debug(\"Handling open trade {} ...\", trade);\n\n BigDecimal currentRate = exchangeService.getTicker(new CurrencyPair(trade.getPair())).getBid();\n if (shouldSell(trade, currentRate, LocalDateTime.now())) {\n executeSell(trade, currentRate);\n return;\n }\n }\n\n /**\n * Calculates bid target between current ask price and last price\n */\n private BigDecimal getTargetBid(Ticker ticker) {\n if (ticker.getAsk().compareTo(ticker.getLast()) < 0) {\n return ticker.getAsk();\n }\n\n // Factor with regards to ask price\n BigDecimal balance = BigDecimal.ZERO;\n return ticker.getAsk().add(balance.multiply(ticker.getLast().subtract(ticker.getAsk())));\n }\n\n /**\n * Checks the implemented trading indicator(s) for a randomly picked pair, if one pair triggers the buy_signal a new trade record gets created\n *\n * @param stakeAmount amount of btc to spend\n * @param exchange exchange to use\n *\n * @throws IOException if any I/O error occurs while contacting the exchange\n * @throws TelegramApiException if any error occurs while using Telegram API\n */\n private Optional<TradeEntity> createTrade(BigDecimal stakeAmount, String exchange) throws IOException, TelegramApiException {\n LOGGER.info(\"Creating new trade with stake_amount: {} ...\", stakeAmount);\n List<CurrencyPair> whitelist = properties.getPairWhitelist();\n // Check if stake_amount is fulfilled\n final BigDecimal balance = exchangeService.getBalance(properties.getStakeCurrency());\n if (balance.compareTo(stakeAmount) > 0) {\n LOGGER.info(\"stake amount is not fulfilled (available={}, stake={}, currency={})\", balance,\n properties.getStakeCurrency(), properties.getStakeCurrency());\n return Optional.empty();\n } else {\n LOGGER.debug(\"balance is sufficient: {}, stake: {}, currency: {}\", balance, properties.getStakeAmount(),\n properties.getStakeCurrency());\n }\n\n // Remove currently opened and latest pairs from whitelist\n List<TradeEntity> trades = tradeService.findAllOpenTrade();\n Optional<TradeEntity> latestTrade = tradeService.findLastClosedTrade();\n if (latestTrade.isPresent()) {\n trades.add(latestTrade.get());\n }\n for (TradeEntity trade : trades) {\n if (whitelist.contains(new CurrencyPair(trade.getPair()))) {\n whitelist.remove(new CurrencyPair(trade.getPair()));\n LOGGER.debug(\"Ignoring {} in pair whitelist\", trade.getPair());\n }\n }\n if (whitelist.isEmpty()) {\n LOGGER.info(\"No pair in whitelist\");\n return Optional.empty();\n }\n\n // Pick pair based on StochRSI buy signals\n CurrencyPair pair = null;\n for (CurrencyPair _pair : whitelist) {\n ZonedDateTime minimumDate = ZonedDateTime.now().minusHours(6);\n List<BittrexChartData> rawTickers = exchangeService.fetchRawticker(_pair, minimumDate); \n TimeSeries tickers = new BittrexDataConverter().parseRawTickers(rawTickers);\n \n if (analyzeService.getBuySignal(tickers)) {\n pair = _pair;\n break;\n }\n }\n\n if (pair == null) {\n return Optional.empty();\n }\n\n BigDecimal openRate = getTargetBid(exchangeService.getTicker(pair));\n BigDecimal amount = stakeAmount.divide(openRate);\n String orderId = exchangeService.buy(pair, openRate, amount);\n\n // Create trade entity and return\n String message = String.format(\"*%s:* Buying [%s](%s) at rate `{%s}`\",\n exchange,\n pair,\n exchangeService.getPairDetailUrl(pair.toString()),\n openRate);\n LOGGER.info(message);\n telegramService.sendMessage(message);\n\n TradeEntity trade = new TradeEntity();\n trade.setPair(pair.toString());\n trade.setStakeAmount(stakeAmount);\n trade.setOpenRate(openRate);\n trade.setOpenDate(LocalDateTime.now());\n trade.setAmount(amount);\n trade.setExchange(\"bittrex\");\n trade.setOpenOrderId(orderId);\n trade.setOpen(true);\n return Optional.of(trade);\n }\n\n /**\n * Main function which handles the application state\n *\n * @throws InterruptedException if a sleep time is interrupted\n * @throws TelegramApiException if any error occurs while using Telegram API\n */\n public void main() throws TelegramApiException, InterruptedException {\n\n // Set initial application state\n state = properties.getInitialState();\n\n try {\n State oldState = state;\n LOGGER.info(\"Initial State: {}\", oldState);\n telegramService.sendMessage(String.format(\"*Status:* `%s`\", oldState));\n boolean running = true;\n while (running) {\n State newState = state;\n // Log state transition\n if (newState != oldState) {\n telegramService.sendMessage(String.format(\"*Status:* `%s`\", newState));\n LOGGER.info(\"Changing state to: {}\", newState);\n }\n\n switch (newState) {\n case STOPPED:\n running = false;\n break;\n case RUNNING:\n process();\n // We need to sleep here because otherwise we would run into bittrex rate limit\n Thread.sleep(25 * 1000L);\n break;\n default:\n Thread.sleep(1 * 1000L);\n }\n oldState = newState;\n }\n } catch (RuntimeException e) {\n telegramService.sendMessage(String.format(\"*Status:* Got RuntimeError: ```%n%s%n```\", e.getMessage()));\n LOGGER.error(\"RuntimeError. Trader stopped!\", e);\n } finally {\n telegramService.sendMessage(\"*Status:* `Trader has stopped`\");\n }\n }\n\n public State getState() {\n return state;\n }\n\n public void updateState(State state) {\n this.state = state;\n }\n\n}", "public interface FreqTradeExchangeService {\n\n /**\n * Places a limit buy order.\n *\n * @param pair currency pair\n * @param rate Rate limit for order\n * @param amount The amount to purchase\n * @return orderId of the placed buy order\n *\n * @throws IOException if any error occur while contacting the exchange\n */\n String buy(CurrencyPair pair, BigDecimal rate, BigDecimal amount) throws IOException;\n\n /**\n * Get Ticker for given pair.\n *\n * @param pair Pair as str, format: BTC_ETC\n * @return the ticker\n *\n * @throws IOException if any error occur while contacting the exchange\n */\n Ticker getTicker(CurrencyPair pair) throws IOException;\n\n /**\n * Places a limit sell order.\n *\n * @param pair currency pair\n * @param rate Rate limit for order\n * @param amount The amount to sell\n * @return the order ID\n *\n * @throws IOException if any communication error occur while contacting the\n * exchange\n */\n String sell(CurrencyPair pair, BigDecimal rate, BigDecimal amount) throws IOException;\n\n /**\n * Get all open orders for given pair.\n *\n * @param pair the currency pair\n * @return list of orders\n *\n * @throws IOException if any communication error occur while contacting the\n * exchange\n */\n List<LimitOrder> getOpenOrders(CurrencyPair pair) throws IOException;\n\n /**\n * Returns the market detail url for the given pair\n *\n * @param pair pair as a String, format: BTC_ANT\n * @return url as a string\n */\n String getPairDetailUrl(String pair);\n\n /**\n * Get account balance.\n *\n * @param currency currency as str, format: BTC\n * @return balance\n *\n * @throws IOException if any communication error occur while contacting the\n * exchange\n */\n BigDecimal getBalance(Currency currency) throws IOException;\n\n /**\n * Request ticker data from Bittrex for a given currency pair\n */\n List<BittrexChartData> fetchRawticker(CurrencyPair pair) throws IOException;\n\n /**\n * Request ticker data from Bittrex for a given currency pair\n */\n List<BittrexChartData> fetchRawticker(CurrencyPair pair, ZonedDateTime minimumDate) throws IOException;\n\n}", "public interface TelegramService {\n\n /**\n * Sends a message to the user of the application\n *\n * @param message the content of the message\n * @throws TelegramApiException if any error occurs while using Telegram API\n */\n void sendMessage(String message) throws TelegramApiException;\n\n void sendMessage(String message, String parseMode) throws TelegramApiException;\n\n}", "@Entity\n@Table(name = \"trades\")\npublic class TradeEntity {\n\n @Id\n @GeneratedValue\n private Long id;\n\n @Column(name = \"exchange\", nullable = false)\n private String exchange;\n\n @Column(name = \"pair\", nullable = false)\n private String pair;\n\n @Column(name = \"is_open\", nullable = false)\n private Boolean open = true;\n\n @Column(name = \"open_rate\", nullable = false)\n private BigDecimal openRate;\n\n @Column(name = \"close_rate\")\n private BigDecimal closeRate;\n\n @Column(name = \"close_profit\")\n private BigDecimal closeProfit;\n\n @Column(name = \"stake_amount\", nullable = false)\n private BigDecimal stakeAmount;\n\n @Column(name = \"amount\", nullable = false)\n private BigDecimal amount;\n\n @Column(name = \"open_date\", nullable = false)\n private LocalDateTime openDate;\n\n @Column(name = \"close_date\")\n private LocalDateTime closeDate;\n\n @Column(name = \"open_order_id\")\n private String openOrderId;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getExchange() {\n return exchange;\n }\n\n public void setExchange(String exchange) {\n this.exchange = exchange;\n }\n\n public String getPair() {\n return pair;\n }\n\n public void setPair(String pair) {\n this.pair = pair;\n }\n\n public Boolean getOpen() {\n return open;\n }\n\n public void setOpen(Boolean open) {\n this.open = open;\n }\n\n public BigDecimal getOpenRate() {\n return openRate;\n }\n\n public void setOpenRate(BigDecimal openRate) {\n this.openRate = openRate;\n }\n\n public BigDecimal getCloseRate() {\n return closeRate;\n }\n\n public void setCloseRate(BigDecimal closeRate) {\n this.closeRate = closeRate;\n }\n\n public BigDecimal getCloseProfit() {\n return closeProfit;\n }\n\n public void setCloseProfit(BigDecimal closeProfit) {\n this.closeProfit = closeProfit;\n }\n\n public BigDecimal getStakeAmount() {\n return stakeAmount;\n }\n\n public void setStakeAmount(BigDecimal stakeAmount) {\n this.stakeAmount = stakeAmount;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public LocalDateTime getOpenDate() {\n return openDate;\n }\n\n public void setOpenDate(LocalDateTime openDate) {\n this.openDate = openDate;\n }\n\n public LocalDateTime getCloseDate() {\n return closeDate;\n }\n\n public void setCloseDate(LocalDateTime closeDate) {\n this.closeDate = closeDate;\n }\n\n public String getOpenOrderId() {\n return openOrderId;\n }\n\n public void setOpenOrderId(String openOrderId) {\n this.openOrderId = openOrderId;\n }\n\n @Override\n public String toString() {\n String openSince;\n if (open) {\n openSince = Long.toString(openDate.until(LocalDateTime.now(), ChronoUnit.MINUTES));\n } else {\n openSince = \"closed\";\n }\n\n StringBuilder builder = new StringBuilder(\"Trade(\");\n builder.append(\"id=\").append(id);\n builder.append(\", pair=\").append(pair);\n builder.append(\", amount=\").append(amount);\n builder.append(\", open_rate=\").append(openRate);\n builder.append(\", open_since=\").append(openSince).append(\"minutes\");\n builder.append(\")\");\n return builder.toString();\n }\n\n}", "public interface TradeService {\n\n /**\n * Executes a sell for the given trade and updated the entity.\n *\n * @param trade the trade upon which the sell order was executed\n * @param rate rate to sell for\n * @param amount amount to sell\n * @return current profit as percentage\n *\n * @throws IOException if any error occurs while contacting the exchange for information\n */\n BigDecimal executeSellOrder(TradeEntity trade, BigDecimal rate, BigDecimal amount) throws IOException;\n\n List<TradeEntity> findAllOpenTrade();\n\n List<TradeEntity> findAllClosedTrade();\n\n void save(TradeEntity trade);\n\n List<TradeEntity> findAllOrderById();\n\n Optional<TradeEntity> findOpenTradeById(Long tradeId);\n\n Optional<TradeEntity> findLastClosedTrade();\n\n}", "public enum State {\n\n RUNNING,\n\n SLEEP,\n\n STOPPED\n\n}" ]
import java.math.BigDecimal; import java.math.MathContext; import java.util.Optional; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import ch.urbanfox.freqtrade.FreqTradeMainRunner; import ch.urbanfox.freqtrade.exchange.FreqTradeExchangeService; import ch.urbanfox.freqtrade.telegram.TelegramService; import ch.urbanfox.freqtrade.trade.TradeEntity; import ch.urbanfox.freqtrade.trade.TradeService; import ch.urbanfox.freqtrade.type.State;
package ch.urbanfox.freqtrade.telegram.command; /** * Handler for /forcesell <id> * * Sells the given trade at current price */ @Component public class ForceSellCommandHandler extends AbstractCommandHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ForceSellCommandHandler.class); @Autowired
private FreqTradeMainRunner runner;
0
GhostFlying/PortalWaitingList
app/src/main/java/com/ghostflying/portalwaitinglist/fragment/ReDesignDetailFragment.java
[ "public class MainActivity extends ActionBarActivity\n implements PortalListFragment.OnFragmentInteractionListener{\n private static final String LIST_FRAGMENT_TAG = \"LIST_FRAGMENT\";\n private static final String DETAIL_FRAGMENT_TAG = \"DETAIL_FRAGMENT\";\n\n String account;\n PortalDetail clickedPortal;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n // read all settings from storage.\n SettingUtil.getSettings(this);\n // If account is not set, usually user open this first time\n // turn to AuthIntent.\n if ((account = SettingUtil.getAccount()) == null){\n doAuth();\n }\n setContentView(R.layout.activity_main);\n getFragmentManager()\n .beginTransaction()\n .replace(R.id.content_layout, PortalListFragment.newInstance(), LIST_FRAGMENT_TAG)\n .commit();\n }\n\n private void doAuth() {\n Intent authIntent = new Intent(this, AuthActivity.class);\n authIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);\n startActivity(authIntent);\n }\n\n @Override\n protected void onResume(){\n super.onResume();\n if (account == null){\n if ((account = SettingUtil.getAccount()) == null){\n this.finish();\n }\n }\n }\n\n @Override\n public void onBackPressed() {\n if(getFragmentManager().getBackStackEntryCount() != 0) {\n getFragmentManager().popBackStack();\n } else {\n super.onBackPressed();\n }\n }\n\n @Override\n public void doAuthInActivity() {\n doAuth();\n }\n\n @Override\n public void portalItemClicked(PortalDetail clickedPortal, View clickedView) {\n this.clickedPortal = clickedPortal;\n Intent detail = new Intent(this, DetailActivity.class);\n detail.putExtra(DetailActivity.ARG_CLICKED_PORTAL, clickedPortal);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){\n clickedView.setTransitionName(\"title\");\n ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this, clickedView, \"title\");\n startActivity(detail, options.toBundle());\n return;\n }\n startActivity(detail);\n }\n}", "public class ObservableScrollView extends ScrollView {\n private ArrayList<Callbacks> mCallbacks = new ArrayList<Callbacks>();\n\n public ObservableScrollView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n @Override\n protected void onScrollChanged(int l, int t, int oldl, int oldt) {\n super.onScrollChanged(l, t, oldl, oldt);\n for (Callbacks c : mCallbacks) {\n c.onScrollChanged(l - oldl, t - oldt);\n }\n }\n\n @Override\n public int computeVerticalScrollRange() {\n return super.computeVerticalScrollRange();\n }\n\n public void addCallbacks(Callbacks listener) {\n if (!mCallbacks.contains(listener)) {\n mCallbacks.add(listener);\n }\n }\n\n public static interface Callbacks {\n public void onScrollChanged(int deltaX, int deltaY);\n }\n}", "public class SearchResultLoader extends AsyncTaskLoader<PortalDetail> {\n String messageId;\n PortalDetail mDetail;\n\n public SearchResultLoader(Context context, String messageId){\n super(context);\n this.messageId = messageId;\n }\n\n @Override\n public PortalDetail loadInBackground() {\n PortalEventHelper mHelper = new PortalEventHelper(getContext());\n MailProcessUtil mUtil = MailProcessUtil.getInstance();\n List<PortalEvent> events = mHelper.getEventsByName(messageId);\n // if no matched event, return null.\n if (events.isEmpty())\n return null;\n List<PortalDetail> portals = new ArrayList<>();\n mUtil.mergeEvents(portals, events);\n return portals.get(0);\n }\n\n @Override\n public void deliverResult(PortalDetail detail){\n mDetail = detail;\n if (isStarted())\n super.deliverResult(detail);\n }\n\n @Override\n public void onStartLoading(){\n if (mDetail != null){\n deliverResult(mDetail);\n }\n\n if (takeContentChanged() || mDetail == null){\n forceLoad();\n }\n }\n\n @Override\n protected void onStopLoading() {\n cancelLoad();\n }\n\n @Override\n protected void onReset(){\n super.onReset();\n\n onStopLoading();\n mDetail = null;\n }\n}", "public class PortalDetail implements Comparable<PortalDetail>, Parcelable{\n public static final int PRIORITY_REVIEWED_IN_SHORT_TIME = 4;\n public static final int PRIORITY_WAITING_FOR_REVIEW = 3;\n public static final int PRIORITY_NO_RESPONSE_FOR_LONG_TIME = 2;\n public static final int PRIORITY_REVIEWED_BEFORE_SHORT_TIME = 1;\n\n private static final long ONE_DAY_TIME_IN_MILLISECONDS = 24 * 3600 * 1000;\n private static final long DEFAULT_EARLY_TIME_TIME_STAMP = 805176000;\n private String name;\n private List<PortalEvent> events;\n\n /**\n * Construct method to create a new instance of PortalDetail.\n * @param event the first event\n */\n public PortalDetail(PortalEvent event){\n events = new ArrayList<PortalEvent>();\n addEvent(event);\n name = event.portalName;\n }\n\n /**\n * Construct method to create a new instance of PortalDetail.\n * @param in the parcel.\n */\n private PortalDetail(Parcel in){\n events = new ArrayList<>();\n in.readTypedList(events, PortalEvent.CREATOR);\n this.name = events.get(0).getPortalName();\n }\n\n /**\n * Add event to the last position of the events.\n * @param event the new event to be added.\n * @return the size after the add action.\n */\n public int addEvent(PortalEvent event){\n events.add(event);\n return events.size();\n }\n\n public String getName(){\n return name;\n }\n\n /**\n * Get the image url if exist.\n * @return the url if exist, otherwise null.\n */\n public String getImageUrl(){\n for(PortalEvent event : events){\n if (event instanceof SubmissionEvent)\n return ((SubmissionEvent) event).getPortalImageUrl();\n }\n return null;\n }\n\n /**\n * Get the address if exist.\n * @return the address if exist, otherwise null.\n */\n public String getAddress(){\n for (PortalEvent event : events)\n if (event.getPortalAddress() != null)\n return event.getPortalAddress();\n return null;\n }\n\n /**\n * Get the address url if exist.\n * @return the address if exist, otherwise null.\n */\n public String getAddressUrl(){\n for (PortalEvent event : events)\n if (event.getPortalAddressUrl() != null)\n return event.getPortalAddressUrl();\n return null;\n }\n\n public List<PortalEvent> getEvents(){\n return events;\n }\n\n /**\n * Override to achieve the desc sort by last update date.\n * @param another {@inheritDoc}\n * @return a negative int as the instance is more than another,\n * a positive int as the instance is less than another,\n * 0 when they are equal.\n */\n @Override\n public int compareTo(PortalDetail another) {\n return this.getLastUpdated().compareTo(another.getLastUpdated());\n }\n\n /**\n * Get the last update date of this portal\n * @return the newest event's update date.\n */\n public Date getLastUpdated(){\n return events.get(events.size() - 1).date;\n }\n\n /**\n * Get the last proposed event's date of this portal.\n * @return the newest proposed event' update date, if there are no proposed event,\n * return default date.\n */\n public Date getLastProposedUpdated(){\n for (int i = events.size() - 1; i >= 0; i--){\n if (events.get(i).getOperationResult() == PortalEvent.OperationResult.PROPOSED)\n return events.get(i).getDate();\n }\n return new Date(DEFAULT_EARLY_TIME_TIME_STAMP);\n }\n\n /**\n * Check if the portal edit/submit reviewed by NIA.\n * @return true if it is reviewed, otherwise false.\n */\n public boolean isReviewed(){\n return events.get(events.size() - 1).getOperationResult() != PortalEvent.OperationResult.PROPOSED;\n }\n\n /**\n * Check if the portal edit/submit has no response for a long time.\n * @return true if it has no response for a long time, otherwise false.\n */\n public boolean isNoResponseForLongTime(){\n if ((!isReviewed())\n && (new Date().getTime() - getLastUpdated().getTime()) >\n ONE_DAY_TIME_IN_MILLISECONDS * SettingUtil.getLongTime())\n return true;\n else\n return false;\n }\n\n /**\n * Check if the portal edit/submit reviewed in a short time.\n * @return true if it is reviewed in a short time, otherwise false.\n */\n public boolean isReviewedInShortTime(){\n return isReviewed() && isUpdatedInShortTime();\n }\n\n /**\n * Check if the portal edit/submit reviewed before a short time.\n * @return true if it is reviewed before a short time, otherwise false.\n */\n public boolean isReviewedBeforeShortTime(){\n return isReviewed() && (!isUpdatedInShortTime());\n }\n\n private boolean isUpdatedInShortTime(){\n return (new Date().getTime() - getLastUpdated().getTime()) <\n ONE_DAY_TIME_IN_MILLISECONDS * SettingUtil.getShortTime();\n }\n\n /**\n * Get the priority to use in smart order.\n * @return the order priority.\n */\n public int getOrderPrior(){\n if (isNoResponseForLongTime())\n return PRIORITY_NO_RESPONSE_FOR_LONG_TIME;\n else if (!isReviewed())\n return PRIORITY_WAITING_FOR_REVIEW;\n else if (isReviewedBeforeShortTime())\n return PRIORITY_REVIEWED_BEFORE_SHORT_TIME;\n else\n return PRIORITY_REVIEWED_IN_SHORT_TIME;\n }\n\n /**\n * Check if the portal edit/submit ever accepted by NIA.\n * If there is any accept event for the portal, it will be deal as accepted.\n * @return true if accepted, otherwise false.\n */\n public boolean isEverAccepted(){\n for (PortalEvent eachEvent : events){\n if (eachEvent.getOperationResult() == PortalEvent.OperationResult.ACCEPTED)\n return true;\n }\n return false;\n }\n\n /**\n * Check if the portal edit/submit ever rejected by NIA.\n * If there is any rejected event for the portal, it will be deal as rejected.\n * @return true if rejected, otherwise false.\n */\n public boolean isEverRejected(){\n for (PortalEvent eachEvent : events){\n if (eachEvent.getOperationResult() == PortalEvent.OperationResult.REJECTED\n || eachEvent.getOperationResult() == PortalEvent.OperationResult.DUPLICATE)\n return true;\n }\n return false;\n }\n\n /**\n * Check if the last operation for this portal is accepted by NIA.\n * @return true if accepted, otherwise false.\n */\n public boolean isAccepted(){\n return events.get(events.size() - 1).getOperationResult() == PortalEvent.OperationResult.ACCEPTED;\n }\n\n /**\n * Check if the portal edit/submit rejected by NIA.\n * @return true if rejected, otherwise false.\n */\n public boolean isRejected(){\n return events.get(events.size() - 1).getOperationResult() == PortalEvent.OperationResult.REJECTED\n || events.get(events.size() - 1).getOperationResult() == PortalEvent.OperationResult.DUPLICATE;\n }\n\n /**\n * Check if the portal has submission event.\n * @return true if there is one submission event at least, otherwise false.\n */\n public boolean hasSubmission(){\n for (PortalEvent event : events){\n if (event.getOperationType() == PortalEvent.OperationType.SUBMISSION)\n return true;\n }\n return false;\n }\n\n /**\n * Check if the portal has edit/invalid event.\n * @return true if there is one edit/invalid event at least, otherwise false.\n */\n public boolean hasEdit(){\n for (PortalEvent event : events){\n if (event.getOperationType() == PortalEvent.OperationType.EDIT\n || event.getOperationType() == PortalEvent.OperationType.INVALID)\n return true;\n }\n return false;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeTypedList(events);\n }\n\n public static final Creator<PortalDetail> CREATOR\n = new Creator<PortalDetail>(){\n @Override\n public PortalDetail createFromParcel(Parcel source) {\n return new PortalDetail(source);\n }\n\n @Override\n public PortalDetail[] newArray(int size) {\n return new PortalDetail[size];\n }\n };\n}", "public abstract class PortalEvent implements Comparable<PortalEvent>, Parcelable{\n String portalName;\n OperationResult operationResult;\n Date date;\n String portalAddress;\n String portalAddressUrl;\n // The message's id related to this event, store to avoid duplicate when update.\n String messageId;\n\n public PortalEvent(String portalName,\n OperationResult operationResult,\n Date date,\n String messageId){\n this.portalName = portalName;\n this.operationResult = operationResult;\n this.date = date;\n this.messageId = messageId;\n }\n\n protected PortalEvent(Parcel in){\n portalName = in.readString();\n operationResult = OperationResult.values()[in.readInt()];\n date = new Date(in.readLong());\n portalAddress = (String)in.readValue(String.class.getClassLoader());\n portalAddressUrl = (String)in.readValue(String.class.getClassLoader());\n messageId = in.readString();\n }\n\n public String getPortalName() {\n return portalName;\n }\n\n public abstract OperationType getOperationType();\n\n public OperationResult getOperationResult() {\n return operationResult;\n }\n\n public Date getDate() {\n return date;\n }\n\n public String getMessageId(){\n return messageId;\n }\n\n public String getPortalAddress(){\n return portalAddress;\n }\n\n public String getPortalAddressUrl(){\n return portalAddressUrl;\n }\n\n @Override\n public int compareTo(PortalEvent another) {\n return this.date.compareTo(another.getDate());\n }\n\n public enum OperationType{\n SUBMISSION, EDIT, INVALID\n }\n\n public enum OperationResult{\n PROPOSED, ACCEPTED, REJECTED, DUPLICATE\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeInt(getOperationType().ordinal());\n out.writeString(portalName);\n out.writeInt(operationResult.ordinal());\n out.writeLong(date.getTime());\n out.writeValue(portalAddress);\n out.writeValue(portalAddressUrl);\n out.writeString(messageId);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Creator<PortalEvent> CREATOR\n = new Creator<PortalEvent>() {\n @Override\n public PortalEvent createFromParcel(Parcel source) {\n OperationType type = OperationType.values()[source.readInt()];\n switch (type){\n case EDIT:\n return new EditEvent(source);\n case INVALID:\n return new InvalidEvent(source);\n case SUBMISSION:\n default:\n return new SubmissionEvent(source);\n }\n }\n\n @Override\n public PortalEvent[] newArray(int size) {\n return new PortalEvent[0];\n }\n };\n}", "public class SettingUtil {\n static final String SORT_ORDER_NAME = \"SortOrder\";\n static final String RESULT_FILTER_METHOD_NAME = \"FilterMethod\";\n static final String ACCOUNT_NAME = \"account\";\n static final String IF_SHOW_IMAGES_NAME = \"IfShowImages\";\n static final String SHORT_TIME_NAME = \"ShortTime\";\n static final String LONG_TIME_NAME = \"LongTime\";\n static final String IF_INVERSE_WAITING_IN_SMART_NAME = \"IfInverseWaitingInSmart\";\n static final String FORCE_CHINESE_NAME = \"ForceChinese\";\n static final String TYPE_FILTER_METHOD_NAME = \"TypeFilterMethod\";\n static final String SHOW_STATUS_IN_LIST_NAME = \"ShowStatusInList\";\n static final boolean DEFAULT_IF_SHOW_IMAGES = true;\n static final int DEFAULT_SHORT_TIME = 7;\n static final int DEFAULT_LONG_TIME = 365;\n static final boolean DEFAULT_IF_INVERSE_WAITING_IN_SMART = false;\n static final boolean DEFAULT_FORCE_CHINESE = false;\n static final int DEFAULT_TYPE_FILTER_METHOD = 0;\n static final boolean DEFAULT_SHOW_STATUS_IN_LIST = false;\n private static SharedPreferences options;\n private static Observer settingObserver;\n\n /**\n * Get shared Preferences.\n * @param context the context.\n */\n public static void getSettings(Context context){\n createSharedPreferences(context);\n }\n\n /**\n * Get the setting account.\n * @return account.\n */\n public static String getAccount(){\n return options.getString(ACCOUNT_NAME, null);\n }\n\n /**\n * Set the setting account.\n * @param account the account to set.\n */\n public static void setAccount(String account){\n options.edit()\n .putString(ACCOUNT_NAME, account)\n .apply();\n }\n\n /**\n * Get the setting filterMethod.\n * @return filterMethod.\n */\n public static ResultFilterMethod getResultFilterMethod(){\n return ResultFilterMethod.values()[\n options.getInt(RESULT_FILTER_METHOD_NAME,\n ResultFilterMethod.EVERYTHING.ordinal())];\n }\n\n /**\n * Set the setting filterMethod.\n * @param resultFilterMethod filterMethod to be set.\n */\n public static void setResultFilterMethod(ResultFilterMethod resultFilterMethod){\n if (resultFilterMethod != getResultFilterMethod()){\n options.edit().putInt(RESULT_FILTER_METHOD_NAME, resultFilterMethod.ordinal()).apply();\n notifyChange(resultFilterMethod);\n }\n }\n\n /**\n * Get the setting sortOrder.\n * @return sortOrder.\n */\n public static SortOrder getSortOrder(){\n return SortOrder.values()[\n options.getInt(SORT_ORDER_NAME, SortOrder.SMART_ORDER.ordinal())];\n }\n\n /**\n * Set the setting sortOrder.\n * @param sortOrder the sortOrder to set.\n */\n public static void setSortOrder(SortOrder sortOrder){\n if (sortOrder != getSortOrder()){\n options.edit().putInt(SORT_ORDER_NAME, sortOrder.ordinal()).apply();\n notifyChange(sortOrder);\n }\n }\n\n /**\n * Get the setting ifShowImages.\n * @return true if the images should be showed, otherwise false.\n */\n public static Boolean getIfShowImages(){\n return options.getBoolean(IF_SHOW_IMAGES_NAME, DEFAULT_IF_SHOW_IMAGES);\n }\n\n /**\n * Set the setting ifShowImagesName\n * @param ifShowImages the ifShowImagesName to set.\n */\n public static void setIfShowImages(boolean ifShowImages){\n options.edit()\n .putBoolean(IF_SHOW_IMAGES_NAME, ifShowImages)\n .apply();\n }\n\n /**\n * Get the setting short time.\n * @return the short time saved.\n */\n public static int getShortTime(){\n return options.getInt(SHORT_TIME_NAME, DEFAULT_SHORT_TIME);\n }\n\n /**\n * Set the setting short time.\n * @param shortTime the short time to set.\n */\n public static void setShortTime(int shortTime){\n options.edit()\n .putInt(SHORT_TIME_NAME, DEFAULT_SHORT_TIME)\n .apply();\n }\n\n /**\n * Get the setting long time.\n * @return the long time saved.\n */\n public static int getLongTime(){\n return options.getInt(LONG_TIME_NAME, DEFAULT_LONG_TIME);\n }\n\n /**\n * Set the setting long time.\n * @param longTime the long time to set.\n */\n public static void setLongTime(int longTime){\n options.edit()\n .putInt(LONG_TIME_NAME, longTime)\n .apply();\n }\n\n /**\n * Get the setting if inverse waiting list in smart order.\n * @return true if inverse, otherwise false.\n */\n public static boolean getIfInverseWaitingInSmart(){\n return options.getBoolean(IF_INVERSE_WAITING_IN_SMART_NAME, DEFAULT_IF_INVERSE_WAITING_IN_SMART);\n }\n\n /**\n * Set the setting if inverse waiting list in smart order.\n * @param ifInverseWaitingInSmart the value to set.\n */\n public static void setIfInverseWaitingInSmart(boolean ifInverseWaitingInSmart){\n options.edit()\n .putBoolean(IF_INVERSE_WAITING_IN_SMART_NAME, ifInverseWaitingInSmart)\n .apply();\n }\n\n /**\n * Get the setting if treat all names of portals as Chinese..\n * @return true if treat as Chinese, otherwise false.\n */\n public static boolean getForceChinese(){\n return options.getBoolean(FORCE_CHINESE_NAME, DEFAULT_FORCE_CHINESE);\n }\n\n /**\n * Set the setting if treat all names of portals as Chinese..\n * @param forceChinese the value to set.\n */\n public static void setForceChinese(boolean forceChinese){\n options.edit()\n .putBoolean(FORCE_CHINESE_NAME, forceChinese)\n .apply();\n }\n\n /**\n * Get the setting type filter method.\n * @return the type filter method.\n */\n public static TypeFilterMethod getTypeFilterMethod(){\n return TypeFilterMethod.values()[\n options.getInt(TYPE_FILTER_METHOD_NAME, DEFAULT_TYPE_FILTER_METHOD)\n ];\n }\n\n /**\n * Set the setting type filter method.\n * @param typeFilterMethod the method set to filter by type.\n */\n public static void setTypeFilterMethod(TypeFilterMethod typeFilterMethod){\n if (typeFilterMethod != getTypeFilterMethod()){\n options.edit()\n .putInt(TYPE_FILTER_METHOD_NAME, typeFilterMethod.ordinal())\n .apply();\n notifyChange(typeFilterMethod);\n }\n }\n\n /**\n * Get the setting if show status in list.\n * @return the setting show status in list..\n */\n public static boolean getShowStatusInList(){\n return options.getBoolean(SHOW_STATUS_IN_LIST_NAME, DEFAULT_SHOW_STATUS_IN_LIST);\n }\n\n /**\n * Set the setting show status in list.\n * @param showStatusInList the value to set.\n */\n public static void setShowStatusInList(boolean showStatusInList){\n options.edit()\n .putBoolean(SHOW_STATUS_IN_LIST_NAME, showStatusInList)\n .apply();\n }\n\n /**\n * Create the SharedPreferences.\n * @param context the context.\n */\n private static void createSharedPreferences(Context context){\n if (options == null)\n options = context.getSharedPreferences(context.getString(R.string.preference_name), Context.MODE_PRIVATE);\n }\n\n public static void registerObserver(Observer observer){\n settingObserver = observer;\n }\n\n public static void unregisterObserver(){\n settingObserver = null;\n }\n\n private static void notifyChange(Object data){\n if (settingObserver != null)\n settingObserver.update(null, data);\n }\n\n /**\n * Stay for debug.\n * @param context the context.\n */\n public static void clearSetting(Context context){\n createSharedPreferences(context);\n options.edit().clear().commit();\n }\n\n public static enum SortOrder{\n LAST_DATE_ASC,\n LAST_DATE_DESC,\n SMART_ORDER,\n ALPHABETICAL,\n PROPOSED_DATE_ASC,\n PROPOSED_DATE_DESC\n }\n\n public static enum ResultFilterMethod {\n EVERYTHING, ACCEPTED, REJECTED, WAITING\n }\n\n public static enum TypeFilterMethod {\n ALL, SUBMISSION, EDIT\n }\n}" ]
import android.app.Fragment; import android.app.LoaderManager; import android.content.Intent; import android.content.Loader; import android.graphics.Bitmap; import android.graphics.Canvas; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.ViewCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ghostflying.portalwaitinglist.MainActivity; import com.ghostflying.portalwaitinglist.ObservableScrollView; import com.ghostflying.portalwaitinglist.R; import com.ghostflying.portalwaitinglist.loader.SearchResultLoader; import com.ghostflying.portalwaitinglist.model.PortalDetail; import com.ghostflying.portalwaitinglist.model.PortalEvent; import com.ghostflying.portalwaitinglist.util.SettingUtil; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import com.squareup.picasso.Picasso; import java.io.File; import java.io.FileOutputStream; import java.text.DateFormat; import java.util.Date;
return fragment; } public ReDesignDetailFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); localDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); mClient = new GoogleApiClient.Builder(getActivity()).addApi(AppIndex.APP_INDEX_API).build(); if (getArguments() != null) { clickedPortal = getArguments().getParcelable(ARG_CLICKED_PORTAL_NAME); firstEventId = getArguments().getString(ARG_FIRST_EVENT_ID); } } @Override public void onStart(){ super.onStart(); if (clickedPortal != null) recordView(); } private void recordView() { mClient.connect(); final String TITLE = clickedPortal.getName(); String messageId = clickedPortal.getEvents().get(0).getMessageId(); appUri = BASE_APP_URI.buildUpon().appendPath(messageId).build(); final Uri WEB_URI = Uri.parse(BASE_WEB_URL + messageId); AppIndex.AppIndexApi.view(mClient, getActivity(), appUri, TITLE, WEB_URI, null); } @Override public void onStop(){ super.onStop(); AppIndex.AppIndexApi.viewEnd(mClient, getActivity(), appUri); mClient.disconnect(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_re_design_detail, container, false); // toolbar mToolbar = (Toolbar)view.findViewById(R.id.detail_toolbar); mToolbar.setTitle(""); ((ActionBarActivity)getActivity()).setSupportActionBar(mToolbar); mToolbar.setNavigationIcon(R.drawable.ic_up); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (firstEventId != null){ startActivity(new Intent(getActivity(), MainActivity.class)); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ getActivity().finishAfterTransition(); } else getActivity().finish(); } }); // remove the elevation to make header unify if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) mToolbar.setElevation(0); mScrollView = (ObservableScrollView)view.findViewById(R.id.scroll_view); mScrollView.addCallbacks(this); // Header mHeaderBox = view.findViewById(R.id.header_portal); mPhotoView = (ImageView)view.findViewById(R.id.portal_photo); mPhotoViewContainer = view.findViewById(R.id.portal_photo_container); mPortalName = (TextView)view.findViewById(R.id.portal_name); mPortalSummary = (TextView)view.findViewById(R.id.portal_status_in_detail); mMaxHeaderElevation = getResources().getDimensionPixelSize( R.dimen.portal_detail_max_header_elevation); // details mDetailsContainer = view.findViewById(R.id.detail_container); mPortalAddress = (TextView)view.findViewById(R.id.portal_address_in_detail); mPortalAddressView = view.findViewById(R.id.portal_address_view_in_detail); mPortalEventListContainer = view.findViewById(R.id.portal_event_list); // set observer for views ViewTreeObserver vto = mScrollView.getViewTreeObserver(); if (vto.isAlive()) { vto.addOnGlobalLayoutListener(mGlobalLayoutListener); } // menu setHasOptionsMenu(true); if (clickedPortal != null) showPortal(clickedPortal); else { getLoaderManager().initLoader(0, null, this); } return view; } private void showPortal(PortalDetail portal){ mPortalName.setText(portal.getName()); mPortalSummary.setText(getSummaryText(portal)); String address = portal.getAddress(); if (address != null){ mPortalAddress.setText(address); } else { mPortalAddressView.setVisibility(View.GONE); } addEventViews(portal, (ViewGroup)mPortalEventListContainer); // photo String photoUrl = portal.getImageUrl();
if (SettingUtil.getIfShowImages() && photoUrl != null && photoUrl.startsWith("http")){
5
NuVotifier/NuVotifier
common/src/main/java/com/vexsoftware/votifier/util/standalone/StandaloneVotifierPlugin.java
[ "public class Vote {\n\n /**\n * The name of the vote service.\n */\n private String serviceName;\n\n /**\n * The username of the voter.\n */\n private String username;\n\n /**\n * The address of the voter.\n */\n private String address;\n\n /**\n * The date and time of the vote.\n */\n private String timeStamp;\n\n private byte[] additionalData;\n\n @Deprecated\n public Vote() {\n }\n\n public Vote(String serviceName, String username, String address, String timeStamp) {\n this.serviceName = serviceName;\n this.username = username;\n this.address = address;\n this.timeStamp = timeStamp;\n this.additionalData = null;\n }\n\n public Vote(String serviceName, String username, String address, String timeStamp, byte[] additionalData) {\n this.serviceName = serviceName;\n this.username = username;\n this.address = address;\n this.timeStamp = timeStamp;\n this.additionalData = additionalData == null ? null : additionalData.clone();\n }\n\n public Vote(Vote vote) {\n this(vote.getServiceName(), vote.getUsername(), vote.getAddress(), vote.getTimeStamp(),\n vote.getAdditionalData() == null ? null : vote.getAdditionalData().clone());\n }\n\n private static String getTimestamp(JsonElement object) {\n try {\n return Long.toString(object.getAsLong());\n } catch (Exception e) {\n return object.getAsString();\n }\n }\n\n public Vote(JsonObject jsonObject) {\n this(jsonObject.get(\"serviceName\").getAsString(),\n jsonObject.get(\"username\").getAsString(),\n jsonObject.get(\"address\").getAsString(),\n getTimestamp(jsonObject.get(\"timestamp\")));\n if (jsonObject.has(\"additionalData\"))\n additionalData = Base64.getDecoder().decode(jsonObject.get(\"additionalData\").getAsString());\n }\n\n @Override\n public String toString() {\n String data;\n if (additionalData == null)\n data = \"null\";\n else\n data = Base64.getEncoder().encodeToString(additionalData);\n\n return \"Vote (from:\" + serviceName + \" username:\" + username\n + \" address:\" + address + \" timeStamp:\" + timeStamp\n + \" additionalData:\" + data + \")\";\n }\n\n /**\n * Sets the serviceName.\n *\n * @param serviceName The new serviceName\n */\n @Deprecated\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n /**\n * Gets the serviceName.\n *\n * @return The serviceName\n */\n public String getServiceName() {\n return serviceName;\n }\n\n /**\n * Sets the username.\n *\n * @param username The new username\n */\n @Deprecated\n public void setUsername(String username) {\n this.username = username;\n }\n\n /**\n * Gets the username.\n *\n * @return The username\n */\n public String getUsername() {\n return username;\n }\n\n /**\n * Sets the address.\n *\n * @param address The new address\n */\n @Deprecated\n public void setAddress(String address) {\n this.address = address;\n }\n\n /**\n * Gets the address.\n *\n * @return The address\n */\n public String getAddress() {\n return address;\n }\n\n /**\n * Sets the time stamp.\n *\n * @param timeStamp The new time stamp\n */\n @Deprecated\n public void setTimeStamp(String timeStamp) {\n this.timeStamp = timeStamp;\n }\n\n /**\n * Gets the time stamp.\n *\n * @return The time stamp\n */\n public String getTimeStamp() {\n return timeStamp;\n }\n\n /**\n * Returns additional data sent with the vote, if it exists.\n *\n * @return Additional data sent with the vote\n */\n public byte[] getAdditionalData() {\n return additionalData == null ? null : additionalData.clone();\n }\n\n public JsonObject serialize() {\n JsonObject ret = new JsonObject();\n ret.addProperty(\"serviceName\", serviceName);\n ret.addProperty(\"username\", username);\n ret.addProperty(\"address\", address);\n ret.addProperty(\"timestamp\", timeStamp);\n if (additionalData != null)\n ret.addProperty(\"additionalData\", Base64.getEncoder().encodeToString(additionalData));\n return ret;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Vote)) return false;\n\n Vote vote = (Vote) o;\n\n if (!serviceName.equals(vote.serviceName)) return false;\n if (!username.equals(vote.username)) return false;\n if (!address.equals(vote.address)) return false;\n if (!timeStamp.equals(vote.timeStamp)) return false;\n return Arrays.equals(additionalData, vote.additionalData);\n }\n\n @Override\n public int hashCode() {\n int result = serviceName.hashCode();\n result = 31 * result + username.hashCode();\n result = 31 * result + address.hashCode();\n result = 31 * result + timeStamp.hashCode();\n return result;\n }\n}", "public class VotifierServerBootstrap {\n private static final boolean USE_EPOLL = Epoll.isAvailable();\n\n private final String host;\n private final int port;\n private final EventLoopGroup bossLoopGroup;\n private final EventLoopGroup eventLoopGroup;\n private final VotifierPlugin plugin;\n private final boolean v1Disable;\n\n private Channel serverChannel;\n\n public VotifierServerBootstrap(String host, int port, VotifierPlugin plugin, boolean v1Disable) {\n this.host = host;\n this.port = port;\n this.plugin = plugin;\n this.v1Disable = v1Disable;\n if (USE_EPOLL) {\n this.bossLoopGroup = new EpollEventLoopGroup(1, createThreadFactory(\"Votifier epoll boss\"));\n this.eventLoopGroup = new EpollEventLoopGroup(3, createThreadFactory(\"Votifier epoll worker\"));\n plugin.getPluginLogger().info(\"Using epoll transport to accept votes.\");\n } else {\n this.bossLoopGroup = new NioEventLoopGroup(1, createThreadFactory(\"Votifier NIO boss\"));\n this.eventLoopGroup = new NioEventLoopGroup(3, createThreadFactory(\"Votifier NIO worker\"));\n plugin.getPluginLogger().info(\"Using NIO transport to accept votes.\");\n }\n }\n\n private static ThreadFactory createThreadFactory(String name) {\n return runnable -> {\n FastThreadLocalThread thread = new FastThreadLocalThread(runnable, name);\n thread.setDaemon(true);\n return thread;\n };\n }\n\n public void start(Consumer<Throwable> error) {\n Objects.requireNonNull(error, \"error\");\n\n VoteInboundHandler voteInboundHandler = new VoteInboundHandler(plugin);\n\n new ServerBootstrap()\n .channel(USE_EPOLL ? EpollServerSocketChannel.class : NioServerSocketChannel.class)\n .group(bossLoopGroup, eventLoopGroup)\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel channel) {\n channel.attr(VotifierSession.KEY).set(new VotifierSession());\n channel.attr(VotifierPlugin.KEY).set(plugin);\n channel.pipeline().addLast(\"greetingHandler\", VotifierGreetingHandler.INSTANCE);\n channel.pipeline().addLast(\"protocolDifferentiator\", new VotifierProtocolDifferentiator(false, !v1Disable));\n channel.pipeline().addLast(\"voteHandler\", voteInboundHandler);\n }\n })\n .bind(host, port)\n .addListener((ChannelFutureListener) future -> {\n if (future.isSuccess()) {\n serverChannel = future.channel();\n plugin.getPluginLogger().info(\"Votifier enabled on socket \" + serverChannel.localAddress() + \".\");\n error.accept(null);\n } else {\n SocketAddress socketAddress = future.channel().localAddress();\n if (socketAddress == null) {\n socketAddress = new InetSocketAddress(host, port);\n }\n plugin.getPluginLogger().error(\"Votifier was not able to bind to \" + socketAddress.toString(), future.cause());\n error.accept(future.cause());\n }\n });\n }\n\n private Bootstrap client() {\n return new Bootstrap()\n .channel(USE_EPOLL ? EpollSocketChannel.class : NioSocketChannel.class)\n .group(eventLoopGroup);\n }\n\n public ProxyForwardingVoteSource createForwardingSource(List<ProxyForwardingVoteSource.BackendServer> backendServers,\n VoteCache voteCache) {\n return new ProxyForwardingVoteSource(plugin, this::client, backendServers, voteCache);\n }\n\n public void shutdown() {\n if (serverChannel != null) {\n try {\n serverChannel.close().syncUninterruptibly();\n } catch (Exception e) {\n plugin.getPluginLogger().error(\"Unable to shutdown server channel\", e);\n }\n }\n eventLoopGroup.shutdownGracefully();\n bossLoopGroup.shutdownGracefully();\n\n try {\n bossLoopGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n eventLoopGroup.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n}", "public class VotifierSession {\n public static final AttributeKey<VotifierSession> KEY = AttributeKey.valueOf(\"votifier_session\");\n private ProtocolVersion version = ProtocolVersion.UNKNOWN;\n private final String challenge;\n private boolean hasCompletedVote = false;\n\n public VotifierSession() {\n challenge = TokenUtil.newToken();\n }\n\n public void setVersion(ProtocolVersion version) {\n if (this.version != ProtocolVersion.UNKNOWN)\n throw new IllegalStateException(\"Protocol version already switched\");\n\n this.version = version;\n }\n\n public ProtocolVersion getVersion() {\n return version;\n }\n\n public String getChallenge() {\n return challenge;\n }\n\n public void completeVote() {\n if (hasCompletedVote)\n throw new IllegalStateException(\"Protocol completed vote twice!\");\n\n hasCompletedVote = true;\n }\n\n public boolean hasCompletedVote() {\n return hasCompletedVote;\n }\n\n public enum ProtocolVersion {\n UNKNOWN(\"unknown\"),\n ONE(\"protocol v1\"),\n TWO(\"protocol v2\"),\n TEST(\"test\");\n\n public final String humanReadable;\n ProtocolVersion(String hr) {\n this.humanReadable = hr;\n }\n }\n}", "public class JavaUtilLogger implements LoggingAdapter {\n\n private final Logger logger;\n\n public JavaUtilLogger(Logger logger) {\n this.logger = logger;\n }\n\n @Override\n public void error(String s) {\n logger.severe(s);\n }\n\n @Override\n public void error(String s, Object... o) {\n logger.log(Level.SEVERE, s, o);\n }\n\n @Override\n public void error(String s, Throwable e, Object... o) {\n LogRecord lr = new LogRecord(Level.SEVERE, s);\n lr.setParameters(o);\n lr.setThrown(e);\n logger.log(lr);\n }\n\n @Override\n public void warn(String s) {\n logger.warning(s);\n }\n\n @Override\n public void warn(String s, Object... o) {\n logger.log(Level.WARNING, s, o);\n }\n\n @Override\n public void info(String s) {\n logger.info(s);\n }\n\n @Override\n public void info(String s, Object... o) {\n logger.log(Level.INFO, s, o);\n }\n}", "public interface LoggingAdapter {\n void error(String s);\n void error(String s, Object... o);\n void error(String s, Throwable e, Object... o);\n\n void warn(String s);\n void warn(String s, Object... o);\n\n void info(String s);\n void info(String s, Object... o);\n}", "public interface VotifierPlugin extends VoteHandler {\n AttributeKey<VotifierPlugin> KEY = AttributeKey.valueOf(\"votifier_plugin\");\n\n Map<String, Key> getTokens();\n\n KeyPair getProtocolV1Key();\n\n LoggingAdapter getPluginLogger();\n\n VotifierScheduler getScheduler();\n\n default boolean isDebug() {\n return false;\n }\n}", "public class ScheduledExecutorServiceVotifierScheduler implements VotifierScheduler {\n private final ScheduledExecutorService service;\n\n public ScheduledExecutorServiceVotifierScheduler(ScheduledExecutorService service) {\n this.service = Objects.requireNonNull(service, \"service\");\n }\n\n @Override\n public ScheduledVotifierTask sync(Runnable runnable) {\n return new ScheduledVotifierTaskWrapper(service.submit(runnable));\n }\n\n @Override\n public ScheduledVotifierTask onPool(Runnable runnable) {\n return new ScheduledVotifierTaskWrapper(service.submit(runnable));\n }\n\n @Override\n public ScheduledVotifierTask delayedSync(Runnable runnable, int delay, TimeUnit unit) {\n return new ScheduledVotifierTaskWrapper(service.schedule(runnable, delay, unit));\n }\n\n @Override\n public ScheduledVotifierTask delayedOnPool(Runnable runnable, int delay, TimeUnit unit) {\n return new ScheduledVotifierTaskWrapper(service.schedule(runnable, delay, unit));\n }\n\n @Override\n public ScheduledVotifierTask repeatOnPool(Runnable runnable, int delay, int repeat, TimeUnit unit) {\n return new ScheduledVotifierTaskWrapper(service.scheduleAtFixedRate(runnable, delay, repeat, unit));\n }\n\n private static class ScheduledVotifierTaskWrapper implements ScheduledVotifierTask {\n private final Future<?> future;\n\n private ScheduledVotifierTaskWrapper(Future<?> future) {\n this.future = future;\n }\n\n @Override\n public void cancel() {\n future.cancel(false);\n }\n }\n}", "public interface VotifierScheduler {\n ScheduledVotifierTask sync(Runnable runnable);\n\n ScheduledVotifierTask onPool(Runnable runnable);\n\n ScheduledVotifierTask delayedSync(Runnable runnable, int delay, TimeUnit unit);\n\n ScheduledVotifierTask delayedOnPool(Runnable runnable, int delay, TimeUnit unit);\n\n ScheduledVotifierTask repeatOnPool(Runnable runnable, int delay, int repeat, TimeUnit unit);\n}" ]
import com.vexsoftware.votifier.model.Vote; import com.vexsoftware.votifier.net.VotifierServerBootstrap; import com.vexsoftware.votifier.net.VotifierSession; import com.vexsoftware.votifier.platform.JavaUtilLogger; import com.vexsoftware.votifier.platform.LoggingAdapter; import com.vexsoftware.votifier.platform.VotifierPlugin; import com.vexsoftware.votifier.platform.scheduler.ScheduledExecutorServiceVotifierScheduler; import com.vexsoftware.votifier.platform.scheduler.VotifierScheduler; import java.net.InetSocketAddress; import java.security.Key; import java.security.KeyPair; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.logging.Logger;
package com.vexsoftware.votifier.util.standalone; public class StandaloneVotifierPlugin implements VotifierPlugin { private final Map<String, Key> tokens; private final VoteReceiver receiver; private final KeyPair v1Key; private final InetSocketAddress bind; private final VotifierScheduler scheduler; private VotifierServerBootstrap bootstrap; public StandaloneVotifierPlugin(Map<String, Key> tokens, VoteReceiver receiver, KeyPair v1Key, InetSocketAddress bind) { this.receiver = receiver; this.bind = bind; this.tokens = Collections.unmodifiableMap(new HashMap<>(tokens)); this.v1Key = v1Key; this.scheduler = new ScheduledExecutorServiceVotifierScheduler(Executors.newScheduledThreadPool(1)); } public void start() { start(o -> {}); } public void start(Consumer<Throwable> error) { if (bootstrap != null) { bootstrap.shutdown(); } this.bootstrap = new VotifierServerBootstrap(bind.getHostString(), bind.getPort(), this, v1Key == null); this.bootstrap.start(error); } @Override public Map<String, Key> getTokens() { return tokens; } @Override public KeyPair getProtocolV1Key() { return v1Key; } @Override public LoggingAdapter getPluginLogger() { return new JavaUtilLogger(Logger.getAnonymousLogger()); } @Override public VotifierScheduler getScheduler() { return scheduler; } @Override
public void onVoteReceived(Vote vote, VotifierSession.ProtocolVersion protocolVersion, String remoteAddress) throws Exception {
2
cjdaly/fold
net.locosoft.fold.channel.fold/src/net/locosoft/fold/channel/fold/internal/FoldChannel.java
[ "public abstract class AbstractChannel implements IChannel, IChannelInternal {\n\n\t//\n\t// IChannel\n\t//\n\n\tprivate String _id;\n\n\tpublic String getChannelId() {\n\t\treturn _id;\n\t}\n\n\tprivate String _description;\n\n\tpublic String getChannelData(String key, String... params) {\n\t\tswitch (key) {\n\t\tcase \"channel.description\":\n\t\t\treturn _description;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic IChannelItemDetails getChannelItemDetails(String itemLabel,\n\t\t\tlong itemOrdinal) {\n\t\treturn null;\n\t}\n\n\t//\n\t// IChannelInternal\n\t//\n\n\tprivate IChannelService _channelService;\n\n\tpublic IChannelService getChannelService() {\n\t\treturn _channelService;\n\t}\n\n\tpublic final void init(String channelId, IChannelService channelService,\n\t\t\tString channelDescription) {\n\t\t_id = channelId;\n\t\t_description = channelDescription;\n\t\t_channelService = channelService;\n\t}\n\n\tpublic void init() {\n\t}\n\n\tpublic void fini() {\n\t}\n\n\tpublic boolean channelSecurity(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws IOException {\n\t\treturn true;\n\t}\n\n\tpublic void channelHttp(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\n\t\tswitch (request.getMethod()) {\n\t\tcase \"GET\":\n\t\t\tchannelHttpGet(request, response);\n\t\t\tbreak;\n\t\tcase \"POST\":\n\t\t\tchannelHttpPost(request, response);\n\t\t\tbreak;\n\t\tcase \"PUT\":\n\t\t\tchannelHttpPut(request, response);\n\t\t\tbreak;\n\t\tcase \"DELETE\":\n\t\t\tchannelHttpDelete(request, response);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprotected void channelHttpGet(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprotected void channelHttpPost(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprotected void channelHttpPut(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprotected void channelHttpDelete(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tchannelHttpNotImplemented(request, response);\n\t}\n\n\tprivate void channelHttpNotImplemented(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tresponse.setContentType(\"text/html\");\n\n\t\tPrintWriter writer = response.getWriter();\n\n\t\tString channelId = getChannelId();\n\t\tString thingName = getChannelData(\"thing\", \"name\");\n\t\twriter.append(\"<html>\\n<head>\\n<title>\");\n\t\twriter.append(\"fold: \" + thingName + \" / \" + channelId);\n\t\twriter.append(\"</title>\\n</head>\\n<body>\\n\");\n\n\t\twriter.append(\"<p>\");\n\t\twriter.append(\"Method \" + request.getMethod() + \" not implemented!\");\n\t\twriter.append(\"</p>\\n\");\n\n\t\twriter.append(\"\\n</body>\\n</html>\\n\");\n\t}\n\n\tpublic final Properties getChannelConfigProperties(\n\t\t\tString propertiesFilePrefix) {\n\t\tString channelConfigFilePath = FoldUtil.getFoldConfigDir()\n\t\t\t\t+ \"/channel/\" + getChannelId() + \"/\" + propertiesFilePrefix\n\t\t\t\t+ \".properties\";\n\t\treturn FoldUtil.loadPropertiesFile(channelConfigFilePath);\n\t}\n\n\tpublic final IProject getChannelProject() {\n\t\ttry {\n\t\t\tIWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace()\n\t\t\t\t\t.getRoot();\n\t\t\tIProject project = workspaceRoot.getProject(getChannelId());\n\t\t\tboolean workspaceStateChange = false;\n\n\t\t\tif (!project.exists()) {\n\t\t\t\tworkspaceStateChange = true;\n\t\t\t\tproject.create(null);\n\t\t\t}\n\n\t\t\tif (!project.isOpen()) {\n\t\t\t\tworkspaceStateChange = true;\n\t\t\t\tproject.open(null);\n\t\t\t}\n\n\t\t\tif (workspaceStateChange) {\n\t\t\t\tworkspaceRoot.getWorkspace().save(true, null);\n\t\t\t}\n\n\t\t\treturn project;\n\t\t} catch (CoreException ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate long _channelNodeId = -1;\n\n\tpublic final long getChannelNodeId() {\n\t\tif (_channelNodeId == -1) {\n\t\t\tINeo4jService neo4jService = Neo4jUtil.getNeo4jService();\n\n\t\t\tICypher cypher = neo4jService\n\t\t\t\t\t.constructCypher(\"MERGE (channel:fold_Channel {fold_channelId : {channelId}}) RETURN ID(channel)\");\n\t\t\tcypher.addParameter(\"channelId\", getChannelId());\n\t\t\tneo4jService.invokeCypher(cypher);\n\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\t\t_channelNodeId = jsonValue.asLong();\n\t\t}\n\t\treturn _channelNodeId;\n\t}\n\n}", "public class ChannelUtil {\n\n\tpublic static IChannelService getChannelService() {\n\t\treturn FoldUtil.getService(IChannelService.class);\n\t}\n}", "public interface IChannel {\n\n\tString getChannelId();\n\n\tString getChannelData(String key, String... params);\n\n\tIChannelItemDetails getChannelItemDetails(String itemLabel, long itemOrdinal);\n\n\tClass<? extends IChannel> getChannelInterface();\n\n}", "public interface IFoldChannel extends IChannel {\n\n\tlong getStartCount();\n\n}", "public abstract class ChannelHeaderFooterHtml extends AbstractChannelHtmlSketch {\n\n\tpublic ChannelHeaderFooterHtml(IChannelInternal channel) {\n\t\tsuper(channel);\n\t}\n\n\tpublic void composeHtmlResponse(HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws ServletException, IOException {\n\t\tresponse.setContentType(\"text/html\");\n\t\tString thingName = getChannel().getChannelService().getChannelData(\n\t\t\t\t\"thing\", \"name\");\n\n\t\tHtmlComposer html = new HtmlComposer(response.getWriter());\n\t\thtml.html_head(\"fold: \" + thingName + \" / \"\n\t\t\t\t+ getChannel().getChannelId());\n\n\t\tcomposeHtmlResponseBody(request, response, html);\n\n\t\thtml.html_body(false);\n\t}\n\n\tprotected abstract void composeHtmlResponseBody(HttpServletRequest request,\n\t\t\tHttpServletResponse response, HtmlComposer html)\n\t\t\tthrows ServletException, IOException;\n}", "public class CounterPropertyNode extends AbstractNodeSketch {\n\n\tpublic CounterPropertyNode(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tprivate long crementCounter(String counterPropertyName, boolean isIncrement) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\n\t\tchar crementOp = isIncrement ? '+' : '-';\n\t\tString cypherText = \"MATCH node WHERE id(node)={nodeId}\"\n\t\t\t\t+ \" SET node.`\" + counterPropertyName + \"`=COALESCE(node.`\"\n\t\t\t\t+ counterPropertyName + \"`, 0) \" + crementOp + \" 1\"\n\t\t\t\t+ \" RETURN node.`\" + counterPropertyName + \"`\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"nodeId\", getNodeId());\n\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\treturn jsonValue.asLong();\n\t}\n\n\tpublic long incrementCounter(String counterPropertyName) {\n\t\treturn crementCounter(counterPropertyName, true);\n\t}\n\n\tpublic long decrementCounter(String counterPropertyName) {\n\t\treturn crementCounter(counterPropertyName, false);\n\t}\n\n\tpublic long getCounter(String counterPropertyName) {\n\t\tPropertyAccessNode sketch = new PropertyAccessNode(getNodeId());\n\t\tJsonValue jsonValue = sketch.getValue(counterPropertyName);\n\t\tif ((jsonValue == null) || !jsonValue.isNumber())\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn jsonValue.asLong();\n\t}\n\n}", "public class HierarchyNode extends AbstractNodeSketch {\n\n\tpublic HierarchyNode(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tpublic void setNodeId(long nodeId) {\n\t\t_nodeId = nodeId;\n\t}\n\n\tpublic long getSupId() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sub)={subId}\" //\n\t\t\t\t+ \" RETURN ID(sup)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"subId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif (jsonValue != null)\n\t\t\treturn jsonValue.asLong();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tpublic JsonObject getSubNode(String segment) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId} AND sub.fold_Hierarchy_segment={segment}\" //\n\t\t\t\t+ \" RETURN sub\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tcypher.addParameter(\"segment\", segment);\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif ((jsonValue == null) || (!jsonValue.isObject()))\n\t\t\treturn null;\n\t\telse\n\t\t\treturn jsonValue.asObject();\n\t}\n\n\tpublic long getSubId(String segment, boolean createIfAbsent) {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText;\n\t\tif (createIfAbsent) {\n\t\t\tcypherText = \"MATCH sup\" //\n\t\t\t\t\t+ \" WHERE id(sup)={supId}\" //\n\t\t\t\t\t+ \" CREATE UNIQUE (sup)-[:fold_Hierarchy]->\"\n\t\t\t\t\t+ \"(sub{ fold_Hierarchy_segment:{segment} }) \"\n\t\t\t\t\t+ \" RETURN ID(sub)\";\n\t\t} else {\n\t\t\tcypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t\t+ \" WHERE ID(sup)={supId} AND sub.fold_Hierarchy_segment={segment}\" //\n\t\t\t\t\t+ \" RETURN ID(sub)\";\n\t\t}\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tcypher.addParameter(\"segment\", segment);\n\t\tneo4jService.invokeCypher(cypher);\n\t\tJsonValue jsonValue = cypher.getResultDataRow(0);\n\t\tif (jsonValue != null)\n\t\t\treturn jsonValue.asLong();\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tpublic long[] getSubIds() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId}\" //\n\t\t\t\t+ \" RETURN ID(sub)\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tlong[] subIds = new long[cypher.getResultDataRowCount()];\n\t\tfor (int i = 0; i < cypher.getResultDataRowCount(); i++) {\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(i);\n\t\t\tsubIds[i] = jsonValue.asLong();\n\t\t}\n\t\treturn subIds;\n\t}\n\n\tpublic String[] getSubSegments() {\n\t\tINeo4jService neo4jService = getNeo4jService();\n\t\tString cypherText = \"MATCH (sup)-[:fold_Hierarchy]->(sub)\"\n\t\t\t\t+ \" WHERE ID(sup)={supId}\"\n\t\t\t\t+ \" RETURN sub.fold_Hierarchy_segment\";\n\t\tICypher cypher = neo4jService.constructCypher(cypherText);\n\t\tcypher.addParameter(\"supId\", getNodeId());\n\t\tneo4jService.invokeCypher(cypher);\n\n\t\tString[] subSegments = new String[cypher.getResultDataRowCount()];\n\t\tfor (int i = 0; i < cypher.getResultDataRowCount(); i++) {\n\t\t\tJsonValue jsonValue = cypher.getResultDataRow(i);\n\t\t\tsubSegments[i] = jsonValue.asString();\n\t\t}\n\t\treturn subSegments;\n\t}\n\n\t// TODO:\n\t// public long[] getPathNodeIds(Path path) {\n\t//\n\t// }\n\t//\n\t// TODO:\n\t// public long getPathEndNodeId(Path path) {\n\t// return -1;\n\t// }\n\n}", "public class HtmlComposer {\n\n\tprivate StringBuilder _builder;\n\tprivate PrintWriter _writer;\n\n\tpublic HtmlComposer(PrintWriter writer) {\n\t\t_writer = writer;\n\t\t_builder = new StringBuilder();\n\t}\n\n\tpublic String A(String href, String linkText) {\n\t\t_builder.setLength(0);\n\t\t_builder.append(\"<a href='\");\n\t\t_builder.append(href);\n\t\t_builder.append(\"'>\");\n\t\t_builder.append(linkText);\n\t\t_builder.append(\"</a>\");\n\t\treturn _builder.toString();\n\t}\n\n\tpublic void a(String href, String linkText) {\n\t\t_writer.print(\"<a href='\");\n\t\t_writer.print(href);\n\t\t_writer.print(\"'>\");\n\t\t_writer.print(linkText);\n\t\t_writer.println(\"</a>\");\n\t}\n\n\tpublic void b(String text) {\n\t\tsimpleTag(\"b\", text);\n\t}\n\n\tpublic void br() {\n\t\t_writer.println(\"<br>\");\n\t}\n\n\tpublic void button(String type, String text) {\n\t\t_writer.print(\"<button type='\");\n\t\t_writer.print(type);\n\t\t_writer.print(\"'>\");\n\t\t_writer.print(text);\n\t\t_writer.print(\"</button>\");\n\t}\n\n\tpublic void code(String text) {\n\t\tsimpleTag(\"code\", text);\n\t}\n\n\tpublic void dd(String text) {\n\t\tsimpleTag(\"dd\", text);\n\t}\n\n\tpublic void div() {\n\t\tdiv(true);\n\t}\n\n\tpublic void div(boolean startTag) {\n\t\tsimpleTag(\"div\", startTag);\n\t}\n\n\tpublic void dl() {\n\t\tdl(true);\n\t}\n\n\tpublic void dl(boolean startTag) {\n\t\tsimpleTag(\"dl\", startTag);\n\t}\n\n\tpublic void dt(String text) {\n\t\tsimpleTag(\"dt\", text);\n\t}\n\n\tpublic void em(String text) {\n\t\tsimpleTag(\"em\", text);\n\t}\n\n\tpublic void form() {\n\t\tform(false);\n\t}\n\n\tpublic void form(boolean startTag) {\n\t\tsimpleTag(\"form\", startTag);\n\t}\n\n\tpublic void h(int level, String text) {\n\t\tif (level < 1)\n\t\t\tlevel = 1;\n\t\telse if (level > 6)\n\t\t\tlevel = 6;\n\t\t_writer.print(\"<h\");\n\t\t_writer.print(level);\n\t\t_writer.print(\">\");\n\t\t_writer.print(text);\n\t\t_writer.print(\"</h\");\n\t\t_writer.print(level);\n\t\t_writer.println(\">\");\n\t}\n\n\tpublic void html_head(String title) {\n\t\t_writer.println(\"<html>\");\n\t\t_writer.println(\"<head>\");\n\t\t_writer.print(\"<title>\");\n\t\t_writer.print(title);\n\t\t_writer.println(\"</title>\");\n\t\t_writer.println(\"</head>\");\n\t\t_writer.println(\"<body>\");\n\t}\n\n\tpublic void html_body(boolean startTag) {\n\t\tif (!startTag) {\n\t\t\t_writer.println(\"</body>\");\n\t\t\t_writer.println(\"</html>\");\n\t\t}\n\t}\n\n\tpublic void i(String text) {\n\t\tsimpleTag(\"i\", text);\n\t}\n\n\tpublic void img(String src, String alt) {\n\t\t_writer.print(\"<img src='\");\n\t\t_writer.print(src);\n\t\t_writer.print(\"' alt='\");\n\t\t_writer.print(alt);\n\t\t_writer.print(\"'>\");\n\t}\n\n\tpublic void input(String type, String name) {\n\t\t_writer.print(\"<input type='\");\n\t\t_writer.print(type);\n\t\t_writer.print(\"' name='\");\n\t\t_writer.print(name);\n\t\t_writer.println(\"'>\");\n\t}\n\n\tpublic void li(String text) {\n\t\tsimpleTag(\"li\", text);\n\t}\n\n\tpublic void object(String data, String type) {\n\t\t_writer.print(\"<object data='\");\n\t\t_writer.print(data);\n\t\t_writer.print(\"' type='\");\n\t\t_writer.print(type);\n\t\t_writer.print(\"'></object>\");\n\t}\n\n\tpublic void ol() {\n\t\tol(true);\n\t}\n\n\tpublic void ol(boolean startTag) {\n\t\tsimpleTag(\"ol\", startTag);\n\t}\n\n\tpublic void p() {\n\t\tp(true);\n\t}\n\n\tpublic void p(boolean startTag) {\n\t\tsimpleTag(\"p\", startTag);\n\t}\n\n\tpublic void p(String text) {\n\t\tsimpleTag(\"p\", text);\n\t}\n\n\tpublic void pre(String text) {\n\t\tsimpleTag(\"pre\", text);\n\t}\n\n\tpublic void span(String text) {\n\t\tsimpleTag(\"span\", text);\n\t}\n\n\tpublic void strong(String text) {\n\t\tsimpleTag(\"strong\", text);\n\t}\n\n\tpublic void table() {\n\t\ttable(true);\n\t}\n\n\tpublic void table(boolean startTag) {\n\t\tsimpleTag(\"table\", startTag);\n\t}\n\n\tpublic void text(String text) {\n\t\t_writer.print(text);\n\t}\n\n\tpublic void td(String text) {\n\t\tsimpleTag(\"td\", text);\n\t}\n\n\tpublic void th(String text) {\n\t\tsimpleTag(\"th\", text);\n\t}\n\n\tpublic void tr(boolean startTag) {\n\t\tsimpleTag(\"tr\", startTag);\n\t}\n\n\tpublic void tr(String... tableCells) {\n\t\ttr(false, tableCells);\n\t}\n\n\tpublic void tr(boolean isHeader, String... tableCells) {\n\t\t_writer.print(\"<tr>\");\n\t\tfor (String tableCell : tableCells) {\n\t\t\tif (isHeader)\n\t\t\t\t_writer.print(\"<th>\");\n\t\t\telse\n\t\t\t\t_writer.print(\"<td>\");\n\t\t\t_writer.print(tableCell);\n\t\t\tif (isHeader)\n\t\t\t\t_writer.print(\"</th>\");\n\t\t\telse\n\t\t\t\t_writer.print(\"</td>\");\n\t\t}\n\t\t_writer.println(\"</tr>\");\n\t}\n\n\tpublic void ul() {\n\t\tul(true);\n\t}\n\n\tpublic void ul(boolean startTag) {\n\t\tsimpleTag(\"ul\", startTag);\n\t}\n\n\t//\n\t//\n\n\tprivate void simpleTag(String tag, String text) {\n\t\t_writer.print(\"<\");\n\t\t_writer.print(tag);\n\t\t_writer.print(\">\");\n\t\t_writer.print(text);\n\t\t_writer.print(\"</\");\n\t\t_writer.print(tag);\n\t\t_writer.println(\">\");\n\t}\n\n\tprivate void simpleTag(String tag, boolean startTag) {\n\t\tif (startTag) {\n\t\t\t_writer.print(\"<\");\n\t\t\t_writer.print(tag);\n\t\t\t_writer.println(\">\");\n\t\t} else {\n\t\t\t_writer.print(\"</\");\n\t\t\t_writer.print(tag);\n\t\t\t_writer.println(\">\");\n\t\t}\n\t}\n\n}" ]
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.locosoft.fold.channel.AbstractChannel; import net.locosoft.fold.channel.ChannelUtil; import net.locosoft.fold.channel.IChannel; import net.locosoft.fold.channel.fold.IFoldChannel; import net.locosoft.fold.sketch.pad.html.ChannelHeaderFooterHtml; import net.locosoft.fold.sketch.pad.neo4j.CounterPropertyNode; import net.locosoft.fold.sketch.pad.neo4j.HierarchyNode; import net.locosoft.fold.util.HtmlComposer; import org.eclipse.core.runtime.Path; import com.eclipsesource.json.JsonObject;
/***************************************************************************** * Copyright (c) 2015 Chris J Daly (github user cjdaly) * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * cjdaly - initial API and implementation ****************************************************************************/ package net.locosoft.fold.channel.fold.internal; public class FoldChannel extends AbstractChannel implements IFoldChannel { private FoldFinder _foldFinder = new FoldFinder(this); private long _startCount = -1; public long getStartCount() { return _startCount; } public Class<? extends IChannel> getChannelInterface() { return IFoldChannel.class; } public void init() { CounterPropertyNode foldStartCount = new CounterPropertyNode( getChannelNodeId()); _startCount = foldStartCount.incrementCounter("fold_startCount"); _foldFinder.start(); } public void fini() { _foldFinder.stop(); } public void channelHttpGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if ((pathInfo == null) || ("".equals(pathInfo)) || ("/".equals(pathInfo))) { // empty channel segment (/fold) new ChannelHttpGetDashboard() .composeHtmlResponse(request, response); } else { Path path = new Path(pathInfo); String channelSegment = path.segment(0); if ("fold".equals(channelSegment)) { // fold channel segment (/fold/fold) new ChannelHttpGetFold().composeHtmlResponse(request, response); } else { // everything else new ChannelHttpGetUndefined().composeHtmlResponse(request, response); } } }
private class ChannelHttpGetDashboard extends ChannelHeaderFooterHtml {
4
spacecowboy/NotePad
app/src/main/java/com/nononsenseapps/notepad/util/ListHelper.java
[ "public class LegacyDBHelper extends SQLiteOpenHelper {\n\n\tpublic static final String LEGACY_DATABASE_NAME = \"note_pad.db\";\n\tpublic static final int LEGACY_DATABASE_FINAL_VERSION = 8;\n\n\tpublic LegacyDBHelper(Context context) {\n\t\tthis(context, \"\");\n\t}\n\n\tpublic LegacyDBHelper(Context context, String testPrefix) {\n\t\tsuper(context.getApplicationContext(), testPrefix\n\t\t\t\t+ LEGACY_DATABASE_NAME, null, LEGACY_DATABASE_FINAL_VERSION);\n\t}\n\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\t// Don't create anything if the database doesn't exist before.\n\t}\n\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\tLog.d(\"LegacyHelper\", \"onUpgrade \" + \"Upgrading database from version \"\n\t\t\t\t+ oldVersion + \" to \" + newVersion);\n\n\t\tif (oldVersion < 3) {\n\t\t\t// FIrst add columns to Notes table\n\n\t\t\tString preName = \"ALTER TABLE \" + \"notes\" + \" ADD COLUMN \";\n\t\t\t// Don't want null values. Prefer empty String\n\t\t\tString postText = \" TEXT\";\n\t\t\tString postNameInt = \" INTEGER\";\n\t\t\t// Add Columns to Notes DB\n\t\t\tdb.execSQL(preName + \"list\" + postNameInt);\n\t\t\tdb.execSQL(preName + \"duedate\" + postText);\n\t\t\tdb.execSQL(preName + \"gtaskstatus\" + postText);\n\t\t\tdb.execSQL(preName + \"modifiedflag\" + postNameInt);\n\t\t\tdb.execSQL(preName + \"deleted\" + postNameInt);\n\n\t\t\t// Then create the 3 missing tables\n\t\t\tdb.execSQL(\"CREATE TABLE \" + \"lists\" + \" (\" + BaseColumns._ID\n\t\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + \"title\"\n\t\t\t\t\t+ \" TEXT DEFAULT '' NOT NULL,\" + \"modifiedflag\"\n\t\t\t\t\t+ \" INTEGER DEFAULT 0 NOT NULL,\" + \"modified\"\n\t\t\t\t\t+ \" INTEGER DEFAULT 0 NOT NULL,\" + \"deleted\"\n\t\t\t\t\t+ \" INTEGER DEFAULT 0 NOT NULL\" + \");\");\n\n\t\t\tdb.execSQL(\"CREATE TABLE \" + \"gtasks\" + \" (\" + BaseColumns._ID\n\t\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + \"dbid\"\n\t\t\t\t\t+ \" INTEGER UNIQUE NOT NULL REFERENCES \" + \"notes\" + \",\"\n\t\t\t\t\t+ \"googleid\" + \" INTEGER NOT NULL,\" + \"googleaccount\"\n\t\t\t\t\t+ \" INTEGER NOT NULL,\" + \"updated\" + \" TEXT,\" + \"etag\"\n\t\t\t\t\t+ \" TEXT\" + \");\");\n\n\t\t\tdb.execSQL(\"CREATE TABLE \" + \"gtasklists\" + \" (\" + BaseColumns._ID\n\t\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + \"dbid\"\n\t\t\t\t\t+ \" INTEGER UNIQUE NOT NULL REFERENCES \" + \"lists\" + \",\"\n\t\t\t\t\t+ \"googleid\" + \" INTEGER NOT NULL,\" + \"googleaccount\"\n\t\t\t\t\t+ \" INTEGER NOT NULL,\" + \"updated\" + \" TEXT,\" + \"etag\"\n\t\t\t\t\t+ \" TEXT\" + \");\");\n\n\t\t\t// Now insert a default list\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(\"title\", \"Tasks\");\n\t\t\tvalues.put(\"modifiedflag\", 1);\n\t\t\tvalues.put(\"deleted\", 0);\n\t\t\tlong listId = db.insert(\"lists\", null, values);\n\n\t\t\t// Place all existing notes in this list\n\t\t\t// And give them sensible values in the new columns\n\t\t\tvalues.clear();\n\t\t\tvalues.put(\"list\", listId);\n\t\t\tvalues.put(\"modifiedflag\", 1);\n\t\t\tvalues.put(\"deleted\", 0);\n\t\t\tvalues.put(\"duedate\", \"\");\n\t\t\tvalues.put(\"gtaskstatus\", \"needsAction\");\n\n\t\t\tdb.update(\"notes\", values, \"list\" + \" IS NOT ?\",\n\t\t\t\t\tnew String[] { Long.toString(listId) });\n\t\t}\n\t\tif (oldVersion < 4) {\n\n\t\t\tString preName = \"ALTER TABLE \" + \"notes\" + \" ADD COLUMN \";\n\t\t\tString postText = \" TEXT\";\n\t\t\tString postNameInt = \" INTEGER\";\n\t\t\t// Add Columns to Notes DB\n\t\t\tdb.execSQL(preName + \"gtasks_parent\" + postText);\n\t\t\tdb.execSQL(preName + \"gtasks_position\" + postText);\n\t\t\tdb.execSQL(preName + \"hiddenflag\" + postNameInt);\n\n\t\t\t// Give all notes sensible values\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(\"gtasks_parent\", \"\");\n\t\t\tvalues.put(\"gtasks_position\", \"\");\n\t\t\tvalues.put(\"hiddenflag\", 0);\n\t\t\tdb.update(\"notes\", values, \"hiddenflag\" + \" IS NOT ?\",\n\t\t\t\t\tnew String[] { \"0\" });\n\t\t}\n\t\tif (oldVersion < 5) {\n\n\t\t\tString preName = \"ALTER TABLE \" + \"notes\" + \" ADD COLUMN \";\n\t\t\tString postText = \" TEXT DEFAULT ''\";\n\t\t\tString postNameInt = \" INTEGER DEFAULT 0\";\n\t\t\tdb.execSQL(preName + \"possubsort\" + postText);\n\t\t\tdb.execSQL(preName + \"localhidden\" + postNameInt);\n\t\t}\n\t\tif (oldVersion < 6) {\n\t\t\t// Add Columns to Notes DB\n\t\t\tString preName = \"ALTER TABLE \" + \"notes\" + \" ADD COLUMN \";\n\t\t\tString postNameInt = \" INTEGER DEFAULT 0\";\n\t\t\tdb.execSQL(preName + \"indentlevel\" + postNameInt);\n\t\t\tdb.execSQL(preName + \"locked\" + postNameInt);\n\n\t\t\t// Mark all notes as modified to ensure we set the indents on\n\t\t\t// next sync\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(\"modifiedflag\", 1);\n\t\t\tdb.update(\"notes\", values, null, null);\n\t\t}\n\t\tif (oldVersion < 7) {\n\t\t\tdb.execSQL(\"CREATE TABLE \" + \"notification\" + \" (\"\n\t\t\t\t\t+ BaseColumns._ID + \" INTEGER PRIMARY KEY,\" + \"time\"\n\t\t\t\t\t+ \" INTEGER NOT NULL DEFAULT 0,\" + \"permanent\"\n\t\t\t\t\t+ \" INTEGER NOT NULL DEFAULT 0,\" + \"noteid\" + \" INTEGER,\"\n\t\t\t\t\t+ \"FOREIGN KEY(\" + \"noteid\" + \") REFERENCES \" + \"notes\"\n\t\t\t\t\t+ \"(\" + BaseColumns._ID + \") ON DELETE CASCADE\" + \");\");\n\t\t}\n\t\tif (oldVersion < 8) {\n\t\t\ttry {\n\t\t\t\tdb.execSQL(\"CREATE TRIGGER post_note_markdelete AFTER UPDATE ON \"\n\t\t\t\t\t\t+ \"notes\"\n\t\t\t\t\t\t+ \" WHEN new.\"\n\t\t\t\t\t\t+ \"deleted\"\n\t\t\t\t\t\t+ \" = 1\"\n\t\t\t\t\t\t+ \" BEGIN\"\n\t\t\t\t\t\t+ \" DELETE FROM \"\n\t\t\t\t\t\t+ \"notification\"\n\t\t\t\t\t\t+ \" WHERE \"\n\t\t\t\t\t\t+ \"notification\"\n\t\t\t\t\t\t+ \".\"\n\t\t\t\t\t\t+ \"noteid\"\n\t\t\t\t\t\t+ \" = \" + \"new.\" + BaseColumns._ID + \";\" + \" END\");\n\t\t\t}\n\t\t\tcatch (SQLException e) {\n\t\t\t\t// Log.d(TAG,\n\t\t\t\t// \"Creating trigger failed. It probably already existed:\\n \" +\n\t\t\t\t// e.getLocalizedMessage());\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tdb.execSQL(\"CREATE TRIGGER post_note_actualdelete AFTER DELETE ON \"\n\t\t\t\t\t\t+ \"notes\"\n\t\t\t\t\t\t+ \" BEGIN\"\n\t\t\t\t\t\t+ \" DELETE FROM \"\n\t\t\t\t\t\t+ \"notification\"\n\t\t\t\t\t\t+ \" WHERE \"\n\t\t\t\t\t\t+ \"notification\"\n\t\t\t\t\t\t+ \".\"\n\t\t\t\t\t\t+ \"noteid\"\n\t\t\t\t\t\t+ \" = \"\n\t\t\t\t\t\t+ \"old.\"\n\t\t\t\t\t\t+ BaseColumns._ID\n\t\t\t\t\t\t+ \";\"\n\t\t\t\t\t\t+ \" END\");\n\t\t\t}\n\t\t\tcatch (SQLException e) {\n\t\t\t\t// Log.d(TAG,\n\t\t\t\t// \"Creating trigger failed. It probably already existed:\\n \" +\n\t\t\t\t// e.getLocalizedMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static final class NotePad {\n\t\tpublic static final String AUTHORITY = MyContentProvider.AUTHORITY;\n\n\t\t// This class cannot be instantiated\n\t\tprivate NotePad() {\n\t\t}\n\n\t\t/**\n\t\t * Notes table contract\n\t\t */\n\t\tpublic static final class Notes implements BaseColumns {\n\n\t\t\t// This class cannot be instantiated\n\t\t\tprivate Notes() {\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * The table name offered by this provider\n\t\t\t */\n\t\t\tpublic static final String TABLE_NAME = \"notes\";\n\t\t\tpublic static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;\n\n\t\t\t/*\n\t\t\t * URI definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The scheme part for this provider's URI\n\t\t\t */\n\t\t\tprivate static final String SCHEME = \"content://\";\n\n\t\t\t/**\n\t\t\t * Path parts for the URIs\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * Path part for the Notes URI\n\t\t\t */\n\t\t\tpublic static final String PATH_NOTES = \"/notes\";\n\t\t\tpublic static final String NOTES = \"notes\";\n\t\t\t// Visible notes\n\t\t\tpublic static final String PATH_VISIBLE_NOTES = \"/visiblenotes\";\n\t\t\tpublic static final String VISIBLE_NOTES = \"visiblenotes\";\n\t\t\t// Complete note entry including stuff in GTasks table\n\t\t\tprivate static final String PATH_JOINED_NOTES = \"/joinednotes\";\n\n\t\t\t/**\n\t\t\t * Path part for the Note ID URI\n\t\t\t */\n\t\t\tpublic static final String PATH_NOTE_ID = \"/notes/\";\n\t\t\tpublic static final String PATH_VISIBLE_NOTE_ID = \"/visiblenotes/\";\n\n\t\t\t/**\n\t\t\t * 0-relative position of a note ID segment in the path part of a\n\t\t\t * note ID URI\n\t\t\t */\n\t\t\tpublic static final int NOTE_ID_PATH_POSITION = 1;\n\n\t\t\t/**\n\t\t\t * The content:// style URL for this table\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY\n\t\t\t\t\t+ PATH_NOTES);\n\t\t\tpublic static final Uri CONTENT_VISIBLE_URI = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_VISIBLE_NOTES);\n\t\t\tpublic static final Uri CONTENT_JOINED_URI = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_JOINED_NOTES);\n\n\t\t\t/**\n\t\t\t * The content URI base for a single note. Callers must append a\n\t\t\t * numeric note id to this Uri to retrieve a note\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_NOTE_ID);\n\t\t\tpublic static final Uri CONTENT_VISIBLE_ID_URI_BASE = Uri\n\t\t\t\t\t.parse(SCHEME + AUTHORITY + PATH_VISIBLE_NOTE_ID);\n\n\t\t\t/**\n\t\t\t * The content URI match pattern for a single note, specified by its\n\t\t\t * ID. Use this to match incoming URIs or to construct an Intent.\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_NOTE_ID + \"/#\");\n\t\t\tpublic static final Uri CONTENT_VISIBLE_ID_URI_PATTERN = Uri\n\t\t\t\t\t.parse(SCHEME + AUTHORITY + PATH_VISIBLE_NOTE_ID + \"/#\");\n\n\t\t\t/*\n\t\t\t * MIME type definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The MIME type of {@link #CONTENT_URI} providing a directory of\n\t\t\t * notes.\n\t\t\t */\n\t\t\t// public static final String CONTENT_TYPE =\n\t\t\t// \"vnd.android.cursor.dir/vnd.nononsenseapps.note\";\n\n\t\t\t/**\n\t\t\t * The MIME type of a {@link #CONTENT_URI} sub-directory of a single\n\t\t\t * note.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/vnd.nononsenseapps.note\";\n\n\t\t\tpublic static final String CONTENT_TYPE = CONTENT_ITEM_TYPE;\n\n\t\t\t/*\n\t\t\t * Column definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * Column name for the title of the note\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_TITLE = \"title\";\n\n\t\t\t/**\n\t\t\t * Column name of the note content\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_NOTE = \"note\";\n\n\t\t\t/**\n\t\t\t * Column name for the creation timestamp\n\t\t\t * <P>\n\t\t\t * Type: INTEGER (long from System.curentTimeMillis())\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_CREATE_DATE = \"created\";\n\n\t\t\t/**\n\t\t\t * Column name for the modification timestamp\n\t\t\t * <P>\n\t\t\t * Type: INTEGER (long from System.curentTimeMillis())\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_MODIFICATION_DATE = \"modified\";\n\n\t\t\t/**\n\t\t\t * Due date of the task (as an RFC 3339 timestamp) formatted as\n\t\t\t * String.\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_DUE_DATE = \"duedate\";\n\n\t\t\t/**\n\t\t\t * Status of task, such as \"completed\"\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_GTASKS_STATUS = \"gtaskstatus\";\n\n\t\t\t/**\n\t\t\t * INTEGER, id of entry in lists table\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_LIST = \"list\";\n\n\t\t\t/**\n\t\t\t * Deleted flag\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_DELETED = \"deleted\";\n\n\t\t\t/**\n\t\t\t * Modified flag\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_MODIFIED = \"modifiedflag\";\n\n\t\t\t// parent position hidden\n\n\t\t\tpublic static final String COLUMN_NAME_PARENT = \"gtasks_parent\";\n\n\t\t\tpublic static final String COLUMN_NAME_POSITION = \"gtasks_position\";\n\t\t\tpublic static final String COLUMN_NAME_HIDDEN = \"hiddenflag\";\n\n\t\t\t// server side sorting and local hiding\n\t\t\tpublic static final String COLUMN_NAME_INDENTLEVEL = \"indentlevel\";\n\t\t\tpublic static final String COLUMN_NAME_POSSUBSORT = \"possubsort\";\n\t\t\tpublic static final String COLUMN_NAME_LOCALHIDDEN = \"localhidden\";\n\n\t\t\t/**\n\t\t\t * The default sort order for this table\n\t\t\t */\n\t\t\t// public static final String DEFAULT_SORT_TYPE = COLUMN_NAME_TITLE\n\t\t\t// +\n\t\t\t// \" COLLATE NOCASE\";\n\t\t\tpublic static final String ALPHABETIC_SORT_TYPE = COLUMN_NAME_TITLE\n\t\t\t\t\t+ \" COLLATE NOCASE\";\n\t\t\t// We want items with no due dates to be placed at the end, hence\n\t\t\t// the\n\t\t\t// sql magic\n\t\t\t// Coalesce returns the first non-null argument\n\t\t\tpublic static final String MODIFICATION_SORT_TYPE = COLUMN_NAME_MODIFICATION_DATE;\n\t\t\tpublic static final String DUEDATE_SORT_TYPE = \"CASE WHEN \"\n\t\t\t\t\t+ COLUMN_NAME_DUE_DATE + \" IS NULL OR \"\n\t\t\t\t\t+ COLUMN_NAME_DUE_DATE + \" IS '' THEN 1 ELSE 0 END, \"\n\t\t\t\t\t+ COLUMN_NAME_DUE_DATE;\n\t\t\tpublic static final String POSSUBSORT_SORT_TYPE = COLUMN_NAME_POSSUBSORT;\n\n\t\t\tpublic static final String ASCENDING_SORT_ORDERING = \"ASC\";\n\t\t\tpublic static final String DESCENDING_SORT_ORDERING = \"DESC\";\n\t\t\tpublic static final String ALPHABETIC_ASC_ORDER = COLUMN_NAME_TITLE\n\t\t\t\t\t+ \" COLLATE NOCASE ASC\";\n\t\t\t// public static final String POSITION_ASC_ORDER =\n\t\t\t// COLUMN_NAME_POSITION+\n\t\t\t// \" ASC\";\n\n\t\t\tpublic static final String DEFAULT_SORT_TYPE = POSSUBSORT_SORT_TYPE;\n\t\t\tpublic static final String DEFAULT_SORT_ORDERING = ASCENDING_SORT_ORDERING;\n\n\t\t\tpublic static String SORT_ORDER = ALPHABETIC_ASC_ORDER;\n\t\t}\n\n\t\t/**\n\t\t * Lists table contract\n\t\t */\n\t\tpublic static final class Lists implements BaseColumns {\n\n\t\t\t// This class cannot be instantiated\n\t\t\tprivate Lists() {\n\t\t\t}\n\n\t\t\tpublic static final String DEFAULT_LIST_NAME = \"Notes\";\n\n\t\t\t/**\n\t\t\t * The table name offered by this provider\n\t\t\t */\n\t\t\tpublic static final String TABLE_NAME = \"lists\";\n\t\t\tpublic static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;\n\n\t\t\t/*\n\t\t\t * URI definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The scheme part for this provider's URI\n\t\t\t */\n\t\t\tprivate static final String SCHEME = \"content://\";\n\n\t\t\t/**\n\t\t\t * Path parts for the URIs\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * Path part for the Lists URI\n\t\t\t */\n\t\t\tpublic static final String PATH_LISTS = \"/lists\";\n\t\t\tpublic static final String LISTS = \"lists\";\n\t\t\tpublic static final String PATH_VISIBLE_LISTS = \"/visiblelists\";\n\t\t\tpublic static final String VISIBLE_LISTS = \"visiblelists\";\n\t\t\t// Complete entry gotten with a join with GTasksLists table\n\t\t\tprivate static final String PATH_JOINED_LISTS = \"/joinedlists\";\n\n\t\t\t/**\n\t\t\t * Path part for the List ID URI\n\t\t\t */\n\t\t\tpublic static final String PATH_LIST_ID = \"/lists/\";\n\t\t\tpublic static final String PATH_VISIBLE_LIST_ID = \"/visiblelists/\";\n\n\t\t\t/**\n\t\t\t * 0-relative position of a ID segment in the path part of a ID URI\n\t\t\t */\n\t\t\tpublic static final int ID_PATH_POSITION = 1;\n\n\t\t\t/**\n\t\t\t * The content:// style URL for this table\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY\n\t\t\t\t\t+ PATH_LISTS);\n\t\t\tpublic static final Uri CONTENT_VISIBLE_URI = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_VISIBLE_LISTS);\n\t\t\tpublic static final Uri CONTENT_JOINED_URI = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_JOINED_LISTS);\n\n\t\t\t/**\n\t\t\t * The content URI base for a single note. Callers must append a\n\t\t\t * numeric note id to this Uri to retrieve a note\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_LIST_ID);\n\t\t\tpublic static final Uri CONTENT_VISIBLE_ID_URI_BASE = Uri\n\t\t\t\t\t.parse(SCHEME + AUTHORITY + PATH_VISIBLE_LIST_ID);\n\n\t\t\t/**\n\t\t\t * The content URI match pattern for a single note, specified by its\n\t\t\t * ID. Use this to match incoming URIs or to construct an Intent.\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_LIST_ID + \"/#\");\n\t\t\tpublic static final Uri CONTENT_VISIBLE_ID_URI_PATTERN = Uri\n\t\t\t\t\t.parse(SCHEME + AUTHORITY + PATH_VISIBLE_LIST_ID + \"/#\");\n\n\t\t\t/*\n\t\t\t * MIME type definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The MIME type of {@link #CONTENT_URI} providing a directory.\n\t\t\t */\n\t\t\t// public static final String CONTENT_TYPE =\n\t\t\t// \"vnd.android.cursor.dir/vnd.nononsenseapps.list\";\n\n\t\t\t/**\n\t\t\t * The MIME type of a {@link #CONTENT_URI} sub-directory of a single\n\t\t\t * item.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/vnd.nononsenseapps.list\";\n\n\t\t\tpublic static final String CONTENT_TYPE = CONTENT_ITEM_TYPE;\n\n\t\t\t/*\n\t\t\t * Column definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * Column name for the title of the note\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_TITLE = \"title\";\n\n\t\t\t/**\n\t\t\t * Deleted flag\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_DELETED = \"deleted\";\n\n\t\t\t/**\n\t\t\t * Modified flag\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_MODIFIED = \"modifiedflag\";\n\n\t\t\t/**\n\t\t\t * Column name for the modification timestamp\n\t\t\t * <P>\n\t\t\t * Type: INTEGER (long from System.curentTimeMillis())\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_MODIFICATION_DATE = \"modified\";\n\n\t\t\t/**\n\t\t\t * The default sort order for this table\n\t\t\t */\n\n\t\t\tpublic static final String DEFAULT_SORT_TYPE = COLUMN_NAME_MODIFICATION_DATE;\n\t\t\tpublic static final String DEFAULT_SORT_ORDERING = \"DESC\";\n\t\t\tpublic static final String MODIFIED_DESC_ORDER = COLUMN_NAME_MODIFICATION_DATE\n\t\t\t\t\t+ \" DESC\";\n\t\t\tpublic static final String ALPHABETIC_ASC_ORDER = COLUMN_NAME_TITLE\n\t\t\t\t\t+ \" COLLATE NOCASE ASC\";\n\n\t\t\tpublic static String SORT_ORDER = ALPHABETIC_ASC_ORDER;\n\t\t}\n\n\t\t/**\n\t\t * GoogleTasks table contract\n\t\t */\n\t\tpublic static final class GTasks implements BaseColumns {\n\n\t\t\t// This class cannot be instantiated\n\t\t\tprivate GTasks() {\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * The table name offered by this provider\n\t\t\t */\n\t\t\tpublic static final String TABLE_NAME = \"gtasks\";\n\t\t\tpublic static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;\n\n\t\t\t/*\n\t\t\t * URI definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The scheme part for this provider's URI\n\t\t\t */\n\t\t\tprivate static final String SCHEME = \"content://\";\n\n\t\t\t/**\n\t\t\t * Path parts for the URIs\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * Path part for the Lists URI\n\t\t\t */\n\t\t\tprivate static final String PATH = \"/gtasks\";\n\n\t\t\t/**\n\t\t\t * Path part for the List ID URI\n\t\t\t */\n\t\t\tprivate static final String PATH_ID = \"/gtasks/\";\n\n\t\t\t/**\n\t\t\t * 0-relative position of a note ID segment in the path part of a\n\t\t\t * note ID URI\n\t\t\t */\n\t\t\tpublic static final int ID_PATH_POSITION = 1;\n\n\t\t\t/**\n\t\t\t * The content:// style URL for this table\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY\n\t\t\t\t\t+ PATH);\n\n\t\t\t/**\n\t\t\t * The content URI base for a single note. Callers must append a\n\t\t\t * numeric note id to this Uri to retrieve a note\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_ID);\n\n\t\t\t/**\n\t\t\t * The content URI match pattern for a single note, specified by its\n\t\t\t * ID. Use this to match incoming URIs or to construct an Intent.\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_ID + \"/#\");\n\n\t\t\t/*\n\t\t\t * MIME type definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The MIME type of {@link #CONTENT_URI} providing a directory of\n\t\t\t * notes.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_TYPE = \"vnd.android.cursor.dir/vnd.nononsenseapps.gtask\";\n\n\t\t\t/**\n\t\t\t * The MIME type of a {@link #CONTENT_URI} sub-directory of a single\n\t\t\t * note.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/vnd.nononsenseapps.gtask\";\n\n\t\t\t/*\n\t\t\t * Column definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: INTEGER, database ID\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_DB_ID = \"dbid\";\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_GTASKS_ID = \"googleid\";\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_GOOGLE_ACCOUNT = \"googleaccount\";\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_ETAG = \"etag\";\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_UPDATED = \"updated\";\n\t\t}\n\n\t\t/**\n\t\t * GoogleTaskLists table contract\n\t\t */\n\t\tpublic static final class GTaskLists implements BaseColumns {\n\n\t\t\t// This class cannot be instantiated\n\t\t\tprivate GTaskLists() {\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * The table name offered by this provider\n\t\t\t */\n\t\t\tpublic static final String TABLE_NAME = \"gtasklists\";\n\t\t\tpublic static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;\n\n\t\t\t/*\n\t\t\t * URI definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The scheme part for this provider's URI\n\t\t\t */\n\t\t\tprivate static final String SCHEME = \"content://\";\n\n\t\t\t/**\n\t\t\t * Path parts for the URIs\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * Path part for the Lists URI\n\t\t\t */\n\t\t\tprivate static final String PATH = \"/gtasklists\";\n\n\t\t\t/**\n\t\t\t * Path part for the List ID URI\n\t\t\t */\n\t\t\tprivate static final String PATH_ID = \"/gtasklists/\";\n\n\t\t\t/**\n\t\t\t * 0-relative position of a note ID segment in the path part of a\n\t\t\t * note ID URI\n\t\t\t */\n\t\t\tpublic static final int ID_PATH_POSITION = 1;\n\n\t\t\t/**\n\t\t\t * The content:// style URL for this table\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY\n\t\t\t\t\t+ PATH);\n\n\t\t\t/**\n\t\t\t * The content URI base for a single note. Callers must append a\n\t\t\t * numeric note id to this Uri to retrieve a note\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_ID);\n\n\t\t\t/**\n\t\t\t * The content URI match pattern for a single note, specified by its\n\t\t\t * ID. Use this to match incoming URIs or to construct an Intent.\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_ID + \"/#\");\n\n\t\t\t/*\n\t\t\t * MIME type definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The MIME type of {@link #CONTENT_URI} providing a directory of\n\t\t\t * notes.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_TYPE = \"vnd.android.cursor.dir/vnd.nononsenseapps.gtasklist\";\n\n\t\t\t/**\n\t\t\t * The MIME type of a {@link #CONTENT_URI} sub-directory of a single\n\t\t\t * note.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/vnd.nononsenseapps.gtasklist\";\n\n\t\t\t/*\n\t\t\t * Column definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: INTEGER, database ID\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_DB_ID = \"dbid\";\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_GTASKS_ID = \"googleid\";\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_GOOGLE_ACCOUNT = \"googleaccount\";\n\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_ETAG = \"etag\";\n\t\t\t/**\n\t\t\t * <P>\n\t\t\t * Type: TEXT\n\t\t\t * </P>\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_UPDATED = \"updated\";\n\t\t}\n\n\t\t/**\n\t\t * Notifications table contract\n\t\t */\n\t\tpublic static final class Notifications implements BaseColumns {\n\n\t\t\t// This class cannot be instantiated\n\t\t\tprivate Notifications() {\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * The table name offered by this provider\n\t\t\t */\n\t\t\tpublic static final String TABLE_NAME = \"notification\";\n\t\t\tpublic static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;\n\n\t\t\t/*\n\t\t\t * Column definitions\n\t\t\t */\n\t\t\tpublic static final String COLUMN_NAME_TIME = \"time\";\n\t\t\tpublic static final String COLUMN_NAME_PERMANENT = \"permanent\";\n\t\t\tpublic static final String COLUMN_NAME_NOTEID = \"noteid\";\n\n\t\t\tpublic static final String JOINED_COLUMN_LIST_TITLE = NotePad.Lists.TABLE_NAME\n\t\t\t\t\t+ \".\" + NotePad.Lists.COLUMN_NAME_TITLE;\n\n\t\t\t/*\n\t\t\t * URI definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The scheme part for this provider's URI\n\t\t\t */\n\t\t\tprivate static final String SCHEME = \"content://\";\n\n\t\t\t/**\n\t\t\t * Path parts for the URIs\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * Path part for the Lists URI\n\t\t\t */\n\t\t\tprivate static final String PATH = \"/\" + TABLE_NAME;\n\n\t\t\t/**\n\t\t\t * Path part for the List ID URI\n\t\t\t */\n\t\t\tprivate static final String PATH_ID = PATH + \"/\";\n\n\t\t\t/**\n\t\t\t * 0-relative position of a note ID segment in the path part of a\n\t\t\t * note ID URI\n\t\t\t */\n\t\t\tpublic static final int ID_PATH_POSITION = 1;\n\n\t\t\tprivate static final String PATH_JOINED_NOTIFICATIONS = \"/joinednotifications\";\n\t\t\tpublic static final String PATH_NOTIFICATIONS_LISTID = \"/notificationlists\";\n\t\t\tprivate static final String PATH_NOTIFICATIONS_LISTID_BASE = PATH_NOTIFICATIONS_LISTID\n\t\t\t\t\t+ \"/\";\n\t\t\t/**\n\t\t\t * The content:// style URL for this table\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY\n\t\t\t\t\t+ PATH);\n\n\t\t\tpublic static final Uri CONTENT_JOINED_URI = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_JOINED_NOTIFICATIONS);\n\n\t\t\tpublic static final Uri CONTENT_LISTID_URI_BASE = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_NOTIFICATIONS_LISTID);\n\n\t\t\t/**\n\t\t\t * The content URI base for a single note. Callers must append a\n\t\t\t * numeric note id to this Uri to retrieve a note\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_ID);\n\n\t\t\t/**\n\t\t\t * The content URI match pattern for a single note, specified by its\n\t\t\t * ID. Use this to match incoming URIs or to construct an Intent.\n\t\t\t */\n\t\t\tpublic static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME\n\t\t\t\t\t+ AUTHORITY + PATH_ID + \"/#\");\n\n\t\t\t/*\n\t\t\t * MIME type definitions\n\t\t\t */\n\n\t\t\t/**\n\t\t\t * The MIME type of {@link #CONTENT_URI} providing a directory of\n\t\t\t * notes.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_TYPE = \"vnd.android.cursor.dir/vnd.nononsenseapps.\"\n\t\t\t\t\t+ TABLE_NAME;\n\n\t\t\t/**\n\t\t\t * The MIME type of a {@link #CONTENT_URI} sub-directory of a single\n\t\t\t * note.\n\t\t\t */\n\t\t\tpublic static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/vnd.nononsenseapps.\"\n\t\t\t\t\t+ TABLE_NAME;\n\t\t}\n\t}\n\n\t/**\n\t * Converts the columns names from the legacy URIs. However, the data must\n\t * also be returned correctly!\n\t */\n\tpublic static String[] convertLegacyColumns(final String[] legacyCols) {\n\t\tString[] newCols = new String[legacyCols.length];\n\t\tfor (int i = 0; i < legacyCols.length; i++) {\n\t\t\tString col = legacyCols[i];\n\t\t\tString newCol = col;\n\t\t\t// Lists\n\t\t\tif (NotePad.Lists.COLUMN_NAME_TITLE.equals(col)) {\n\t\t\t\tnewCol = TaskList.Columns.TITLE;\n\t\t\t}\n\t\t\t// Tasks\n\t\t\telse if (NotePad.Notes.COLUMN_NAME_TITLE.equals(col)) {\n\t\t\t\tnewCol = Task.Columns.TITLE;\n\t\t\t}\n\t\t\telse if (NotePad.Notes.COLUMN_NAME_NOTE.equals(col)) {\n\t\t\t\tnewCol = Task.Columns.NOTE;\n\t\t\t}\n\t\t\telse if (NotePad.Notes.COLUMN_NAME_LIST.equals(col)) {\n\t\t\t\tnewCol = Task.Columns.DBLIST;\n\t\t\t}\n\t\t\telse if (NotePad.Notes.COLUMN_NAME_DUE_DATE.equals(col)) {\n\t\t\t\tnewCol = Task.Columns.DUE;\n\t\t\t}\n\t\t\telse if (NotePad.Notes.COLUMN_NAME_GTASKS_STATUS.equals(col)) {\n\t\t\t\tnewCol = Task.Columns.COMPLETED;\n\t\t\t}\n\n\t\t\t//Log.d(\"nononsenseapps db\", \"legacy converted field:\" + newCol);\n\t\t\tnewCols[i] = newCol;\n\t\t}\n\t\treturn newCols;\n\t}\n\n\t/** \n\t * Convert new values to old, but using old or new column names\n\t * \n\t * TaskProjection: new String[] { \"_id\", \"title\", \"note\", \"list\", \"duedate\",\n\t * \"gtaskstatus\"};\n\t */\n\tpublic static Object[] convertLegacyTaskValues(final Cursor cursor) {\n\t\tObject[] retval = new Object[cursor.getColumnCount()];\n\t\tfor (int i = 0; i < cursor.getColumnCount(); i++) {\n\t\t\tfinal String colName = cursor.getColumnName(i);\n\t\t\tfinal Object val;\n\t\t\tif (NotePad.Notes.COLUMN_NAME_DUE_DATE.equals(colName) ||\n\t\t\t\t\tTask.Columns.DUE.equals(colName)) {\n\t\t\t\tval = cursor.isNull(i) ? \"\" : RFC3339Date.asRFC3339(cursor.getLong(i));\n\t\t\t}\n\t\t\telse if (NotePad.Notes.COLUMN_NAME_GTASKS_STATUS.equals(colName) ||\n\t\t\t\t\tTask.Columns.COMPLETED.equals(colName)) {\n\t\t\t\tval = cursor.isNull(i) ? \"needsAction\" : \"completed\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tswitch (cursor.getType(i)) {\n\t\t\t\tcase Cursor.FIELD_TYPE_FLOAT:\n\t\t\t\t\tval = cursor.getFloat(i);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Cursor.FIELD_TYPE_INTEGER:\n\t\t\t\t\tval = cursor.getLong(i);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Cursor.FIELD_TYPE_STRING:\n\t\t\t\t\tval = cursor.getString(i);\n\t\t\t\t\tbreak;\n\t\t\t\tcase Cursor.FIELD_TYPE_NULL:\n\t\t\t\tdefault:\n\t\t\t\t\tval = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Log.d(\"nononsenseapps db\", \"legacy notes col: \" + val);\n\t\t\tretval[i] = val;\n\t\t}\n\t\treturn retval;\n\t}\n}", "public class Task extends DAO {\n\n\t// Used to separate tasks with due dates from completed and from tasks with\n\t// no date\n\tpublic static final String SECRET_TYPEID = \"secret_typeid\";\n\tpublic static final String SECRET_TYPEID2 = \"secret_typeid2\";\n\n\t// SQL convention says Table name should be \"singular\"\n\tpublic static final String TABLE_NAME = \"task\";\n\tpublic static final String DELETE_TABLE_NAME = \"deleted_task\";\n\tpublic static final String FTS3_DELETE_TABLE_NAME = \"fts3_deleted_task\";\n\tpublic static final String HISTORY_TABLE_NAME = \"history\";\n\tprivate static final String SECTIONED_DATE_VIEW = \"sectioned_date_view\";\n\tpublic static final String FTS3_TABLE_NAME = \"fts3_task\";\n private static final String TAG = \"Task\";\n\n public static String getSECTION_DATE_VIEW_NAME(final String listId) {\n\t\t// listId CAN be null. Hence the string concat hack\n\t\treturn new StringBuilder().append(SECTIONED_DATE_VIEW).append(\"_\")\n\t\t\t\t.append(\"\" + listId).toString();\n\t}\n\n\t// Used in sectioned view date\n\tstatic final String FAR_FUTURE = \"strftime('%s','3999-01-01') * 1000\";\n\tpublic static final String OVERDUE = \"strftime('%s', '1970-01-01') * 1000\";\n\t// Today should be from NOW...\n\tpublic static final String TODAY_START = \"strftime('%s','now', 'utc') * 1000\";\n\n\t// static final String TODAY_START =\n\t// \"strftime('%s','now','localtime','start of day', 'utc') * 1000\";\n\n\tpublic static final String TODAY_PLUS(final int offset) {\n\t\treturn \"strftime('%s','now','localtime','+\" + Integer.toString(offset)\n\t\t\t\t+ \" days','start of day', 'utc') * 1000\";\n\t}\n\n\t// Code used to decode title of date header\n\tpublic static final String HEADER_KEY_TODAY = \"today+0\";\n\tpublic static final String HEADER_KEY_PLUS1 = \"today+1\";\n\tpublic static final String HEADER_KEY_PLUS2 = \"today+2\";\n\tpublic static final String HEADER_KEY_PLUS3 = \"today+3\";\n\tpublic static final String HEADER_KEY_PLUS4 = \"today+4\";\n\tpublic static final String HEADER_KEY_OVERDUE = \"overdue\";\n\tpublic static final String HEADER_KEY_LATER = \"later\";\n\tpublic static final String HEADER_KEY_NODATE = \"nodate\";\n\tpublic static final String HEADER_KEY_COMPLETE = \"complete\";\n\n\tpublic static final String CONTENT_TYPE = \"vnd.android.cursor.item/vnd.nononsenseapps.note\";\n\n\tpublic static final Uri URI = Uri.withAppendedPath(\n\t\t\tUri.parse(MyContentProvider.SCHEME + MyContentProvider.AUTHORITY),\n\t\t\tTABLE_NAME);\n\n\tpublic static Uri getUri(final long id) {\n\t\treturn Uri.withAppendedPath(URI, Long.toString(id));\n\t}\n\n\tpublic static final int BASEURICODE = 201;\n\tpublic static final int BASEITEMCODE = 202;\n\tpublic static final int DELETEDQUERYCODE = 209;\n\tpublic static final int DELETEDITEMCODE = 210;\n\tpublic static final int SECTIONEDDATEQUERYCODE = 211;\n\tpublic static final int SECTIONEDDATEITEMCODE = 212;\n\tpublic static final int HISTORYQUERYCODE = 213;\n\tpublic static final int MOVEITEMLEFTCODE = 214;\n\tpublic static final int MOVEITEMRIGHTCODE = 215;\n\t// Legacy support, these also need to use legacy projections\n\tpublic static final int LEGACYBASEURICODE = 221;\n\tpublic static final int LEGACYBASEITEMCODE = 222;\n\tpublic static final int LEGACYVISIBLEURICODE = 223;\n\tpublic static final int LEGACYVISIBLEITEMCODE = 224;\n\t// Search URI\n\tpublic static final int SEARCHCODE = 299;\n\tpublic static final int SEARCHSUGGESTIONSCODE = 298;\n\n\tpublic static void addMatcherUris(UriMatcher sURIMatcher) {\n\t\tsURIMatcher\n\t\t\t\t.addURI(MyContentProvider.AUTHORITY, TABLE_NAME, BASEURICODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/#\",\n\t\t\t\tBASEITEMCODE);\n\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ MOVEITEMLEFT + \"/#\", MOVEITEMLEFTCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ MOVEITEMRIGHT + \"/#\", MOVEITEMRIGHTCODE);\n\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ DELETEDQUERY, DELETEDQUERYCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ DELETEDQUERY + \"/#\", DELETEDITEMCODE);\n\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ SECTIONED_DATE_VIEW, SECTIONEDDATEQUERYCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ SECTIONED_DATE_VIEW + \"/#\", SECTIONEDDATEITEMCODE);\n\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ HISTORY_TABLE_NAME, HISTORYQUERYCODE);\n\n\t\t// Legacy URIs\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Notes.NOTES, LEGACYBASEURICODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Notes.NOTES + \"/#\", LEGACYBASEITEMCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Notes.VISIBLE_NOTES,\n\t\t\t\tLEGACYVISIBLEURICODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Notes.VISIBLE_NOTES + \"/#\",\n\t\t\t\tLEGACYVISIBLEITEMCODE);\n\n\t\t// Search URI\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, FTS3_TABLE_NAME,\n\t\t\t\tSEARCHCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tSearchManager.SUGGEST_URI_PATH_QUERY, SEARCHSUGGESTIONSCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tSearchManager.SUGGEST_URI_PATH_QUERY + \"/*\",\n\t\t\t\tSEARCHSUGGESTIONSCODE);\n\n\t}\n\n\tpublic static final String TARGETPOS = \"targetpos\";\n\tprivate static final String MOVEITEMLEFT = \"moveitemleft\";\n\tprivate static final String MOVEITEMRIGHT = \"moveitemright\";\n\tprivate static final String DELETEDQUERY = \"deletedquery\";\n\n\t// Special URI to look at backup table\n\tpublic static final Uri URI_DELETED_QUERY = Uri.withAppendedPath(URI,\n\t\t\tDELETEDQUERY);\n\n\t// Query the view with date section headers\n\tpublic static final Uri URI_SECTIONED_BY_DATE = Uri.withAppendedPath(URI,\n\t\t\tSECTIONED_DATE_VIEW);\n\n\t// Query for history of tasks\n\tpublic static final Uri URI_TASK_HISTORY = Uri.withAppendedPath(URI,\n\t\t\tHISTORY_TABLE_NAME);\n\n\t// Search URI\n\tpublic static final Uri URI_SEARCH = Uri.withAppendedPath(\n\t\t\tUri.parse(MyContentProvider.SCHEME + MyContentProvider.AUTHORITY),\n\t\t\tFTS3_TABLE_NAME);\n\n\t// Special URI to use when a move is requested\n\t// public static final Uri URI_WRITE_MOVESUBTREE = Uri.withAppendedPath(URI,\n\t// MOVESUBTREE);\n\tprivate static final Uri URI_WRITE_MOVEITEMLEFT = Uri.withAppendedPath(URI,\n\t\t\tMOVEITEMLEFT);\n\tprivate static final Uri URI_WRITE_MOVEITEMRIGHT = Uri.withAppendedPath(\n\t\t\tURI, MOVEITEMRIGHT);\n\n\t// public Uri getMoveSubTreeUri() {\n\t// if (_id < 1) {\n\t// throw new InvalidParameterException(\n\t// \"_ID of this object is not valid\");\n\t// }\n\t// return Uri.withAppendedPath(URI_WRITE_MOVESUBTREE, Long.toString(_id));\n\t// }\n\tprivate Uri getMoveItemLeftUri() {\n\t\tif (_id < 1) {\n\t\t\tthrow new InvalidParameterException(\n\t\t\t\t\t\"_ID of this object is not valid\");\n\t\t}\n\t\treturn Uri.withAppendedPath(URI_WRITE_MOVEITEMLEFT, Long.toString(_id));\n\t}\n\n\tprivate Uri getMoveItemRightUri() {\n\t\tif (_id < 1) {\n\t\t\tthrow new InvalidParameterException(\n\t\t\t\t\t\"_ID of this object is not valid\");\n\t\t}\n\t\treturn Uri\n\t\t\t\t.withAppendedPath(URI_WRITE_MOVEITEMRIGHT, Long.toString(_id));\n\t}\n\n public static int delete(final long id, Context context) {\n if (id > 0) {\n return context.getContentResolver()\n .delete(Uri.withAppendedPath(Uri.withAppendedPath(\n Uri.parse(MyContentProvider.SCHEME + MyContentProvider.AUTHORITY),\n TABLE_NAME), Long.toString(id)),\n null,\n null);\n }\n throw new IllegalArgumentException(\"Can only delete positive ids\");\n }\n\n\tpublic static class Columns implements BaseColumns {\n\n\t\tprivate Columns() {\n\t\t}\n\n\t\tpublic static final String TITLE = \"title\";\n\t\tpublic static final String NOTE = \"note\";\n\t\tpublic static final String DBLIST = \"dblist\";\n\t\tpublic static final String COMPLETED = \"completed\";\n\t\tpublic static final String DUE = \"due\";\n\t\tpublic static final String UPDATED = \"updated\";\n\t\tpublic static final String LOCKED = \"locked\";\n\n\t\tpublic static final String LEFT = \"lft\";\n\t\tpublic static final String RIGHT = \"rgt\";\n\n\t\tpublic static final String[] FIELDS = { _ID, TITLE, NOTE, COMPLETED,\n\t\t\t\tDUE, UPDATED, LEFT, RIGHT, DBLIST, LOCKED };\n\t\tpublic static final String[] FIELDS_NO_ID = { TITLE, NOTE, COMPLETED,\n\t\t\t\tDUE, UPDATED, LEFT, RIGHT, DBLIST, LOCKED };\n\t\tpublic static final String[] SHALLOWFIELDS = { _ID, TITLE, NOTE,\n\t\t\t\tDBLIST, COMPLETED, DUE, UPDATED, LOCKED };\n\t\tpublic static final String TRIG_DELETED = \"deletedtime\";\n\t\tpublic static final String HIST_TASK_ID = \"taskid\";\n\t\t// Used to read the table. Deleted field set by database\n\t\tpublic static final String[] DELETEFIELDS = { _ID, TITLE, NOTE,\n\t\t\t\tCOMPLETED, DUE, DBLIST, TRIG_DELETED };\n\t\t// Used in trigger creation\n\t\tprivate static final String[] DELETEFIELDS_TRIGGER = { TITLE, NOTE,\n\t\t\t\tCOMPLETED, DUE, DBLIST };\n\n\t\t// accessible fields in history table\n\t\tpublic static final String[] HISTORY_COLUMNS = { Columns.HIST_TASK_ID,\n\t\t\t\tColumns.TITLE, Columns.NOTE };\n\t\tpublic static final String[] HISTORY_COLUMNS_UPDATED = { Columns.HIST_TASK_ID,\n\t\t\tColumns.TITLE, Columns.NOTE, Columns.UPDATED };\n\n\t}\n\n\tpublic static final String CREATE_TABLE = new StringBuilder(\"CREATE TABLE \")\n\t\t\t.append(TABLE_NAME)\n\t\t\t.append(\"(\")\n\t\t\t.append(Columns._ID)\n\t\t\t.append(\" INTEGER PRIMARY KEY,\")\n\t\t\t.append(Columns.TITLE)\n\t\t\t.append(\" TEXT NOT NULL DEFAULT '',\")\n\t\t\t.append(Columns.NOTE)\n\t\t\t.append(\" TEXT NOT NULL DEFAULT '',\")\n\t\t\t// These are all msec times\n\t\t\t.append(Columns.COMPLETED)\n\t\t\t.append(\" INTEGER DEFAULT NULL,\")\n\t\t\t.append(Columns.UPDATED)\n\t\t\t.append(\" INTEGER DEFAULT NULL,\")\n\t\t\t.append(Columns.DUE)\n\t\t\t.append(\" INTEGER DEFAULT NULL,\")\n\t\t\t// boolean, 1 for locked, unlocked otherwise\n\t\t\t.append(Columns.LOCKED)\n\t\t\t.append(\" INTEGER NOT NULL DEFAULT 0,\")\n\n\t\t\t// position stuff\n\t\t\t.append(Columns.LEFT)\n\t\t\t.append(\" INTEGER NOT NULL DEFAULT 1,\")\n\t\t\t.append(Columns.RIGHT)\n\t\t\t.append(\" INTEGER NOT NULL DEFAULT 2,\")\n\t\t\t.append(Columns.DBLIST)\n\t\t\t.append(\" INTEGER NOT NULL,\")\n\n\t\t\t// Positions must be positive and ordered!\n\t\t\t.append(\" CHECK(\")\n\t\t\t.append(Columns.LEFT)\n\t\t\t.append(\" > 0), \")\n\t\t\t.append(\" CHECK(\")\n\t\t\t.append(Columns.RIGHT)\n\t\t\t.append(\" > 1), \")\n\t\t\t// Each side's value should be unique in it's list\n\t\t\t// Handled in trigger\n\t\t\t// ).append(\" UNIQUE(\").append(Columns.LEFT).append(\", \").append(Columns.DBLIST).append(\")\"\n\t\t\t// ).append(\" UNIQUE(\").append(Columns.RIGHT).append(\", \").append(Columns.DBLIST).append(\")\"\n\n\t\t\t// Foreign key for list\n\t\t\t.append(\"FOREIGN KEY(\").append(Columns.DBLIST)\n\t\t\t.append(\") REFERENCES \").append(TaskList.TABLE_NAME).append(\"(\")\n\t\t\t.append(TaskList.Columns._ID).append(\") ON DELETE CASCADE\")\n\t\t\t.append(\")\")\n\n\t\t\t.toString();\n\n\t// Delete table has no constraints. In fact, list values and positions\n\t// should not even be thought of as valid.\n\tpublic static final String CREATE_DELETE_TABLE = new StringBuilder(\n\t\t\t\"CREATE TABLE \").append(DELETE_TABLE_NAME).append(\"(\")\n\t\t\t.append(Columns._ID).append(\" INTEGER PRIMARY KEY,\")\n\t\t\t.append(Columns.TITLE).append(\" TEXT NOT NULL DEFAULT '',\")\n\t\t\t.append(Columns.NOTE).append(\" TEXT NOT NULL DEFAULT '',\")\n\t\t\t.append(Columns.COMPLETED).append(\" INTEGER DEFAULT NULL,\")\n\t\t\t.append(Columns.DUE).append(\" INTEGER DEFAULT NULL,\")\n\t\t\t.append(Columns.DBLIST).append(\" INTEGER DEFAULT NULL,\")\n\t\t\t.append(Columns.TRIG_DELETED)\n\t\t\t.append(\" TIMESTAMP NOT NULL DEFAULT current_timestamp\")\n\t\t\t.append(\")\").toString();\n\n\t// Every change to a note gets saved here\n\tpublic static final String CREATE_HISTORY_TABLE = new StringBuilder(\n\t\t\t\"CREATE TABLE \").append(HISTORY_TABLE_NAME).append(\"(\")\n\t\t\t.append(Columns._ID).append(\" INTEGER PRIMARY KEY,\")\n\t\t\t.append(Columns.HIST_TASK_ID).append(\" INTEGER NOT NULL,\")\n\t\t\t.append(Columns.TITLE).append(\" TEXT NOT NULL DEFAULT '',\")\n\t\t\t.append(Columns.NOTE).append(\" TEXT NOT NULL DEFAULT '',\")\n\t\t\t.append(Columns.UPDATED)\n\t\t\t.append(\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\")\n\t\t\t.append(\" FOREIGN KEY(\").append(Columns.HIST_TASK_ID)\n\t\t\t.append(\" ) REFERENCES \").append(TABLE_NAME).append(\" ( \")\n\t\t\t.append(Columns._ID).append(\") ON DELETE CASCADE \").append(\" ) \")\n\t\t\t.toString();\n\tstatic final String HISTORY_TRIGGER_BODY = new StringBuilder(\n\t\t\t\" INSERT INTO \")\n\t\t\t.append(HISTORY_TABLE_NAME)\n\t\t\t.append(\" (\")\n\t\t\t.append(arrayToCommaString(Columns.HISTORY_COLUMNS))\n\t\t\t.append(\")\")\n\t\t\t.append(\" VALUES (\")\n\t\t\t.append(arrayToCommaString(\"new.\", new String[] { Columns._ID,\n\t\t\t\t\tColumns.TITLE, Columns.NOTE })).append(\");\").toString();\n\tpublic static final String HISTORY_UPDATE_TRIGGER_NAME = \"trigger_update_\" + HISTORY_TABLE_NAME;\n\tpublic static final String CREATE_HISTORY_UPDATE_TRIGGER = new StringBuilder(\n\t\t\t\"CREATE TRIGGER \").append(HISTORY_UPDATE_TRIGGER_NAME)\n\t\t\t.append(\" AFTER UPDATE OF \")\n\t\t\t.append(arrayToCommaString(new String[] { Columns.TITLE,\n\t\t\t\t\tColumns.NOTE })).append(\" ON \").append(TABLE_NAME)\n\n\t\t\t.append(\" WHEN old.\")\n\t\t\t.append(Columns.TITLE).append(\" IS NOT new.\")\n\t\t\t.append(Columns.TITLE).append(\" OR old.\")\n\t\t\t.append(Columns.NOTE).append(\" IS NOT new.\")\n\t\t\t.append(Columns.NOTE)\n\n\t\t\t.append(\" BEGIN \").append(HISTORY_TRIGGER_BODY).append(\" END;\")\n\t\t\t.toString();\n\tpublic static final String CREATE_HISTORY_INSERT_TRIGGER = new StringBuilder(\n\t\t\t\"CREATE TRIGGER trigger_insert_\").append(HISTORY_TABLE_NAME)\n\t\t\t.append(\" AFTER INSERT ON \").append(TABLE_NAME).append(\" BEGIN \")\n\t\t\t.append(HISTORY_TRIGGER_BODY).append(\" END;\").toString();\n\n\t// Delete search table\n\tpublic static final String CREATE_FTS3_DELETE_TABLE = \"CREATE VIRTUAL TABLE \"\n\t\t\t+ FTS3_DELETE_TABLE_NAME\n\t\t\t+ \" USING FTS3(\"\n\t\t\t+ Columns._ID\n\t\t\t+ \", \"\n\t\t\t+ Columns.TITLE + \", \" + Columns.NOTE + \");\";\n\tpublic static final String CREATE_FTS3_DELETED_INSERT_TRIGGER = new StringBuilder()\n\t\t\t.append(\"CREATE TRIGGER deletedtask_fts3_insert AFTER INSERT ON \")\n\t\t\t.append(DELETE_TABLE_NAME)\n\t\t\t.append(\" BEGIN \")\n\t\t\t.append(\" INSERT INTO \")\n\t\t\t.append(FTS3_DELETE_TABLE_NAME)\n\t\t\t.append(\" (\")\n\t\t\t.append(arrayToCommaString(Columns._ID, Columns.TITLE, Columns.NOTE))\n\t\t\t.append(\") VALUES (\")\n\t\t\t.append(arrayToCommaString(\"new.\", new String[] { Columns._ID,\n\t\t\t\t\tColumns.TITLE, Columns.NOTE })).append(\");\")\n\t\t\t.append(\" END;\").toString();\n\n\tpublic static final String CREATE_FTS3_DELETED_UPDATE_TRIGGER = new StringBuilder()\n\t\t\t.append(\"CREATE TRIGGER deletedtask_fts3_update AFTER UPDATE OF \")\n\t\t\t.append(arrayToCommaString(new String[] { Columns.TITLE,\n\t\t\t\t\tColumns.NOTE })).append(\" ON \").append(DELETE_TABLE_NAME)\n\t\t\t.append(\" BEGIN \").append(\" UPDATE \")\n\t\t\t.append(FTS3_DELETE_TABLE_NAME).append(\" SET \")\n\t\t\t.append(Columns.TITLE).append(\" = new.\").append(Columns.TITLE)\n\t\t\t.append(\",\").append(Columns.NOTE).append(\" = new.\")\n\t\t\t.append(Columns.NOTE).append(\" WHERE \").append(Columns._ID)\n\t\t\t.append(\" IS new.\").append(Columns._ID).append(\";\").append(\" END;\")\n\t\t\t.toString();\n\tpublic static final String CREATE_FTS3_DELETED_DELETE_TRIGGER = new StringBuilder()\n\t\t\t.append(\"CREATE TRIGGER deletedtask_fts3_delete AFTER DELETE ON \")\n\t\t\t.append(DELETE_TABLE_NAME).append(\" BEGIN \")\n\t\t\t.append(\" DELETE FROM \").append(FTS3_DELETE_TABLE_NAME)\n\t\t\t.append(\" WHERE \").append(Columns._ID).append(\" IS old.\")\n\t\t\t.append(Columns._ID).append(\";\").append(\" END;\").toString();\n\n\t// Search table\n\tpublic static final String CREATE_FTS3_TABLE = \"CREATE VIRTUAL TABLE \"\n\t\t\t+ FTS3_TABLE_NAME + \" USING FTS3(\" + Columns._ID + \", \"\n\t\t\t+ Columns.TITLE + \", \" + Columns.NOTE + \");\";\n\n\tpublic static final String CREATE_FTS3_INSERT_TRIGGER = new StringBuilder()\n\t\t\t.append(\"CREATE TRIGGER task_fts3_insert AFTER INSERT ON \")\n\t\t\t.append(TABLE_NAME)\n\t\t\t.append(\" BEGIN \")\n\t\t\t.append(\" INSERT INTO \")\n\t\t\t.append(FTS3_TABLE_NAME)\n\t\t\t.append(\" (\")\n\t\t\t.append(arrayToCommaString(Columns._ID, Columns.TITLE, Columns.NOTE))\n\t\t\t.append(\") VALUES (\")\n\t\t\t.append(arrayToCommaString(\"new.\", new String[] { Columns._ID,\n\t\t\t\t\tColumns.TITLE, Columns.NOTE })).append(\");\")\n\t\t\t.append(\" END;\").toString();\n\n\tpublic static final String CREATE_FTS3_UPDATE_TRIGGER = new StringBuilder()\n\t\t\t.append(\"CREATE TRIGGER task_fts3_update AFTER UPDATE OF \")\n\t\t\t.append(arrayToCommaString(new String[] { Columns.TITLE,\n\t\t\t\t\tColumns.NOTE })).append(\" ON \").append(TABLE_NAME)\n\t\t\t.append(\" BEGIN \").append(\" UPDATE \").append(FTS3_TABLE_NAME)\n\t\t\t.append(\" SET \").append(Columns.TITLE).append(\" = new.\")\n\t\t\t.append(Columns.TITLE).append(\",\").append(Columns.NOTE)\n\t\t\t.append(\" = new.\").append(Columns.NOTE).append(\" WHERE \")\n\t\t\t.append(Columns._ID).append(\" IS new.\").append(Columns._ID)\n\t\t\t.append(\";\").append(\" END;\").toString();\n\n\tpublic static final String CREATE_FTS3_DELETE_TRIGGER = new StringBuilder()\n\t\t\t.append(\"CREATE TRIGGER task_fts3_delete AFTER DELETE ON \")\n\t\t\t.append(TABLE_NAME).append(\" BEGIN \").append(\" DELETE FROM \")\n\t\t\t.append(FTS3_TABLE_NAME).append(\" WHERE \").append(Columns._ID)\n\t\t\t.append(\" IS old.\").append(Columns._ID).append(\";\").append(\" END;\")\n\t\t\t.toString();\n\n\t/**\n\t * This is a view which returns the tasks in the specified list with headers\n\t * suitable for dates, if any tasks would be sorted under them. Provider\n\t * hardcodes the sort order for this.\n\t *\n\t * if listId is null, will return for all lists\n\t */\n\tpublic static final String CREATE_SECTIONED_DATE_VIEW(final String listId) {\n\t\tfinal String sListId = listId == null ? \" NOT NULL \" : \"'\" + listId\n\t\t\t\t+ \"'\";\n\t\treturn new StringBuilder()\n\t\t\t\t.append(\"CREATE TEMP VIEW IF NOT EXISTS \")\n\t\t\t\t.append(getSECTION_DATE_VIEW_NAME(listId))\n\t\t\t\t// Tasks WITH dates NOT completed, secret 0\n\t\t\t\t.append(\" AS SELECT \")\n\t\t\t\t.append(arrayToCommaString(Columns.FIELDS))\n\t\t\t\t.append(\",0\")\n\t\t\t\t.append(\" AS \")\n\t\t\t\t.append(SECRET_TYPEID)\n\t\t\t\t.append(\",1\")\n\t\t\t\t.append(\" AS \")\n\t\t\t\t.append(SECRET_TYPEID2)\n\t\t\t\t.append(\" FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS null \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" IS NOT null \")\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t// Tasks NO dates NOT completed, secret 1\n\t\t\t\t.append(\" SELECT \")\n\t\t\t\t.append(arrayToCommaString(Columns.FIELDS))\n\t\t\t\t.append(\",1\")\n\t\t\t\t.append(\" AS \")\n\t\t\t\t.append(SECRET_TYPEID)\n\t\t\t\t.append(\",1\")\n\t\t\t\t.append(\" AS \")\n\t\t\t\t.append(SECRET_TYPEID2)\n\t\t\t\t.append(\" FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS null \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" IS null \")\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t// Tasks completed, secret 2 + 1\n\t\t\t\t.append(\" SELECT \")\n\t\t\t\t.append(arrayToCommaString(Columns.FIELDS))\n\t\t\t\t.append(\",3\")\n\t\t\t\t.append(\" AS \")\n\t\t\t\t.append(SECRET_TYPEID)\n\t\t\t\t.append(\",1\")\n\t\t\t\t.append(\" AS \")\n\t\t\t\t.append(SECRET_TYPEID2)\n\t\t\t\t.append(\" FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NOT null \")\n\t\t\t\t// TODAY\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, TODAY_START, Columns.TITLE,\n\t\t\t\t\t\tHEADER_KEY_TODAY, Columns.DBLIST, listId))\n\t\t\t\t.append(\",0,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NULL \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" BETWEEN \")\n\t\t\t\t.append(TODAY_START)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(TODAY_PLUS(1))\n\t\t\t\t.append(\") \")\n\t\t\t\t// TOMORROW (Today + 1)\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, TODAY_PLUS(1), Columns.TITLE,\n\t\t\t\t\t\tHEADER_KEY_PLUS1, Columns.DBLIST, listId))\n\t\t\t\t.append(\",0,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NULL \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" BETWEEN \")\n\t\t\t\t.append(TODAY_PLUS(1))\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(TODAY_PLUS(2))\n\t\t\t\t.append(\") \")\n\t\t\t\t// Today + 2\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, TODAY_PLUS(2), Columns.TITLE,\n\t\t\t\t\t\tHEADER_KEY_PLUS2, Columns.DBLIST, listId))\n\t\t\t\t.append(\",0,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NULL \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" BETWEEN \")\n\t\t\t\t.append(TODAY_PLUS(2))\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(TODAY_PLUS(3))\n\t\t\t\t.append(\") \")\n\t\t\t\t// Today + 3\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, TODAY_PLUS(3), Columns.TITLE,\n\t\t\t\t\t\tHEADER_KEY_PLUS3, Columns.DBLIST, listId))\n\t\t\t\t.append(\",0,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NULL \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" BETWEEN \")\n\t\t\t\t.append(TODAY_PLUS(3))\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(TODAY_PLUS(4))\n\t\t\t\t.append(\") \")\n\t\t\t\t// Today + 4\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, TODAY_PLUS(4), Columns.TITLE,\n\t\t\t\t\t\tHEADER_KEY_PLUS4, Columns.DBLIST, listId))\n\t\t\t\t.append(\",0,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NULL \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" BETWEEN \")\n\t\t\t\t.append(TODAY_PLUS(4))\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(TODAY_PLUS(5))\n\t\t\t\t.append(\") \")\n\t\t\t\t// Overdue (0)\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, OVERDUE, Columns.TITLE,\n\t\t\t\t\t\tHEADER_KEY_OVERDUE, Columns.DBLIST, listId))\n\t\t\t\t.append(\",0,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NULL \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" BETWEEN \")\n\t\t\t\t.append(OVERDUE)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(TODAY_START)\n\t\t\t\t.append(\") \")\n\t\t\t\t// Later\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT '-1',\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, TODAY_PLUS(5), Columns.TITLE,\n\t\t\t\t\t\tHEADER_KEY_LATER, Columns.DBLIST, listId))\n\t\t\t\t.append(\",0,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NULL \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" >= \")\n\t\t\t\t.append(TODAY_PLUS(5))\n\t\t\t\t.append(\") \")\n\t\t\t\t// No date\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, \"null\", Columns.TITLE, HEADER_KEY_NODATE,\n\t\t\t\t\t\tColumns.DBLIST, listId))\n\t\t\t\t.append(\",1,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \")\n\t\t\t\t.append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \")\n\t\t\t\t.append(Columns.DBLIST)\n\t\t\t\t.append(\" IS \")\n\t\t\t\t.append(sListId)\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.DUE)\n\t\t\t\t.append(\" IS null \")\n\t\t\t\t.append(\" AND \")\n\t\t\t\t.append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS null \")\n\t\t\t\t.append(\") \")\n\t\t\t\t// Complete, overdue to catch all\n\t\t\t\t// Set complete time to 1\n\t\t\t\t.append(\" UNION ALL \")\n\t\t\t\t.append(\" SELECT -1,\")\n\t\t\t\t.append(asEmptyCommaStringExcept(Columns.FIELDS_NO_ID,\n\t\t\t\t\t\tColumns.DUE, OVERDUE, Columns.COMPLETED, \"1\",\n\t\t\t\t\t\tColumns.TITLE, HEADER_KEY_COMPLETE, Columns.DBLIST,\n\t\t\t\t\t\tlistId))\n\t\t\t\t.append(\",2,0\")\n\t\t\t\t// Only show header if there are tasks under it\n\t\t\t\t.append(\" WHERE EXISTS(SELECT _ID FROM \").append(TABLE_NAME)\n\t\t\t\t.append(\" WHERE \").append(Columns.DBLIST).append(\" IS \")\n\t\t\t\t.append(sListId).append(\" AND \").append(Columns.COMPLETED)\n\t\t\t\t.append(\" IS NOT null \").append(\") \")\n\n\t\t\t\t.append(\";\").toString();\n\t}\n\n\tpublic String title = null;\n\tpublic String note = null;\n\t// All milliseconds since 1970-01-01 UTC\n\tpublic Long completed = null;\n\tpublic Long due = null;\n\tpublic Long updated = null;\n\t// converted from integer\n\tpublic boolean locked = false;\n\n\t// position stuff\n\tpublic Long left = null;\n\tpublic Long right = null;\n\tpublic Long dblist = null;\n\n\tpublic Task() {\n\n\t}\n\n\t/**\n\t * Resets id and position values\n\t */\n\tpublic void resetForInsertion() {\n\t\t_id = -1;\n\t\tleft = null;\n\t\tright = null;\n\t}\n\n\t/**\n\t * Set task as completed. Returns the time stamp that is set.\n\t */\n\tpublic Long setAsCompleted() {\n\n\t\tfinal Time time = new Time(Time.TIMEZONE_UTC);\n\t\ttime.setToNow();\n\t\tcompleted = new Time().toMillis(false);\n\t\treturn completed;\n\t}\n\n\t/**\n\t * Set first line as title, rest as note.\n\t *\n\t * @param text\n\t */\n\tpublic void setText(final String text) {\n\t\tint titleEnd = text.indexOf(\"\\n\");\n\n\t\tif (titleEnd < 0) {\n\t\t\ttitleEnd = text.length();\n\t\t}\n\n\t\ttitle = text.substring(0, titleEnd);\n\t\tif (titleEnd + 1 < text.length()) {\n\t\t\tnote = text.substring(titleEnd + 1, text.length());\n\t\t}\n\t\telse {\n\t\t\tnote = \"\";\n\t\t}\n\t}\n\n\t/**\n\t * Returns a text where first line is title, rest is note\n\t */\n\tpublic String getText() {\n\t\tString result = \"\";\n\t\tif (title != null) {\n\t\t\tresult += title;\n\t\t}\n\t\tif (note != null && !note.isEmpty()) {\n // If title is empty, it should remain so\n\t\t\tresult += \"\\n\" + note;\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic Task(final Cursor c) {\n\t\tthis._id = c.getLong(0);\n\t\tthis.title = c.getString(1);\n\t\tnote = c.getString(2);\n\t\t// msec times which can be null\n\t\tif (!c.isNull(3)) completed = c.getLong(3);\n\t\tif (!c.isNull(4)) due = c.getLong(4);\n\t\tif (!c.isNull(5)) updated = c.getLong(5);\n\n\t\t// enforced not to be null\n\t\tleft = c.getLong(6);\n\t\tright = c.getLong(7);\n\t\tdblist = c.getLong(8);\n\t\tlocked = c.getInt(9) == 1;\n\t}\n\n\tpublic Task(final long id, final ContentValues values) {\n\t\tthis(values);\n\t\tthis._id = id;\n\t}\n\n\tpublic Task(final Uri uri, final ContentValues values) {\n\t\tthis(Long.parseLong(uri.getLastPathSegment()), values);\n\t}\n\n\tpublic Task(final ContentValues values) {\n\t\tif (values != null) {\n\t\t\tif (values.containsKey(TARGETPOS)) {\n\t\t\t\t// Content form getMoveValues\n\t\t\t\tthis.left = values.getAsLong(Columns.LEFT);\n\t\t\t\tthis.right = values.getAsLong(Columns.RIGHT);\n\t\t\t\tthis.dblist = values.getAsLong(Columns.DBLIST);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.title = values.getAsString(Columns.TITLE);\n\t\t\t\tthis.note = values.getAsString(Columns.NOTE);\n\t\t\t\tthis.completed = values.getAsLong(Columns.COMPLETED);\n\t\t\t\tthis.due = values.getAsLong(Columns.DUE);\n\t\t\t\tthis.updated = values.getAsLong(Columns.UPDATED);\n\t\t\t\tthis.locked = values.getAsLong(Columns.LOCKED) == 1;\n\n\t\t\t\tthis.dblist = values.getAsLong(Columns.DBLIST);\n\t\t\t\tthis.left = values.getAsLong(Columns.LEFT);\n\t\t\t\tthis.right = values.getAsLong(Columns.RIGHT);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Task(final JSONObject json) throws JSONException {\n\t\tif (json.has(Columns.TITLE))\n\t\t\tthis.title = json.getString(Columns.TITLE);\n\t\tif (json.has(Columns.NOTE))\n\t\t\tthis.note = json.getString(Columns.NOTE);\n\t\tif (json.has(Columns.COMPLETED))\n\t\t\tthis.completed = json.getLong(Columns.COMPLETED);\n\t\tif (json.has(Columns.DUE))\n\t\t\tthis.due = json.getLong(Columns.DUE);\n\t\tif (json.has(Columns.UPDATED))\n\t\t\tthis.updated = json.getLong(Columns.UPDATED);\n\t\tif (json.has(Columns.LOCKED))\n\t\t\tthis.locked = json.getLong(Columns.LOCKED) == 1;\n\t\tif (json.has(Columns.DBLIST))\n\t\t\tthis.dblist = json.getLong(Columns.DBLIST);\n\t\tif (json.has(Columns.LEFT))\n\t\t\tthis.left = json.getLong(Columns.LEFT);\n\t\tif (json.has(Columns.RIGHT))\n\t\t\tthis.right = json.getLong(Columns.RIGHT);\n\t}\n\n\t/**\n\t * A move operation should be performed alone. No other information should\n\t * accompany such an update.\n\t */\n\tpublic ContentValues getMoveValues(final long targetPos) {\n\t\tfinal ContentValues values = new ContentValues();\n\t\tvalues.put(TARGETPOS, targetPos);\n\t\tvalues.put(Columns.LEFT, left);\n\t\tvalues.put(Columns.RIGHT, right);\n\t\tvalues.put(Columns.DBLIST, dblist);\n\t\treturn values;\n\t}\n\n\t/**\n\t * Use this for regular updates of the task.\n\t */\n\t@Override\n\tpublic ContentValues getContent() {\n\t\tfinal ContentValues values = new ContentValues();\n\t\t// Note that ID is NOT included here\n\t\tif (title != null) values.put(Columns.TITLE, title);\n\t\tif (note != null) values.put(Columns.NOTE, note);\n\n\t\tif (dblist != null) values.put(Columns.DBLIST, dblist);\n\t\t// Never write position values unless you are 110% sure that they are correct\n\t\t//if (left != null) values.put(Columns.LEFT, left);\n\t\t//if (right != null) values.put(Columns.RIGHT, right);\n\n\t\tvalues.put(Columns.UPDATED, updated);\n\t\tvalues.put(Columns.DUE, due);\n\t\tvalues.put(Columns.COMPLETED, completed);\n\t\tvalues.put(Columns.LOCKED, locked ? 1 : 0);\n\n\t\treturn values;\n\t}\n\n\t/**\n\t * Compares this task to another and returns true if their contents are the\n\t * same. Content is defined as: title, note, duedate, completed != null\n\t * Returns false if title or note are null.\n\t *\n\t * The intended usage is the editor where content and not id's or position\n\t * are of importance.\n\t */\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tboolean result = false;\n\n\t\tif (o instanceof Task) {\n\t\t\tfinal Task other = (Task) o;\n\t\t\tresult = true;\n\n\t\t\tresult &= (title != null && title.equals(other.title));\n\t\t\tresult &= (note != null && note.equals(other.note));\n\t\t\tresult &= (due == other.due);\n\t\t\tresult &= ((completed != null) == (other.completed != null));\n\n\t\t}\n\t\telse {\n\t\t\tresult = super.equals(o);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Convenience method for normal operations. Updates \"updated\" field to\n\t * specified Returns number of db-rows affected. Fail if < 1\n\t */\n\tpublic int save(final Context context, final long updated) {\n\t\tint result = 0;\n\t\tthis.updated = updated;\n\t\tif (_id < 1) {\n\t\t\tfinal Uri uri = context.getContentResolver().insert(getBaseUri(),\n\t\t\t\t\tgetContent());\n\t\t\tif (uri != null) {\n\t\t\t\t_id = Long.parseLong(uri.getLastPathSegment());\n\t\t\t\tresult++;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tresult += context.getContentResolver().update(getUri(),\n\t\t\t\t\tgetContent(), null, null);\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Convenience method for normal operations. Updates \"updated\" field.\n\t * Returns number of db-rows affected. Fail if < 1\n\t */\n\t@Override\n\tpublic int save(final Context context) {\n\t\treturn save(context, Calendar.getInstance().getTimeInMillis());\n\t}\n\n\t/**\n\t * Convenience method to complete tasks in list view for example. Starts an\n\t * asynctask to do the operation in the background.\n\t */\n\tpublic static void setCompleted(final Context context,\n\t\t\tfinal boolean completed, final Long... ids) {\n\t\tif (ids.length > 0) {\n\t\t\tfinal AsyncTask<Long, Void, Void> task = new AsyncTask<Long, Void, Void>() {\n\t\t\t\t@Override\n\t\t\t\tprotected Void doInBackground(final Long... ids) {\n\t\t\t\t\tsetCompletedSynced(context, completed, ids);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t};\n\t\t\ttask.execute(ids);\n\t\t}\n\t}\n\n /**\n * Convenience method to complete tasks. Runs on the thread that called it.\n * @param context\n * @param completed\n * @param ids\n */\n public static void setCompletedSynced(final Context context,\n final boolean completed, final Long... ids) {\n if (ids.length < 1) {\n return;\n }\n\n final ContentValues values = new ContentValues();\n values.put(Columns.COMPLETED, completed ? Calendar\n .getInstance().getTimeInMillis() : null);\n values.put(Columns.UPDATED, Calendar.getInstance()\n .getTimeInMillis());\n String idStrings = \"(\";\n for (Long id : ids) {\n idStrings += id + \",\";\n }\n idStrings = idStrings.substring(0, idStrings.length() - 1);\n idStrings += \")\";\n context.getContentResolver().update(URI, values,\n Columns._ID + \" IN \" + idStrings, null);\n }\n\n\tpublic int moveTo(final ContentResolver resolver, final Task targetTask) {\n\t\tif (targetTask.dblist.longValue() == dblist.longValue()) {\n\t\t\tif (targetTask.left < left) {\n\t\t\t\t// moving left\n\t\t\t\treturn resolver.update(getMoveItemLeftUri(),\n\t\t\t\t\t\tgetMoveValues(targetTask.left), null, null);\n\t\t\t}\n\t\t\telse if (targetTask.right > right) {\n\t\t\t\t// moving right\n\t\t\t\treturn resolver.update(getMoveItemRightUri(),\n\t\t\t\t\t\tgetMoveValues(targetTask.right), null, null);\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\n\t@Override\n\tprotected String getTableName() {\n\t\treturn TABLE_NAME;\n\t}\n\n\t/**\n\t * Can't use unique constraint on positions because SQLite checks\n\t * constraints after every row is updated an not after each statement like\n\t * it should. So have to do the check in a trigger instead.\n\t */\n\tstatic final String countVals(final String col, final String ver) {\n\t\treturn String.format(\"SELECT COUNT(DISTINCT %2$s)\"\n\t\t\t\t+ \" AS ColCount FROM %1$s WHERE %3$s=%4$s.%3$s\", TABLE_NAME,\n\t\t\t\tcol, Columns.DBLIST, ver);\n\t}\n\n\t// verify that left are unique\n\t// count number of id and compare to number of left and right\n\tstatic final String posUniqueConstraint(final String ver, final String msg) {\n\t\treturn String.format(\n\t\t\t\t\" SELECT CASE WHEN ((%1$s) != (%2$s) OR (%1$s) != (%3$s)) THEN \"\n\t\t\t\t\t\t+ \" RAISE (ABORT, '\" + msg + \"')\" + \" END;\",\n\t\t\t\tcountVals(Columns._ID, ver), countVals(Columns.LEFT, ver),\n\t\t\t\tcountVals(Columns.RIGHT, ver));\n\t};\n\n\t// public static final String TRIGGER_POST_UPDATE = String.format(\n\t// \"CREATE TRIGGER task_post_update AFTER UPDATE ON %1$s BEGIN \"\n\t// + posUniqueConstraint(\"new\", \"pos not unique post update\")\n\t// + posUniqueConstraint(\"old\", \"pos not unique post update\")\n\t// + \" END;\", TABLE_NAME);\n\n\t// Makes a gap in the list where the task is being inserted\n\tprivate static final String BUMP_TO_RIGHT = \" UPDATE %1$s SET %2$s = %2$s + 2, %3$s = %3$s + 2 WHERE %3$s >= new.%3$s AND %4$s IS new.%4$s;\";\n\tpublic static final String TRIGGER_PRE_INSERT = String.format(\n\t\t\t\"CREATE TRIGGER task_pre_insert BEFORE INSERT ON %s BEGIN \",\n\t\t\tTABLE_NAME)\n\t\t\t+ String.format(BUMP_TO_RIGHT, TABLE_NAME, Columns.RIGHT,\n\t\t\t\t\tColumns.LEFT, Columns.DBLIST) + \" END;\";\n\n\tpublic static final String TRIGGER_POST_INSERT = String.format(\n\t\t\t\"CREATE TRIGGER task_post_insert AFTER INSERT ON %s BEGIN \",\n\t\t\tTABLE_NAME)\n\t\t\t// Enforce integrity\n\t\t\t+ posUniqueConstraint(\"new\", \"pos not unique post insert\")\n\n\t\t\t+ \" END;\";\n\n\t// Upgrades children and closes the gap made from the delete\n\tprivate static final String BUMP_TO_LEFT = \" UPDATE %1$s SET %2$s = %2$s - 2 WHERE %2$s > old.%3$s AND %4$s IS old.%4$s;\";\n\t// private static final String UPGRADE_CHILDREN =\n\t// \" UPDATE %1$s SET %2$s = %2$s - 1, %3$s = %3$s - 1 WHERE %4$s IS old.%4$s AND %2$s BETWEEN old.%2$s AND old.%3$s;\";\n\tpublic static final String TRIGGER_POST_DELETE = String.format(\n\t\t\t\"CREATE TRIGGER task_post_delete AFTER DELETE ON %s BEGIN \",\n\t\t\tTABLE_NAME)\n\t\t\t// + String.format(UPGRADE_CHILDREN, TABLE_NAME, Columns.LEFT,\n\t\t\t// Columns.RIGHT, Columns.DBLIST)\n\t\t\t+ String.format(BUMP_TO_LEFT, TABLE_NAME, Columns.LEFT,\n\t\t\t\t\tColumns.RIGHT, Columns.DBLIST)\n\t\t\t+ String.format(BUMP_TO_LEFT, TABLE_NAME, Columns.RIGHT,\n\t\t\t\t\tColumns.RIGHT, Columns.DBLIST)\n\n\t\t\t// Enforce integrity\n\t\t\t+ posUniqueConstraint(\"old\", \"pos not unique post delete\")\n\n\t\t\t+ \" END;\";\n\n\tpublic static final String TRIGGER_PRE_DELETE = String.format(\n\t\t\t\"CREATE TRIGGER task_pre_delete BEFORE DELETE ON %1$s BEGIN \"\n\t\t\t\t\t+ \" INSERT INTO %2$s (\"\n\t\t\t\t\t+ arrayToCommaString(\"\", Columns.DELETEFIELDS_TRIGGER, \"\")\n\t\t\t\t\t+ \") \"\n\t\t\t\t\t+ \" VALUES(\"\n\t\t\t\t\t+ arrayToCommaString(\"old.\", Columns.DELETEFIELDS_TRIGGER,\n\t\t\t\t\t\t\t\"\") + \"); \"\n\n\t\t\t\t\t+ \" END;\", TABLE_NAME, DELETE_TABLE_NAME);\n\n\tpublic String getSQLMoveItemLeft(final ContentValues values) {\n\t\tif (!values.containsKey(TARGETPOS)\n\t\t\t\t|| values.getAsLong(TARGETPOS) >= left) {\n\t\t\treturn null;\n\t\t}\n\t\treturn getSQLMoveItem(Columns.LEFT, values.getAsLong(TARGETPOS));\n\t}\n\n\tpublic String getSQLMoveItemRight(final ContentValues values) {\n\t\tif (!values.containsKey(TARGETPOS)\n\t\t\t\t|| values.getAsLong(TARGETPOS) <= right) {\n\t\t\treturn null;\n\t\t}\n\t\treturn getSQLMoveItem(Columns.RIGHT, values.getAsLong(TARGETPOS));\n\t}\n\n\t/*\n\t * Trigger to move between lists\n\t */\n\tpublic static final String TRIGGER_MOVE_LIST = new StringBuilder()\n\t\t\t.append(\"CREATE TRIGGER trigger_post_move_list_\")\n\t\t\t.append(TABLE_NAME)\n\t\t\t.append(\" AFTER UPDATE OF \")\n\t\t\t.append(Task.Columns.DBLIST)\n\t\t\t.append(\" ON \")\n\t\t\t.append(Task.TABLE_NAME)\n\t\t\t.append(\" WHEN old.\")\n\t\t\t.append(Task.Columns.DBLIST)\n\t\t\t.append(\" IS NOT new.\")\n\t\t\t.append(Task.Columns.DBLIST)\n\t\t\t.append(\" BEGIN \")\n\t\t\t// Bump everything to the right, except the item itself (in same\n\t\t\t// list)\n\t\t\t.append(String\n\t\t\t\t\t.format(\"UPDATE %1$s SET %2$s = %2$s + 2, %3$s = %3$s + 2 WHERE %4$s IS new.%4$s AND %5$s IS NOT new.%5$s;\",\n\t\t\t\t\t\t\tTABLE_NAME, Columns.LEFT, Columns.RIGHT,\n\t\t\t\t\t\t\tColumns.DBLIST, Columns._ID))\n\n\t\t\t// Bump everything left in the old list, to the right of position\n\t\t\t.append(String\n\t\t\t\t\t.format(\"UPDATE %1$s SET %2$s = %2$s - 2, %3$s = %3$s - 2 WHERE %2$s > old.%3$s AND %4$s IS old.%4$s;\",\n\t\t\t\t\t\t\tTABLE_NAME, Columns.LEFT, Columns.RIGHT,\n\t\t\t\t\t\t\tColumns.DBLIST))\n\n\t\t\t// Set positions to 1 and 2 for item\n\t\t\t.append(String\n\t\t\t\t\t.format(\"UPDATE %1$s SET %2$s = 1, %3$s = 2 WHERE %4$s IS new.%4$s;\",\n\t\t\t\t\t\t\tTABLE_NAME, Columns.LEFT, Columns.RIGHT,\n\t\t\t\t\t\t\tColumns._ID))\n\n\t\t\t.append(posUniqueConstraint(\"new\", \"Moving list, new positions not unique/ordered\"))\n\t\t\t.append(posUniqueConstraint(\"old\", \"Moving list, old positions not unique/ordered\"))\n\n\t\t\t.append(\" END;\").toString();\n\n\t/**\n\t * If moving left, then edgeCol is left and vice-versa. Values should come\n\t * from getMoveValues\n\t *\n\t * 1 = table name 2 = left 3 = right 4 = edgecol 5 = old.left 6 = old.right\n\t * 7 = target.pos (actually target.edgecol) 8 = dblist 9 = old.dblist\n\t */\n\tprivate String getSQLMoveItem(final String edgeCol, final Long edgeVal) {\n\t\tboolean movingLeft = Columns.LEFT.equals(edgeCol);\n\t\treturn String\n\t\t\t\t.format(new StringBuilder(\"UPDATE %1$s SET \")\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Left item follows Left = Left + ...\n\t\t\t\t\t\t */\n\t\t\t\t\t\t.append(\"%2$s = %2$s + \")\n\t\t\t\t\t\t.append(\" CASE \")\n\t\t\t\t\t\t// Moving item jumps to target pos\n\t\t\t\t\t\t.append(\" WHEN %2$s IS %5$d \")\n\t\t\t\t\t\t// ex: left = 5, target = 2, --> left = 5 + (2 - 5) == 2\n\t\t\t\t\t\t// ex left = 5, target = 9(right), --> left = 5 + (9 - 5\n\t\t\t\t\t\t// - 1) = 8\n\t\t\t\t\t\t.append(\" THEN \")\n\t\t\t\t\t\t.append(\" (%7$d - %5$d\")\n\t\t\t\t\t\t.append(movingLeft ? \") \" : \" -1) \")\n\t\t\t\t\t\t// Sub items take one step opposite\n\t\t\t\t\t\t// Careful if moving inside subtree, which can only\n\t\t\t\t\t\t// happen when moving right.\n\t\t\t\t\t\t// Then only left position changes\n\t\t\t\t\t\t.append(\" WHEN %2$s BETWEEN (%5$d + 1) AND (%6$d - 1) \")\n\t\t\t\t\t\t.append(\" THEN \")\n\t\t\t\t\t\t.append(movingLeft ? \" 1 \" : \" -1 \")\n\t\t\t\t\t\t// Items in between from and to positions take two steps\n\t\t\t\t\t\t// opposite\n\t\t\t\t\t\t.append(\" WHEN %2$s BETWEEN \")\n\t\t\t\t\t\t.append(movingLeft ? \"%7$d\" : \"%6$d\")\n\t\t\t\t\t\t.append(\" AND \")\n\t\t\t\t\t\t.append(movingLeft ? \"%5$d\" : \"%7$d\")\n\t\t\t\t\t\t.append(\" THEN \")\n\t\t\t\t\t\t.append(movingLeft ? \" 2 \" : \" -2 \")\n\t\t\t\t\t\t// Not in target range, no change\n\t\t\t\t\t\t.append(\" ELSE 0 END, \")\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * Right item follows Right = Right + ...\n\t\t\t\t\t\t */\n\t\t\t\t\t\t.append(\" %3$s = %3$s + \")\n\t\t\t\t\t\t.append(\" CASE \")\n\t\t\t\t\t\t// Moving item jumps to target pos\n\t\t\t\t\t\t.append(\" WHEN %3$s IS %6$d \")\n\t\t\t\t\t\t// ex: right = 7, target = 3(left), --> right = 7 + (3 -\n\t\t\t\t\t\t// 7 + 1) == 4\n\t\t\t\t\t\t// ex right = 2, target = 9(right), --> right = 2 + (9 -\n\t\t\t\t\t\t// 2) = 9\n\t\t\t\t\t\t.append(\" THEN \")\n\t\t\t\t\t\t.append(\" (%7$d - %6$d\")\n\t\t\t\t\t\t.append(movingLeft ? \" +1) \" : \") \")\n\t\t\t\t\t\t// Sub items take one step opposite\n\t\t\t\t\t\t.append(\" WHEN %3$s BETWEEN (%5$d + 1) AND (%6$d - 1) \")\n\t\t\t\t\t\t.append(\" THEN \")\n\t\t\t\t\t\t.append(movingLeft ? \" 1 \" : \" -1 \")\n\t\t\t\t\t\t// Items in between from and to positions take two steps\n\t\t\t\t\t\t// opposite\n\t\t\t\t\t\t.append(\" WHEN %3$s BETWEEN \")\n\t\t\t\t\t\t.append(movingLeft ? \"%7$d\" : \"%6$d\").append(\" AND \")\n\t\t\t\t\t\t.append(movingLeft ? \"%5$d\" : \"%7$d\").append(\" THEN \")\n\t\t\t\t\t\t.append(movingLeft ? \" 2 \" : \" -2 \")\n\t\t\t\t\t\t// Not in target range, no change\n\t\t\t\t\t\t.append(\" ELSE 0 END \")\n\t\t\t\t\t\t// And limit to the list in question\n\t\t\t\t\t\t.append(\" WHERE %8$s IS %9$d;\").toString(), TABLE_NAME,\n\t\t\t\t\t\tColumns.LEFT, Columns.RIGHT, edgeCol, left, right,\n\t\t\t\t\t\tedgeVal, Columns.DBLIST, dblist);\n\t}\n\n\t/*\n\t * @SuppressLint(\"DefaultLocale\") public String getSQLMoveSubTree(final\n\t * ContentValues values) { return\n\t * String.format(\"UPDATE %1$s SET %2$s = %2$s + \" +\n\t * \n\t * \" CASE \" + // Tasks are moving left \" WHEN (%4$d < %6$d) \" +\n\t * \n\t * \" THEN CASE \" + \" WHEN %2$s BETWEEN %4$d AND (%6$d - 1) \" + // Then they\n\t * must flow [width] to the right \" THEN %7$d - %6$d + 1 \" +\n\t * \" WHEN %2$s BETWEEN %6$d AND %7$d \" + // Tasks in subtree jump to the\n\t * left // targetleft - left \" THEN %4$d - %6$d \" + // Do nothing otherwise\n\t * \" ELSE 0 END \" + // Tasks are moving right \" WHEN (%4$d > %6$d) \" +\n\t * \" THEN CASE \" + \" WHEN %2$s BETWEEN (%7$d + 1) AND %4$d \" + // Then move\n\t * them [width] to the left \" THEN %6$d - %7$d - 1\" +\n\t * \" WHEN %2$s BETWEEN %6$d AND %7$d \" + // Tasks in subtree jump to the\n\t * right // targetleft - left\n\t * \n\t * // Depends on if we are moving inside a task or // moving an entire one\n\t * \" THEN CASE WHEN %5$d > (%4$d + 1) \" + \" THEN %4$d - %7$d \" +\n\t * \" ELSE %4$d - %7$d + 1 END \" + // Do nothing otherwise \" ELSE 0 END \" +\n\t * // No move actually performed. comma to do right next \" ELSE 0 END, \" +\n\t * \n\t * \" %3$s = %3$s + \" + \" CASE \" + // Tasks are moving left\n\t * \" WHEN (%4$d < %6$d) \" +\n\t * \n\t * \" THEN CASE \" + // but only if right is left of originleft\n\t * \" WHEN %3$s BETWEEN %4$d AND (%6$d - 1)\" + // Then they must flow [width]\n\t * to the right \" THEN %7$d - %6$d + 1\" +\n\t * \" WHEN %2$s BETWEEN %6$d AND %7$d \" + // Tasks in subtree jump to the\n\t * left // targetleft - left \" THEN %4$d - %6$d \" + // Do nothing otherwise\n\t * \" ELSE 0 END \" + // Tasks are moving right \" WHEN (%4$d > %6$d) \" +\n\t * \" THEN CASE \" + // when right is between myright + 1 and targetleft + 1\n\t * \" WHEN %3$s BETWEEN (%7$d + 1) AND (%4$d + 1) \" + // Then move them\n\t * [width] to the left \" THEN %6$d - %7$d - 1\" +\n\t * \" WHEN %2$s BETWEEN %6$d AND %7$d \" + // targetleft - left // Depends on\n\t * if we are moving inside a task or // moving an entire one\n\t * \" THEN CASE WHEN %5$d > (%4$d + 1) \" + \" THEN %4$d - %7$d \" +\n\t * \" ELSE %4$d - %7$d + 1 END \" + // Do nothing otherwise \" ELSE 0 END \" +\n\t * // No move actually performed. End update with semicolon \" ELSE 0 END \" +\n\t * \" WHERE %8$s IS %9$d; \"\n\t * \n\t * //Enforce integrity + posUniqueConstraint(\"new\",\n\t * \"pos not unique move sub tree\") ,\n\t * \n\t * TABLE_NAME, Columns.LEFT, Columns.RIGHT, values.getAsLong(TARGETLEFT),\n\t * values.getAsLong(TARGETRIGHT), left, right, Columns.DBLIST, dblist\n\t * \n\t * ); }\n\t */\n\n\t@Override\n\tpublic String getContentType() {\n\t\treturn CONTENT_TYPE;\n\t}\n}", "public class TaskList extends DAO {\n\n\t// SQL convention says Table name should be \"singular\"\n\tpublic static final String TABLE_NAME = \"tasklist\";\n\tpublic static final Uri URI = Uri.withAppendedPath(\n\t\t\tUri.parse(MyContentProvider.SCHEME + MyContentProvider.AUTHORITY),\n\t\t\tTABLE_NAME);\n\n\tpublic static final String VIEWCOUNT_NAME = \"lists_with_count\";\n\tpublic static final Uri URI_WITH_COUNT = Uri.withAppendedPath(URI,\n\t\t\tVIEWCOUNT_NAME);\n\n\tpublic static Uri getUri(final long id) {\n\t\treturn Uri.withAppendedPath(URI, Long.toString(id));\n\t}\n\n\tpublic static final String CONTENT_TYPE = \"vnd.android.cursor.item/vnd.nononsenseapps.list\";\n\n\tpublic static final int BASEURICODE = 101;\n\tpublic static final int BASEITEMCODE = 102;\n\tpublic static final int VIEWCOUNTCODE = 103;\n\t// Legacy support, these also need to use legacy projections\n\tpublic static final int LEGACYBASEURICODE = 111;\n\tpublic static final int LEGACYBASEITEMCODE = 112;\n\tpublic static final int LEGACYVISIBLEURICODE = 113;\n\tpublic static final int LEGACYVISIBLEITEMCODE = 114;\n\n\t/**\n\t * TaskList URIs start at 101, up to 199\n\t */\n\tpublic static void addMatcherUris(UriMatcher sURIMatcher) {\n\t\tsURIMatcher\n\t\t\t\t.addURI(MyContentProvider.AUTHORITY, TABLE_NAME, BASEURICODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/#\",\n\t\t\t\tBASEITEMCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY, TABLE_NAME + \"/\"\n\t\t\t\t+ VIEWCOUNT_NAME, VIEWCOUNTCODE);\n\n\t\t// Legacy URIs\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Lists.LISTS, LEGACYBASEURICODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Lists.LISTS + \"/#\", LEGACYBASEITEMCODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Lists.VISIBLE_LISTS,\n\t\t\t\tLEGACYVISIBLEURICODE);\n\t\tsURIMatcher.addURI(MyContentProvider.AUTHORITY,\n\t\t\t\tLegacyDBHelper.NotePad.Lists.VISIBLE_LISTS + \"/#\",\n\t\t\t\tLEGACYVISIBLEITEMCODE);\n\t}\n\n\tpublic static class Columns implements BaseColumns {\n\n\t\tprivate Columns() {\n\t\t}\n\n\t\tpublic static final String TITLE = \"title\";\n\t\tpublic static final String UPDATED = \"updated\";\n\t\tpublic static final String LISTTYPE = \"tasktype\";\n\t\tpublic static final String SORTING = \"sorting\";\n\n\t\tpublic static final String VIEW_COUNT = \"count\";\n\n\t\t// public static final String GTASKACCOUNT = \"gtaskaccount\";\n\t\t// public static final String GTASKID = \"gtaskid\";\n\t\t//\n\t\t// // Future proofing\n\t\t// public static final String DROPBOXACCOUNT = \"dropboxaccount\";\n\t\t// public static final String DROPBOXID = \"dropboxid\";\n\n\t\tpublic static final String[] FIELDS = { _ID, TITLE, UPDATED, LISTTYPE,\n\t\t\t\tSORTING };\n\t\t// GTASKACCOUNT, GTASKID, DROPBOXACCOUNT, DROPBOXID };\n\t\tpublic static final String[] SHALLOWFIELDS = { _ID, TITLE, UPDATED };\n\t}\n\n\tpublic static final String CREATE_TABLE = new StringBuilder(\"CREATE TABLE \")\n\t\t\t.append(TABLE_NAME).append(\"(\").append(Columns._ID)\n\t\t\t.append(\" INTEGER PRIMARY KEY,\").append(Columns.TITLE)\n\t\t\t.append(\" TEXT NOT NULL DEFAULT '',\").append(Columns.UPDATED)\n\t\t\t.append(\" INTEGER,\").append(Columns.LISTTYPE)\n\t\t\t.append(\" TEXT DEFAULT NULL,\").append(Columns.SORTING)\n\t\t\t.append(\" TEXT DEFAULT NULL\").append(\")\").toString();\n\n\tpublic static final String CREATE_COUNT_VIEW = new StringBuilder(\n\t\t\t\"CREATE TEMP VIEW IF NOT EXISTS \")\n\t\t\t.append(VIEWCOUNT_NAME)\n\t\t\t.append(\" AS SELECT \")\n\t\t\t.append(arrayToCommaString(Columns.FIELDS))\n\t\t\t.append(\",\")\n\t\t\t.append(Columns.VIEW_COUNT)\n\t\t\t.append(\" FROM \")\n\t\t\t.append(TABLE_NAME)\n\t\t\t.append(\" LEFT JOIN \")\n\t\t\t// Select count statement\n\t\t\t.append(\" (SELECT COUNT(1) AS \").append(Columns.VIEW_COUNT)\n\t\t\t.append(\",\").append(Task.Columns.DBLIST).append(\" FROM \")\n\t\t\t.append(Task.TABLE_NAME).append(\" WHERE \")\n\t\t\t.append(Task.Columns.COMPLETED).append(\" IS NULL \")\n\t\t\t.append(\" GROUP BY \").append(Task.Columns.DBLIST).append(\") \")\n\t\t\t.append(\" ON \").append(TABLE_NAME).append(\".\").append(Columns._ID)\n\t\t\t.append(\" = \").append(Task.Columns.DBLIST).append(\";\").toString();\n\n\tpublic String title = \"\";\n\n\t// milliseconds since 1970-01-01 UTC\n\tpublic Long updated = null;\n\n\t// Null, use global prefs\n\tpublic String listtype = null;\n\tpublic String sorting = null;\n\n\t// Sync stuff\n\t// public String gtaskaccount = null;\n\t// public String gtaskid = null;\n\t// public String dropboxaccount = null;\n\t// public String dropboxid = null;\n\n\tpublic TaskList() {\n\t}\n\n\tpublic TaskList(final Cursor c) {\n\t\tthis._id = c.getLong(0);\n\t\tthis.title = c.getString(1);\n\t\tthis.updated = c.getLong(2);\n\t\tthis.listtype = c.getString(3);\n\t\tthis.sorting = c.getString(4);\n\t\t// sync stuff\n\t\t// gtaskaccount = c.getString(3);\n\t\t// gtaskid = c.getString(4);\n\t\t// dropboxaccount = c.getString(5);\n\t\t// dropboxid = c.getString(6);\n\t}\n\n\tpublic TaskList(final Uri uri, final ContentValues values) {\n\t\tthis(Long.parseLong(uri.getLastPathSegment()), values);\n\t}\n\n\tpublic TaskList(final long id, final ContentValues values) {\n\t\tthis(values);\n\t\tthis._id = id;\n\t}\n\n\tpublic TaskList(final JSONObject json) throws JSONException {\n\t\tif (json.has(Columns.TITLE))\n\t\t\ttitle = json.getString(Columns.TITLE);\n\t\tif (json.has(Columns.UPDATED))\n\t\t\tupdated = json.getLong(Columns.UPDATED);\n\t\tif (json.has(Columns.LISTTYPE))\n\t\t\tlisttype = json.getString(Columns.LISTTYPE);\n\t\tif (json.has(Columns.SORTING))\n\t\t\tsorting = json.getString(Columns.SORTING);\n\t}\n\n\tpublic TaskList(final ContentValues values) {\n\t\ttitle = values.getAsString(Columns.TITLE);\n\t\tupdated = values.getAsLong(Columns.UPDATED);\n\t\tlisttype = values.getAsString(Columns.LISTTYPE);\n\t\tsorting = values.getAsString(Columns.SORTING);\n\n\t\t// gtaskaccount = values.getAsString(Columns.GTASKACCOUNT);\n\t\t// gtaskid = values.getAsString(Columns.GTASKID);\n\t\t// dropboxaccount = values.getAsString(Columns.DROPBOXACCOUNT);\n\t\t// dropboxid = values.getAsString(Columns.DROPBOXID);\n\t}\n\n\tpublic ContentValues getContent() {\n\t\tfinal ContentValues values = new ContentValues();\n\t\t// Note that ID is NOT included here\n\t\tvalues.put(Columns.TITLE, title);\n\t\tvalues.put(Columns.UPDATED, updated);\n\t\tvalues.put(Columns.LISTTYPE, listtype);\n\t\tvalues.put(Columns.SORTING, sorting);\n\n\t\t// values.put(Columns.GTASKACCOUNT, gtaskaccount);\n\t\t// values.put(Columns.GTASKID, gtaskid);\n\t\t// values.put(Columns.DROPBOXACCOUNT, dropboxaccount);\n\t\t// values.put(Columns.DROPBOXID, dropboxid);\n\n\t\treturn values;\n\t}\n\n\t@Override\n\tprotected String getTableName() {\n\t\treturn TABLE_NAME;\n\t}\n\n\t@Override\n\tpublic String getContentType() {\n\t\treturn CONTENT_TYPE;\n\t}\n\n\t@Override\n\tpublic int save(final Context context) {\n\t\treturn save(context, Calendar.getInstance().getTimeInMillis());\n\t}\n\n\tpublic int save(final Context context, final long updateTime) {\n\t\tint result = 0;\n\t\tupdated = updateTime;\n\t\tif (_id < 1) {\n\t\t\tfinal Uri uri = context.getContentResolver().insert(getBaseUri(),\n\t\t\t\t\tgetContent());\n\t\t\tif (uri != null) {\n\t\t\t\t_id = Long.parseLong(uri.getLastPathSegment());\n\t\t\t\tresult++;\n\t\t\t}\n\t\t} else {\n\t\t\tresult += context.getContentResolver().update(getUri(),\n\t\t\t\t\tgetContent(), null, null);\n\t\t}\n\t\treturn result;\n\t}\n}", "public class TaskDetailFragment extends Fragment implements OnDateSetListener {\n\n // Id of task to open\n public static final String ARG_ITEM_ID = \"item_id\";\n // If no id is given, a string can be accepted as initial state\n public static final String ARG_ITEM_CONTENT = \"item_text\";\n // A list id is necessary\n public static final String ARG_ITEM_LIST_ID = \"item_list_id\";\n // Random identifier\n private static final String DATE_DIALOG_TAG = \"date_9374jf893jd893jt\";\n public static int LOADER_EDITOR_TASK = 3001;\n public static int LOADER_EDITOR_TASKLISTS = 3002;\n public static int LOADER_EDITOR_NOTIFICATIONS = 3003;\n\n StyledEditText taskText;\n CheckBox taskCompleted;\n Button dueDateBox;\n LinearLayout notificationList;\n View taskSection;\n NestedScrollView editScrollView;\n InputMethodManager inputManager;\n // To override intent values with\n // todo replace functionality of @InstanceState\n long stateId = -1;\n // todo replace functionality of @InstanceState\n long stateListId = -1;\n // Dao version of the object this fragment represents\n private Task mTask;\n // Version when task was opened\n private Task mTaskOrg;\n // To save orgState\n // TODO\n // AND with task.locked. If result is true, note is locked and has not been\n // unlocked, otherwise good to show\n private boolean mLocked = true;\n LoaderCallbacks<Cursor> loaderCallbacks = new LoaderCallbacks<Cursor>() {\n @Override\n public Loader<Cursor> onCreateLoader(final int id, final Bundle args) {\n if (LOADER_EDITOR_NOTIFICATIONS == id) {\n return new CursorLoader(getActivity(), Notification.URI, Notification.Columns\n .FIELDS, Notification.Columns.TASKID + \" IS ?\", new String[]{Long\n .toString(args.getLong(ARG_ITEM_ID, -1))}, Notification.Columns.TIME);\n } else if (LOADER_EDITOR_TASK == id) {\n return new CursorLoader(getActivity(), Task.getUri(args.getLong(ARG_ITEM_ID, -1))\n , Task.Columns.FIELDS, null, null, null);\n } else if (LOADER_EDITOR_TASKLISTS == id) {\n return new CursorLoader(getActivity(), TaskList.getUri(args.getLong\n (ARG_ITEM_LIST_ID)), TaskList.Columns.FIELDS, null, null, null);\n } else {\n return null;\n }\n }\n\n @Override\n public void onLoadFinished(Loader<Cursor> ldr, Cursor c) {\n if (LOADER_EDITOR_TASK == ldr.getId()) {\n if (c != null && c.moveToFirst()) {\n if (mTask == null) {\n mTask = new Task(c);\n if (mTaskOrg == null) {\n mTaskOrg = new Task(c);\n }\n fillUIFromTask();\n // Don't want updates while editing\n // getLoaderManager().destroyLoader(LOADER_EDITOR_TASK);\n } else {\n // Don't want updates while editing\n // getLoaderManager().destroyLoader(LOADER_EDITOR_TASK);\n // Only update the list if that changes\n Log.d(\"nononsenseapps listedit\", \"Updating list in task from \" + mTask\n .dblist);\n mTask.dblist = new Task(c).dblist;\n Log.d(\"nononsenseapps listedit\", \"Updating list in task to \" + mTask\n .dblist);\n if (mTaskOrg != null) {\n mTaskOrg.dblist = mTask.dblist;\n }\n }\n // Load the list to see if we should hide task bits\n Bundle args = new Bundle();\n args.putLong(ARG_ITEM_LIST_ID, mTask.dblist);\n getLoaderManager().restartLoader(LOADER_EDITOR_TASKLISTS, args, this);\n\n args.clear();\n args.putLong(ARG_ITEM_ID, getArguments().getLong(ARG_ITEM_ID, stateId));\n getLoaderManager().restartLoader(LOADER_EDITOR_NOTIFICATIONS, args,\n loaderCallbacks);\n } else {\n // Should kill myself maybe?\n }\n } else if (LOADER_EDITOR_NOTIFICATIONS == ldr.getId()) {\n while (c != null && c.moveToNext()) {\n addNotification(new Notification(c));\n }\n // Don't update while editing\n // TODO this allows updating of the location name etc\n getLoaderManager().destroyLoader(LOADER_EDITOR_NOTIFICATIONS);\n } else if (LOADER_EDITOR_TASKLISTS == ldr.getId()) {\n // At current only loading a single list\n if (c != null && c.moveToFirst()) {\n final TaskList list = new TaskList(c);\n hideTaskParts(list);\n }\n }\n }\n\n @Override\n public void onLoaderReset(Loader<Cursor> arg0) {\n }\n };\n private TaskEditorCallbacks mListener;\n private ActionProvider mShareActionProvider;\n /*\n * If in tablet and added, rotating to portrait actually recreats the\n * fragment even though it isn't visible. So if this is true, don't load\n * anything.\n */\n private boolean dontLoad = false;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public TaskDetailFragment() {\n // Make sure arguments are non-null\n setArguments(new Bundle());\n }\n\n void setListeners() {\n if (dontLoad) {\n return;\n }\n\n taskText.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n setShareIntent(s.toString());\n }\n });\n }\n\n void onDateClick() {\n final Calendar localTime = Calendar.getInstance();\n if (mTask != null && mTask.due != null) {\n //datePicker = DialogCalendar.getInstance(mTask.due);\n localTime.setTimeInMillis(mTask.due);\n }// else {\n //\tdatePicker = DialogCalendar.getInstance();\n //}\n\n //final DialogCalendar datePicker;\n //datePicker.setListener(this);\n //datePicker.show(getFragmentManager(), DATE_DIALOG_TAG);\n final DatePickerDialog datedialog = DatePickerDialog.newInstance(this, localTime.get\n (Calendar.YEAR), localTime.get(Calendar.MONTH), localTime.get(Calendar\n .DAY_OF_MONTH));\n datedialog.show(getFragmentManager(), DATE_DIALOG_TAG);\n }\n\n @Override\n public void onDateSet(DatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth) {\n final Calendar localTime = Calendar.getInstance();\n if (mTask.due != null) {\n localTime.setTimeInMillis(mTask.due);\n }\n localTime.set(Calendar.YEAR, year);\n localTime.set(Calendar.MONTH, monthOfYear);\n localTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);\n\n // set to 23:59 to be more or less consistent with earlier date only\n // implementation\n localTime.set(Calendar.HOUR_OF_DAY, 23);\n localTime.set(Calendar.MINUTE, 59);\n\n mTask.due = localTime.getTimeInMillis();\n setDueText();\n\n // Dont ask for time for due date\n // final TimePickerDialogFragment picker = getTimePickerFragment();\n // picker.setListener(this);\n // picker.show(getFragmentManager(), \"time\");\n }\n\n private void setDueText() {\n if (mTask.due == null) {\n dueDateBox.setText(\"\");\n } else {\n // Due date\n dueDateBox.setText(TimeFormatter.getLocalDateOnlyStringLong(getActivity(), mTask.due));\n }\n }\n\n void onDueRemoveClick() {\n if (!isLocked()) {\n if (mTask != null) {\n mTask.due = null;\n }\n setDueText();\n }\n }\n\n // @Override\n // public void onDialogTimeSet(int hourOfDay, int minute) {\n // final Calendar localTime = Calendar.getInstance();\n // if (mTask.due != null) {\n // localTime.setTimeInMillis(mTask.due);\n // }\n // localTime.set(Calendar.HOUR_OF_DAY, hourOfDay);\n // localTime.set(Calendar.MINUTE, minute);\n //\n // mTask.due = localTime.getTimeInMillis();\n // setDueText();\n // }\n //\n // @Override\n // public void onDialogTimeCancel() {\n // // TODO Auto-generated method stub\n //\n // }\n\n void onAddReminder() {\n if (mTask != null && !isLocked()) {\n // IF no id, have to save first\n if (mTask._id < 1) {\n saveTask();\n }\n // Only allow if save succeeded\n if (mTask._id < 1) {\n Toast.makeText(getActivity(), R.string.please_type_before_reminder, Toast\n .LENGTH_SHORT).show();\n return;\n }\n final Notification not = new Notification(mTask._id);\n not.save(getActivity(), true);\n\n // add item to UI\n addNotification(not);\n\n // And scroll to bottom. takes 300ms for item to appear.\n editScrollView.postDelayed(new Runnable() {\n @Override\n public void run() {\n editScrollView.fullScroll(ScrollView.FOCUS_DOWN);\n }\n }, 300);\n }\n }\n\n // @Override\n // public void onDateTimeSet(final long time) {\n // mTask.due = time;\n // setDueText();\n // }\n\n /**\n * task.locked & mLocked\n */\n public boolean isLocked() {\n return SharedPreferencesHelper.isPasswordSet(getActivity()) & mLocked;\n }\n\n void fillUIFromTask() {\n Log.d(\"nononsenseapps editor\", \"fillUI, act: \" + getActivity());\n if (isLocked()) {\n FragmentHelper.handle(new Runnable() {\n @Override\n public void run() {\n taskText.setText(mTask.title);\n DialogPassword pflock = new DialogPassword();\n pflock.setListener(new PasswordConfirmedListener() {\n @Override\n public void onPasswordConfirmed() {\n mLocked = false;\n fillUIFromTask();\n }\n });\n pflock.show(getFragmentManager(), \"read_verify\");\n }\n });\n } else {\n taskText.setText(mTask.getText());\n }\n setDueText();\n taskCompleted.setChecked(mTask.completed != null);\n taskCompleted.setOnCheckedChangeListener(new OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n if (isChecked)\n mTask.completed = Calendar.getInstance().getTimeInMillis();\n else\n mTask.completed = null;\n }\n });\n // Lock fields\n setFieldStatus();\n\n }\n\n /**\n * Set fields to enabled/disabled depending on lockstate\n */\n void setFieldStatus() {\n final boolean status = !isLocked();\n taskText.setEnabled(status);\n taskCompleted.setEnabled(status);\n dueDateBox.setEnabled(status);\n }\n\n void hideTaskParts(final TaskList list) {\n String type;\n if (list.listtype == null) {\n type = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString\n (getString(R.string.pref_listtype), getString(R.string.default_listtype));\n } else {\n type = list.listtype;\n }\n taskSection.setVisibility(type.equals(getString(R.string.const_listtype_notes)) ? View\n .GONE : View.VISIBLE);\n }\n\n // Call to update the share intent\n private void setShareIntent(final String text) {\n if (mShareActionProvider != null && taskText != null) {\n int titleEnd = text.indexOf(\"\\n\");\n if (titleEnd < 0) {\n titleEnd = text.length();\n }\n\n try {\n // Todo fix for support library version\n /*mShareActionProvider.setShareIntent(new Intent(Intent.ACTION_SEND).setType\n (\"text/plain\").putExtra(Intent.EXTRA_TEXT, text).putExtra(Intent\n .EXTRA_SUBJECT, text.substring(0, titleEnd)));*/\n } catch (RuntimeException e) {\n // Can crash when too many transactions overflow the buffer\n Log.d(\"nononsensenotes\", e.getLocalizedMessage());\n }\n }\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n if (dontLoad) {\n return;\n }\n try {\n mListener = (TaskEditorCallbacks) getActivity();\n } catch (ClassCastException e) {\n throw new ClassCastException(\"Activity must implement TaskEditorCallbacks\");\n }\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n inputManager = (InputMethodManager) getContext().getSystemService(Context\n .INPUT_METHOD_SERVICE);\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle\n savedInstanceState) {\n setHasOptionsMenu(true);\n View rootView = inflater.inflate(R.layout.fragment_task_detail, container, false);\n\n taskText = (StyledEditText) rootView.findViewById(R.id.taskText);\n taskCompleted = (CheckBox) rootView.findViewById(R.id.taskCompleted);\n dueDateBox = (Button) rootView.findViewById(R.id.dueDateBox);\n notificationList = (LinearLayout) rootView.findViewById(R.id.notificationList);\n taskSection = rootView.findViewById(R.id.taskSection);\n editScrollView = (NestedScrollView) rootView.findViewById(R.id.editScrollView);\n\n dueDateBox.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onDateClick();\n }\n });\n\n rootView.findViewById(R.id.dueCancelButton).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onDueRemoveClick();\n }\n });\n\n rootView.findViewById(R.id.notificationAdd).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onAddReminder();\n }\n });\n\n setListeners();\n\n return rootView;\n }\n\n @Override\n public void onActivityCreated(final Bundle state) {\n super.onActivityCreated(state);\n\n if (dontLoad) {\n return;\n }\n\n boolean openKb = false;\n\n final Bundle args = new Bundle();\n\n long idToOpen = mListener.getEditorTaskId();\n\n getArguments().putLong(ARG_ITEM_ID, idToOpen);\n if (idToOpen > 0) {\n // Load data from database\n args.putLong(ARG_ITEM_ID, idToOpen);\n getLoaderManager().restartLoader(LOADER_EDITOR_TASK, args, loaderCallbacks);\n } else {\n // If not valid, find a valid list\n long listId = mListener.getListOfTask();\n if (listId < 1) {\n listId = getARealList(getActivity(), -1);\n }\n // Fail if still not valid\n if (listId < 1) {\n // throw new InvalidParameterException(\n // \"Must specify a list id to create a note in!\");\n Toast.makeText(getActivity(), \"Must specify a list id to create a note in!\",\n Toast.LENGTH_SHORT).show();\n getActivity().finish();\n return;\n }\n getArguments().putLong(ARG_ITEM_LIST_ID, listId);\n args.putLong(ARG_ITEM_LIST_ID, listId);\n getLoaderManager().restartLoader(LOADER_EDITOR_TASKLISTS, args, loaderCallbacks);\n\n openKb = true;\n mTaskOrg = new Task();\n mTask = new Task();\n mTask.dblist = listId;\n // New note but start with the text given\n mTask.setText(mListener.getInitialTaskText());\n fillUIFromTask();\n }\n\n if (openKb) {\n /**\n * Only show keyboard for new/empty notes But not if the showcase\n * view is showing\n */\n taskText.requestFocus();\n inputManager.showSoftInput(taskText, InputMethodManager.SHOW_IMPLICIT);\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n if (dontLoad) {\n return;\n }\n\n // Hide data from snoopers\n if (mTask != null && isLocked()) {\n fillUIFromTask();\n }\n\n // See if there was a dialog and set listener again\n Fragment dateDialog = getFragmentManager().findFragmentByTag(DATE_DIALOG_TAG);\n if (dateDialog != null) {\n ((DatePickerDialog) dateDialog).setOnDateSetListener(this);\n }\n }\n\n @Override\n public void onSaveInstanceState(final Bundle state) {\n super.onSaveInstanceState(state);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n if (dontLoad) {\n return;\n }\n\n saveTask();\n // Set locked again\n mLocked = true;\n // If task is actually locked, remove text\n if (isLocked() && mTask != null && taskText != null) {\n taskText.setText(mTask.title);\n }\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n inflater.inflate(R.menu.fragment_tasks_detail, menu);\n\n // Locate MenuItem with ShareActionProvider\n MenuItem item = menu.findItem(R.id.menu_share);\n\n if (item != null) {\n // Fetch and store ShareActionProvider\n mShareActionProvider = MenuItemCompat.getActionProvider(item);\n setShareIntent(\"\");\n }\n }\n\n @Override\n public void onPrepareOptionsMenu(Menu menu) {\n menu.findItem(R.id.menu_share).setEnabled(!isLocked());\n\n if (getActivity() instanceof MenuStateController) {\n final boolean visible = ((MenuStateController) getActivity()).childItemsVisible();\n\n // Outside group to allow for action bar placement\n if (menu.findItem(R.id.menu_delete) != null)\n menu.findItem(R.id.menu_delete).setVisible(visible);\n if (menu.findItem(R.id.menu_revert) != null)\n menu.findItem(R.id.menu_revert).setVisible(visible);\n if (menu.findItem(R.id.menu_share) != null)\n menu.findItem(R.id.menu_share).setVisible(visible);\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n int itemId = item.getItemId();\n /*if (itemId == R.id.menu_add) {\n // TODO should not call if in tablet mode\n\t\t\tif (mListener != null && mTask != null && mTask.dblist > 0) {\n\t\t\t\tmListener.addTaskInList(\"\", mTask.dblist);\n\t\t\t}\n\t\t\treturn true;\n\t\t} else */\n if (itemId == R.id.menu_revert) {\n // set to null to prevent modifications\n mTask = null;\n // Request a close from activity\n if (mListener != null) {\n mListener.closeEditor(this);\n }\n return true;\n } else if (itemId == R.id.menu_delete) {\n if (mTask != null) {\n if (isLocked()) {\n DialogPassword delpf = new DialogPassword();\n delpf.setListener(new PasswordConfirmedListener() {\n @Override\n public void onPasswordConfirmed() {\n deleteAndClose();\n }\n });\n delpf.show(getFragmentManager(), \"delete_verify\");\n } else {\n deleteAndClose();\n }\n }\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n private void deleteAndClose() {\n if (mTask != null && mTask._id > 0 && !isLocked()) {\n DialogDeleteTask.showDialog(getFragmentManager(), mTask._id, new\n DialogConfirmedListener() {\n @Override\n public void onConfirm() {\n // Prevents save attempts\n mTask = null;\n // Request a close from activity\n // Todo let listener handle delete, and use Snack bar.\n if (mListener != null) {\n mListener.closeEditor(TaskDetailFragment.this);\n }\n }\n });\n } else {\n // Prevents save attempts\n mTask = null;\n // Request a close from activity\n if (mListener != null) {\n mListener.closeEditor(TaskDetailFragment.this);\n }\n }\n }\n\n private void saveTask() {\n // if mTask is null, the task has been deleted or cancelled\n // If the task is not unlocked, editing is disabled\n if (mTask != null && !isLocked()) {\n // Needed for comparison\n mTask.setText(taskText.getText().toString());\n // if new item, only save if something has been entered\n if ((mTask._id > 0 && !mTask.equals(mTaskOrg)) || (mTask._id == -1 && isThereContent\n ())) {\n // mTask.setText(taskText.getText().toString());\n mTask.save(getActivity());\n // Set the intent to open the task.\n // So we dont create a new one on rotation for example\n fixIntent();\n\n // TODO, should restart notification loader for new tasks\n }\n }\n }\n\n void fixIntent() {\n stateId = mTask._id;\n stateListId = mTask.dblist;\n\n if (getActivity() == null)\n return;\n\n final Intent orgIntent = getActivity().getIntent();\n if (orgIntent == null || orgIntent.getAction() == null || !orgIntent.getAction().equals\n (Intent.ACTION_INSERT))\n return;\n\n if (mTask == null || mTask._id < 1)\n return;\n\n final Intent intent = new Intent().setAction(Intent.ACTION_EDIT).setClass(getActivity(),\n ActivityEditor.class).setData(mTask.getUri()).putExtra(TaskDetailFragment\n .ARG_ITEM_LIST_ID, mTask.dblist);\n\n getActivity().setIntent(intent);\n }\n\n boolean isThereContent() {\n boolean result = false;\n result |= taskText.getText().length() > 0;\n result |= dueDateBox.getText().length() > 0;\n\n return result;\n }\n\n /**\n * Inserts a notification item in the UI\n *\n * @param not\n */\n void addNotification(final Notification not) {\n if (getActivity() != null) {\n View nv = LayoutInflater.from(getActivity()).inflate(R.layout.notification_view, null);\n\n // So we can update the view later\n not.view = nv;\n\n // Setup all the listeners etc\n NotificationItemHelper.setup(this, notificationList, nv, not, mTask);\n\n notificationList.addView(nv);\n }\n }\n\n /**\n * Returns an appropriately themed time picker fragment\n */\n // public TimePickerDialogFragment getTimePickerFragment() {\n // final String theme = PreferenceManager.getDefaultSharedPreferences(\n // getActivity()).getString(MainPrefs.KEY_THEME,\n // getString(R.string.const_theme_light_ab));\n // if (theme.contains(\"light\")) {\n // return TimePickerDialogFragment\n // .newInstance(R.style.BetterPickersDialogFragment_Light);\n // }\n // else {\n // // dark\n // return TimePickerDialogFragment\n // .newInstance(R.style.BetterPickersDialogFragment);\n // }\n // }\n\n /**\n * Returns an appropriately themed time picker fragment. Up to caller to set\n * callback and desired starting time.\n */\n public TimePickerDialog getTimePickerDialog() {\n final String theme = PreferenceManager.getDefaultSharedPreferences(getActivity())\n .getString(MainPrefs.KEY_THEME, getString(R.string.const_theme_light_ab));\n\n final TimePickerDialog timePickerDialog = TimePickerDialog.newInstance(null, 0, 0,\n android.text.format.DateFormat.is24HourFormat(getActivity()));\n timePickerDialog.setThemeDark(!theme.contains(\"light\"));\n return timePickerDialog;\n }\n\n public interface TaskEditorCallbacks {\n /**\n * @return the id of the task to open. Negative number indicates a new task. In which\n * case, the fragment will call getListOfTask.\n */\n long getEditorTaskId();\n\n /**\n * @return The list where this task (should) live(s). Used for creating new tasks.\n */\n long getListOfTask();\n\n void closeEditor(Fragment fragment);\n\n /**\n * @return The text a new task should contain, or the empty string.\n */\n @NonNull\n String getInitialTaskText();\n }\n}", "public class TaskListFragment extends Fragment\n implements OnSharedPreferenceChangeListener, SyncStatusMonitor.OnSyncStartStopListener,\n ActionMode.Callback {\n\n // Must be less than -1\n public static final String LIST_ALL_ID_PREF_KEY = \"show_all_tasks_choice_id\";\n public static final int LIST_ID_ALL = -2;\n public static final int LIST_ID_OVERDUE = -3;\n public static final int LIST_ID_TODAY = -4;\n public static final int LIST_ID_WEEK = -5;\n\n public static final String LIST_ID = \"list_id\";\n public static final int LOADER_TASKS = 1;\n public static final int LOADER_CURRENT_LIST = 0;\n private static final String TAG = \"TaskListFragment\";\n\n RecyclerView listView;\n\n SimpleSectionsAdapter mAdapter;\n\n SyncStatusMonitor syncStatusReceiver = null;\n\n private long mListId = -1;\n\n private TaskListFragment.TaskListCallbacks mListener;\n\n private String mSortType = null;\n private int mRowCount = 3;\n\n private LoaderCallbacks<Cursor> mCallback = null;\n\n private ActionMode mMode;\n private SwipeRefreshLayout mSwipeRefreshLayout;\n private ItemTouchHelper touchHelper;\n private SelectedItemHandler selectedItemHandler;\n\n public TaskListFragment() {\n super();\n }\n\n public static TaskListFragment getInstance(final long listId) {\n TaskListFragment f = new TaskListFragment();\n Bundle args = new Bundle();\n args.putLong(LIST_ID, listId);\n f.setArguments(args);\n return f;\n }\n\n public static String whereOverDue() {\n return Task.Columns.DUE + \" BETWEEN \" + Task.OVERDUE + \" AND \" + Task.TODAY_START;\n }\n\n public static String andWhereOverdue() {\n return \" AND \" + whereOverDue();\n }\n\n public static String whereToday() {\n return Task.Columns.DUE + \" BETWEEN \" + Task.TODAY_START + \" AND \" + Task.TODAY_PLUS(1);\n }\n\n public static String andWhereToday() {\n return \" AND \" + whereToday();\n }\n\n public static String whereWeek() {\n return Task.Columns.DUE + \" BETWEEN \" + Task.TODAY_START + \" AND (\" + Task.TODAY_PLUS(5) +\n \" -1)\";\n }\n\n public static String andWhereWeek() {\n return \" AND \" + whereWeek();\n }\n\n void loadList() {\n listView.setLayoutManager(new LinearLayoutManager(getActivity()));\n listView.setHasFixedSize(true);\n // TODO separators\n touchHelper = new ItemTouchHelper(new DragHandler());\n listView.setAdapter(mAdapter);\n touchHelper.attachToRecyclerView(listView);\n\n // TODO jonas\n /*listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {\n final HashMap<Long, Task> tasks = new HashMap<Long, Task>();\n // ActionMode mMode;\n\n @Override\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\n // Must setup the contextual action menu\n final MenuInflater inflater = getActivity().getMenuInflater();\n inflater.inflate(R.menu.fragment_tasklist_context, menu);\n\n // Must clear for reuse\n tasks.clear();\n\n // For password\n mMode = mode;\n\n return true;\n }\n\n @Override\n public boolean onPrepareActionMode(ActionMode mode, Menu menu) {\n // Here you can perform updates to the CAB due to\n // an invalidate() request\n return false;\n }\n\n @Override\n public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {\n // Respond to clicks on the actions in the CAB\n boolean finish = false;\n int itemId = item.getItemId();\n if (itemId == R.id.menu_delete) {\n deleteTasks(tasks);\n finish = true;\n\n } else if (itemId == R.id.menu_switch_list) {\n // show move to list dialog\n DialogMoveToList.getInstance(tasks.keySet().toArray(new Long[tasks.size()]))\n .show(getFragmentManager(), \"move_to_list_dialog\");\n finish = true;\n } else if (itemId == R.id.menu_share) {\n startActivity(getShareIntent());\n finish = true;\n } else {\n finish = false;\n }\n\n if (finish) {\n mode.finish(); // Action picked, so close the CAB\n }\n return finish;\n }\n\n @Override\n public void onDestroyActionMode(ActionMode mode) {\n // Here you can make any necessary updates to the activity when\n // the CAB is removed. By default, selected items are\n // deselected/unchecked.\n tasks.clear();\n }\n\n @Override\n public void onItemCheckedStateChanged(ActionMode mode, int position, long id,\n boolean checked) {\n if (checked) {\n tasks.put(id, new Task(mAdapter.getCursor(position)));\n } else {\n tasks.remove(id);\n }\n // Display in action bar total number of selected items\n mode.setTitle(Integer.toString(tasks.size()));\n }\n\n String getShareText() {\n final StringBuilder sb = new StringBuilder();\n final boolean locked = SharedPreferencesHelper.isPasswordSet(getActivity());\n for (Task t : tasks.values()) {\n if (sb.length() > 0) {\n sb.append(\"\\n\\n\");\n }\n if (locked) {\n sb.append(t.title);\n } else {\n sb.append(t.getText());\n }\n }\n return sb.toString();\n }\n\n String getShareSubject() {\n String result = \"\";\n for (Task t : tasks.values()) {\n result += \", \" + t.title;\n }\n return result.length() > 0 ? result.substring(2) : result;\n }\n\n Intent getShareIntent() {\n final Intent shareIntent = new Intent(Intent.ACTION_SEND);\n shareIntent.setType(\"text/plain\");\n shareIntent.putExtra(Intent.EXTRA_TEXT, getShareText());\n shareIntent.putExtra(Intent.EXTRA_SUBJECT, getShareSubject());\n shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);\n return shareIntent;\n }\n });*/\n }\n\n /**\n * Delete tasks and display a snackbar with an undo action\n *\n */\n private void deleteTasks(final Set<Long> orgItemIds) {\n // If any are locked, ask for password first\n final boolean locked = SharedPreferencesHelper.isPasswordSet(getActivity());\n\n // copy to avoid threading issues\n final Set<Long> itemIds = new TreeSet<>();\n itemIds.addAll(orgItemIds);\n\n final PasswordConfirmedListener pListener = new PasswordConfirmedListener() {\n @Override\n public void onPasswordConfirmed() {\n AsyncTaskHelper.background(new AsyncTaskHelper.Job() {\n @Override\n public void doInBackground() {\n for (Long id: itemIds) {\n try {\n Task.delete(id, getActivity());\n } catch (Exception ignored) {\n Log.e(TAG, \"doInBackground:\" + ignored.getMessage());\n }\n }\n }\n });\n }\n };\n\n if (locked) {\n DialogPassword delpf = new DialogPassword();\n delpf.setListener(pListener);\n delpf.show(getFragmentManager(), \"multi_delete_verify\");\n } else {\n // Just run it directly\n Log.d(TAG, \"deleteTasks: run it\");\n pListener.onPasswordConfirmed();\n }\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n try {\n mListener = (TaskListFragment.TaskListCallbacks) getActivity();\n } catch (ClassCastException e) {\n throw new ClassCastException(\"Activity must implement \" + \"OnFragmentInteractionListener\");\n }\n\n // We want to be notified of future changes to auto refresh\n PreferenceManager.getDefaultSharedPreferences(context)\n .registerOnSharedPreferenceChangeListener(this);\n }\n\n void setupSwipeToRefresh() {\n // Set the offset so it comes out of the correct place\n final int toolbarHeight = getResources().getDimensionPixelOffset(R.dimen.toolbar_height);\n mSwipeRefreshLayout\n .setProgressViewOffset(false, -toolbarHeight, Math.round(0.7f * toolbarHeight));\n\n // The arrow will cycle between these colors (in order)\n mSwipeRefreshLayout\n .setColorSchemeResources(R.color.refresh_progress_1, R.color.refresh_progress_2,\n R.color.refresh_progress_3);\n\n mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n @Override\n public void onRefresh() {\n boolean syncing = SyncHelper.onManualSyncRequest(getActivity());\n\n if (!syncing) {\n // Do not show refresh view\n mSwipeRefreshLayout.setRefreshing(false);\n }\n }\n });\n }\n\n @Override\n public void onCreate(Bundle savedState) {\n super.onCreate(savedState);\n\n setHasOptionsMenu(true);\n\n selectedItemHandler = new SelectedItemHandler((AppCompatActivity) getActivity(), this);\n\n syncStatusReceiver = new SyncStatusMonitor();\n\n if (getArguments().getLong(LIST_ID, -1) == -1) {\n throw new InvalidParameterException(\"Must designate a list to open!\");\n }\n mListId = getArguments().getLong(LIST_ID, -1);\n\n // Start loading data\n mAdapter = new SimpleSectionsAdapter(this, getActivity());\n\n // Set a drag listener\n // TODO jonas\n /*mAdapter.setDropListener(new DropListener() {\n @Override\n public void drop(int from, int to) {\n Log.d(\"nononsenseapps drag\", \"Position from \" + from + \" to \" + to);\n\n final Task fromTask = new Task((Cursor) mAdapter.getItem(from));\n final Task toTask = new Task((Cursor) mAdapter.getItem(to));\n\n fromTask.moveTo(getActivity().getContentResolver(), toTask);\n }\n });*/\n }\n\n /**\n * Called to have the fragment instantiate its user interface view. This is optional, and\n * non-graphical fragments can return null (which is the default implementation). This will be\n * called between {@link #onCreate(Bundle)} and {@link #onActivityCreated(Bundle)}. <p/> <p>If you\n * return a View from here, you will later be called in {@link #onDestroyView} when the view is\n * being released.\n *\n * @param inflater The LayoutInflater object that can be used to inflate any views in the fragment,\n * @param container If non-null, this is the parent view that the fragment's UI should be attached to. The\n * fragment should not add the view itself, but this can be used to generate the LayoutParams\n * of the view.\n * @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given\n * here.\n * @return Return the View for the fragment's UI, or null.\n */\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n //return super.onCreateView(inflater, container, savedInstanceState);\n View rootView = inflater.inflate(R.layout.fragment_task_list, container, false);\n\n listView = (RecyclerView) rootView.findViewById(android.R.id.list);\n loadList();\n // ListView will only support scrolling ToolBar off-screen from Lollipop onwards.\n // RecyclerView does not have this limitation\n ViewCompat.setNestedScrollingEnabled(listView, true);\n\n // setup swipe to refresh\n mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);\n setupSwipeToRefresh();\n\n return rootView;\n }\n\n @Override\n public void onActivityCreated(final Bundle state) {\n super.onActivityCreated(state);\n\n // Get the global list settings\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());\n\n mCallback = new LoaderCallbacks<Cursor>() {\n @Override\n public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {\n if (id == LOADER_CURRENT_LIST) {\n return new CursorLoader(getActivity(), TaskList.getUri(mListId), TaskList.Columns.FIELDS,\n null, null, null);\n } else {\n // What sorting to use\n Uri targetUri;\n String sortSpec;\n\n if (mSortType == null) {\n mSortType = prefs\n .getString(getString(R.string.pref_sorttype), getString(R.string.default_sorttype));\n }\n\n // All-view can't use manual sorting\n if (mListId < 1 && mSortType.equals(getString(R.string.const_possubsort))) {\n mSortType = getString(R.string.const_all_default_sorting);\n }\n\n if (mSortType.equals(getString(R.string.const_alphabetic))) {\n targetUri = Task.URI;\n sortSpec = getString(R.string.const_as_alphabetic, Task.Columns.TITLE);\n } else if (mSortType.equals(getString(R.string.const_duedate))) {\n targetUri = Task.URI_SECTIONED_BY_DATE;\n sortSpec = null;\n } else if (mSortType.equals(getString(R.string.const_modified))) {\n targetUri = Task.URI;\n sortSpec = Task.Columns.UPDATED + \" DESC\";\n }\n // manual sorting\n else {\n targetUri = Task.URI;\n sortSpec = Task.Columns.LEFT;\n }\n\n String where = null;\n String[] whereArgs = null;\n\n if (mListId > 0) {\n where = Task.Columns.DBLIST + \" IS ?\";\n whereArgs = new String[]{Long.toString(mListId)};\n }\n\n return new CursorLoader(getActivity(), targetUri, Task.Columns.FIELDS, where, whereArgs,\n sortSpec);\n }\n }\n\n @Override\n public void onLoadFinished(Loader<Cursor> loader, Cursor c) {\n if (loader.getId() == LOADER_TASKS) {\n mAdapter.swapCursor(c);\n }\n }\n\n @Override\n public void onLoaderReset(Loader<Cursor> loader) {\n if (loader.getId() == LOADER_TASKS) {\n mAdapter.swapCursor(null);\n }\n }\n };\n\n getLoaderManager().restartLoader(LOADER_TASKS, null, mCallback);\n }\n\n /**\n * Called when the fragment is visible to the user and actively running. This is generally tied to\n * {@link Activity#onResume() Activity.onResume} of the containing Activity's lifecycle.\n */\n @Override\n public void onResume() {\n super.onResume();\n // activate monitor\n if (syncStatusReceiver != null) {\n syncStatusReceiver.startMonitoring(getActivity(), this);\n }\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n }\n\n /**\n * Called when the Fragment is no longer resumed. This is generally tied to {@link\n * Activity#onPause() Activity.onPause} of the containing Activity's lifecycle.\n */\n @Override\n public void onPause() {\n //mSwipeRefreshLayout.setRefreshing(false);// deactivate monitor\n if (syncStatusReceiver != null) {\n syncStatusReceiver.stopMonitoring();\n }\n\n super.onPause();\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n getLoaderManager().destroyLoader(0);\n }\n\n @Override\n public void onDetach() {\n mListener = null;\n PreferenceManager.getDefaultSharedPreferences(getActivity())\n .unregisterOnSharedPreferenceChangeListener(this);\n super.onDetach();\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n inflater.inflate(R.menu.fragment_tasklist, menu);\n }\n\n @Override\n public void onPrepareOptionsMenu(Menu menu) {\n if (getActivity() instanceof MenuStateController) {\n final boolean visible = ((MenuStateController) getActivity()).childItemsVisible();\n\n menu.setGroupVisible(R.id.list_menu_group, visible);\n if (!visible) {\n if (mMode != null) {\n mMode.finish();\n }\n }\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.menu_clearcompleted:\n if (mListId != -1) {\n DialogDeleteCompletedTasks.showDialog(getFragmentManager(), mListId, null);\n }\n return true;\n default:\n return false;\n }\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key) {\n if (isDetached()) {\n // Fix crash report\n return;\n }\n try {\n boolean reload = false;\n if (key.equals(getString(R.string.pref_sorttype))) {\n mSortType = null;\n reload = true;\n }\n\n if (reload && mCallback != null) {\n getLoaderManager().restartLoader(LOADER_TASKS, null, mCallback);\n }\n } catch (IllegalStateException ignored) {\n // Fix crash report\n // Might get a race condition where fragment is detached when getString is called\n }\n }\n\n /**\n * @param ongoing\n */\n @Override\n public void onSyncStartStop(boolean ongoing) {\n mSwipeRefreshLayout.setRefreshing(ongoing);\n }\n\n public ItemTouchHelper getTouchHelper() {\n return touchHelper;\n }\n\n public int getRowCount() {\n return mRowCount;\n }\n\n public String getSortType() {\n return mSortType;\n }\n\n public TaskListCallbacks getListener() {\n return mListener;\n }\n\n public SelectedItemHandler getSelectedItemHandler() {\n return selectedItemHandler;\n }\n\n public long getListId() {\n return mListId;\n }\n\n @Override\n public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {\n actionMode.getMenuInflater().inflate(R.menu.fragment_tasklist_context, menu);\n return true;\n }\n\n @Override\n public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {\n return false;\n }\n\n @Override\n public boolean onActionItemClicked(ActionMode actionMode, MenuItem item) {\n // Respond to clicks on the actions in the CAB\n final boolean finish;\n int itemId = item.getItemId();\n if (itemId == R.id.menu_delete) {\n deleteTasks(selectedItemHandler.getSelected());\n finish = true;\n }\n else if (itemId == R.id.menu_switch_list) {\n // show move to list dialog\n DialogMoveToList.getInstance(selectedItemHandler.getSelected())\n .show(getFragmentManager(), \"move_to_list_dialog\");\n finish = true;\n } else if (itemId == R.id.menu_share) {\n shareSelected(selectedItemHandler.getSelected());\n finish = true;\n } else {\n finish = false;\n }\n\n if (finish) {\n actionMode.finish(); // Action picked, so close the CAB\n }\n return finish;\n }\n\n private void shareSelected(Collection<Long> orgItemIds) {\n // This solves threading issues\n final long[] itemIds = ArrayHelper.toArray(orgItemIds);\n\n AsyncTaskHelper.background(new AsyncTaskHelper.Job() {\n @Override\n public void doInBackground() {\n final StringBuilder shareSubject = new StringBuilder();\n final StringBuilder shareText = new StringBuilder();\n\n final String whereId = new StringBuilder(Task.Columns._ID)\n .append(\" IN (\").append(DAO.arrayToCommaString(itemIds))\n .append(\")\").toString();\n\n Cursor c = getContext().getContentResolver().query(Task.URI,\n new String[] {Task.Columns._ID, Task.Columns.TITLE, Task.Columns.NOTE},\n whereId, null, null);\n\n if (c != null) {\n while (c.moveToNext()) {\n if (shareText.length() > 0) {\n shareText.append(\"\\n\\n\");\n }\n if (shareSubject.length() > 0) {\n shareSubject.append(\", \");\n }\n\n shareSubject.append(c.getString(1));\n shareText.append(c.getString(1));\n\n if (!c.getString(2).isEmpty()) {\n shareText.append(\"\\n\").append(c.getString(2));\n }\n }\n\n c.close();\n }\n\n final Intent shareIntent = new Intent(Intent.ACTION_SEND);\n shareIntent.setType(\"text/plain\");\n shareIntent.putExtra(Intent.EXTRA_TEXT, shareText.toString());\n shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject.toString());\n startActivity(shareIntent);\n }\n });\n }\n\n @Override\n public void onDestroyActionMode(ActionMode actionMode) {\n //jonas\n selectedItemHandler.clear();\n mAdapter.notifyDataSetChanged();\n }\n\n /**\n * This interface must be implemented by activities that contain TaskListFragments to allow an\n * interaction in this fragment to be communicated to the activity and potentially other fragments\n * contained in that activity.\n */\n public interface TaskListCallbacks {\n void openTask(final Uri uri, final long listId, final View origin);\n }\n\n class DragHandler extends ItemTouchHelper.Callback {\n\n private static final String TAG = \"DragHandler\";\n\n public DragHandler() {\n super();\n }\n\n @Override\n public boolean isLongPressDragEnabled() {\n return false;\n }\n\n @Override\n public boolean isItemViewSwipeEnabled() {\n return false;\n }\n\n @Override\n public int getMovementFlags(final RecyclerView recyclerView,\n final RecyclerView.ViewHolder viewHolder) {\n int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;\n int swipeFlags = 0;\n return makeMovementFlags(dragFlags, swipeFlags);\n }\n\n @Override\n public boolean onMove(final RecyclerView recyclerView, final RecyclerView.ViewHolder viewHolder,\n final RecyclerView.ViewHolder target) {\n final Task fromTask = new Task(mAdapter.getCursor(viewHolder.getAdapterPosition()));\n final Task toTask = new Task(mAdapter.getCursor(target.getAdapterPosition()));\n\n mAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());\n fromTask.moveTo(getActivity().getContentResolver(), toTask);\n return true;\n }\n\n @Override\n public void onSwiped(final RecyclerView.ViewHolder viewHolder, final int direction) {\n\n }\n }\n}" ]
import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.preference.PreferenceManager; import com.nononsenseapps.notepad.R; import com.nononsenseapps.notepad.data.local.sql.LegacyDBHelper; import com.nononsenseapps.notepad.data.model.sql.Task; import com.nononsenseapps.notepad.data.model.sql.TaskList; import com.nononsenseapps.notepad.ui.editor.TaskDetailFragment; import com.nononsenseapps.notepad.ui.list.TaskListFragment;
/* * Copyright (c) 2015 Jonas Kalderstam. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nononsenseapps.notepad.util; /** * Simple utility class to hold some general functions. */ public class ListHelper { /** * If temp list is > 0, returns it if it exists. Else, checks if a default list is set * then returns that. If none set, then returns first (alphabetical) list * Returns #{TaskListFragment.LIST_ID_ALL} if no lists in database. */ public static long getAViewList(final Context context, final long tempList) { long returnList = tempList;
if (returnList == TaskListFragment.LIST_ID_ALL) {
4
chetan/sewer
src/main/java/net/pixelcop/sewer/sink/durable/TransactionManager.java
[ "@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\npublic class PlumbingBuilder<T> {\n\n private Class clazz;\n private String[] args;\n\n public PlumbingBuilder(Class clazz, String[] args) {\n this.clazz = clazz;\n this.args = args;\n }\n\n public Object build() throws Exception {\n return (T) clazz.getConstructor(String[].class).newInstance((Object) args);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(clazz.getSimpleName());\n sb.append(\"(\");\n if (args != null) {\n for (int i = 0; i < args.length; i++) {\n if (i > 0) {\n sb.append(\", \");\n }\n sb.append(args[i]);\n }\n }\n sb.append(\")\");\n return sb.toString();\n }\n\n public Class getClazz() {\n return clazz;\n }\n\n public String[] getArgs() {\n return args;\n }\n}", "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic class PlumbingFactory<T> {\n\n private static final Pattern configPattern = Pattern.compile(\"^(.*?)(\\\\((.*?)\\\\))?$\");\n\n private String config;\n private List<PlumbingBuilder<T>> classes;\n\n private PlumbingFactory() {\n }\n\n public PlumbingFactory(List<PlumbingBuilder<T>> classes) {\n this.classes = classes;\n }\n\n public PlumbingFactory(String config, Map<String, Class> registry) throws ConfigurationException {\n this.config = config;\n this.classes = new ArrayList<PlumbingBuilder<T>>();\n parseConfig(registry);\n }\n\n private void parseConfig(Map<String, Class> registry) throws ConfigurationException {\n\n String[] pieces = config.split(\"\\\\s*>\\\\s*\");\n for (int i = 0; i < pieces.length; i++) {\n\n String piece = pieces[i];\n\n Matcher matcher = configPattern.matcher(piece);\n if (!matcher.find()) {\n throw new ConfigurationException(\"Invalid config pattern: \" + piece);\n }\n\n String clazzId = matcher.group(1).toLowerCase();\n if (!registry.containsKey(clazzId)) {\n throw new ConfigurationException(\"Invalid source/sink: \" + clazzId);\n }\n\n String[] args = null;\n if (matcher.group(3) != null && !matcher.group(3).isEmpty()) {\n args = matcher.group(3).split(\"\\\\s*,\\\\s*\");\n if (args != null && args.length > 0) {\n for (int j = 0; j < args.length; j++) {\n args[j] = args[j].trim();\n if (args.length > 0 && (args[j].charAt(0) == '\\'' || args[j].charAt(0) == '\"')) {\n args[j] = args[j].substring(1, args[j].length() - 1);\n }\n }\n }\n }\n\n classes.add(new PlumbingBuilder<T>(registry.get(clazzId), args));\n }\n\n }\n\n public T build() {\n\n try {\n\n if (classes.size() == 1) {\n // Sources will not be chained\n return (T) classes.get(0).build();\n }\n\n // Create first Sink in chain\n Sink sink = (Sink) classes.get(0).build();\n\n // Create a new factory minus the sink that was just created\n PlumbingFactory<Sink> factory = new PlumbingFactory<Sink>();\n List list = new ArrayList(this.classes.size());\n list.addAll(this.classes);\n list.remove(0);\n factory.classes = list;\n\n sink.setSinkFactory(factory);\n\n return (T) sink;\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null; // TODO throw exception?\n }\n\n public List<PlumbingBuilder<T>> getClasses() {\n return classes;\n }\n\n}", "public abstract class Sink extends Plumbing {\n\n private static final Logger LOG = LoggerFactory.getLogger(Sink.class);\n\n protected Sink subSink = null;\n\n /**\n * Append an Event to the Sink\n * @param event\n * @throws IOException\n */\n public abstract void append(Event event) throws IOException;\n\n public void setSubSink(Sink subSink) {\n this.subSink = subSink;\n }\n\n public Sink getSubSink() {\n return subSink;\n }\n\n /**\n * Create the SubSink, if possible\n *\n * @return True if a SubSink was created, false otherwise.\n */\n public boolean createSubSink() {\n if (getSinkFactory() == null) {\n return false;\n }\n\n subSink = getSinkFactory().build();\n return true;\n }\n\n @Override\n protected void finalize() throws Throwable {\n if (getStatus() != CLOSED) {\n try {\n close();\n } catch (Throwable t) {\n LOG.warn(\"Caught during finalizer close(): \" + t.getMessage(), t);\n // rethrow? this should be good enough since the object was disposed of anyway\n }\n }\n }\n\n}", "public interface ExitCodes {\n\n public static final int HELP = 1;\n public static final int CONFIG_ERROR = 2;\n public static final int IO_ERROR = 3;\n public static final int OTHER_ERROR = -1;\n public static final int STARTUP_ERROR = 10;\n\n}", "public class Node extends Thread {\n\n static class ShutdownHook extends Thread {\n @Override\n public void run() {\n LOG.warn(\"Caught shutdown signal. Going to try to stop cleanly..\");\n Node.getInstance().shutdown();\n TransactionManager.getInstance().shutdown(false);\n LOG.debug(\"Shutdown complete. Goodbye!\");\n }\n }\n\n private static final Logger LOG = LoggerFactory.getLogger(Node.class);\n\n protected static Node instance;\n\n private final NodeConfig conf;\n\n private MetricRegistry metricRegistry;\n private List<ScheduledReporter> metricReporters;\n\n private Source source;\n\n private PlumbingFactory<Source> sourceFactory;\n private PlumbingFactory<Sink> sinkFactory;\n\n public static Node getInstance() {\n return instance;\n }\n\n /**\n * This main() method is not called directly, rather it is called via {@link NodeDaemon}.\n *\n * @param args\n */\n public static void main(String[] args) {\n\n NodeConfig conf = new NodeConfigurator().configure(args);\n\n try {\n instance = new Node(conf);\n } catch (IOException e) {\n System.err.println(\"Error while starting node: \" + e.getMessage());\n e.printStackTrace();\n LOG.error(\"Error while starting node: \" + e.getMessage(), e);\n System.exit(ExitCodes.IO_ERROR);\n }\n\n }\n\n public Node(NodeConfig config) throws IOException {\n\n instance = this;\n\n setName(\"Node \" + getId());\n this.conf = config;\n configure();\n\n TransactionManager.init(conf);\n }\n\n /**\n * Load node configuration and start source/sink. In the future this could be from a Master\n * server, but for now we simply use a properties file.\n *\n * @throws IOException\n */\n protected void configure() throws IOException {\n\n validateConfig();\n\n loadPlugins();\n\n try {\n this.sourceFactory = new PlumbingFactory<Source>(conf.get(NodeConfig.SOURCE), SourceRegistry.getRegistry());\n this.sinkFactory = new PlumbingFactory<Sink>(conf.get(NodeConfig.SINK), SinkRegistry.getRegistry());\n\n } catch (ConfigurationException ex) {\n LOG.error(\"Node configuration failed: \" + ex.getMessage(), ex);\n System.exit(ExitCodes.CONFIG_ERROR);\n }\n\n this.source = sourceFactory.build();\n this.source.setSinkFactory(sinkFactory);\n\n this.source.init();\n\n }\n\n /**\n * Load plugin classes specified in config\n */\n @SuppressWarnings({ \"rawtypes\" })\n protected void loadPlugins() {\n String[] plugins = conf.getStrings(NodeConfig.PLUGINS);\n if (plugins == null || plugins.length == 0) {\n return;\n }\n for (int i = 0; i < plugins.length; i++) {\n try {\n Class clazz = Class.forName(plugins[i]);\n Constructor con = null;\n Object obj = null;\n try {\n con = clazz.getConstructor(null);\n obj = con.newInstance();\n } catch (NoSuchMethodException e) {\n con = clazz.getConstructor(new String[]{}.getClass());\n obj = con.newInstance(new Object[] { new String[]{} });\n }\n ((PlumbingProvider) obj).register();\n\n } catch (Throwable t) {\n LOG.error(\"Failed to load plugin class: \" + plugins[i], t);\n System.exit(ExitCodes.CONFIG_ERROR);\n }\n }\n }\n\n protected void validateConfig() {\n\n boolean err = false;\n if (conf.get(NodeConfig.SOURCE) == null) {\n err = true;\n LOG.error(\"Property \" + NodeConfig.SOURCE + \" cannot be null\");\n }\n if (conf.get(NodeConfig.SINK) == null) {\n err = true;\n LOG.error(\"Property \" + NodeConfig.SINK + \" cannot be null\");\n }\n\n if (err == true) {\n System.exit(ExitCodes.CONFIG_ERROR);\n }\n\n }\n\n /**\n * Setup {@link GraphiteReporter} if enabled in config\n * @throws IOException\n */\n private void configureMetrics() throws IOException {\n\n this.metricRegistry = new MetricRegistry();\n this.metricReporters = new ArrayList<ScheduledReporter>();\n\n String prefix = conf.get(NodeConfig.GRAPHITE_PREFIX, \"\") +\n NetworkUtil.getLocalhost().replace('.', '_');\n\n String host = conf.get(NodeConfig.GRAPHITE_HOST);\n if (host != null) {\n LOG.info(\"Enabling graphite metrics\");\n\n int port = conf.getInt(NodeConfig.GRAPHITE_PORT, 2003);\n Graphite graphite = new Graphite(new InetSocketAddress(host, port));\n addMetricReporter(GraphiteReporter.forRegistry(metricRegistry)\n .prefixedWith(prefix)\n .convertRatesTo(TimeUnit.SECONDS)\n .convertDurationsTo(TimeUnit.MILLISECONDS)\n .build(graphite)).start(1, TimeUnit.MINUTES);\n }\n\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Enabling console metrics since DEBUG level enabled\");\n Graphite graphite = new GraphiteConsole();\n addMetricReporter(GraphiteReporter.forRegistry(metricRegistry)\n .prefixedWith(prefix)\n .convertRatesTo(TimeUnit.SECONDS)\n .convertDurationsTo(TimeUnit.MILLISECONDS)\n .build(graphite)).start(1, TimeUnit.MINUTES);\n }\n\n }\n\n /**\n * Cleanup any configured metrics\n */\n private void cleanupMetrics() {\n if (metricReporters == null) {\n return;\n }\n for (ScheduledReporter reporter : metricReporters) {\n reporter.stop();\n }\n }\n\n /**\n * Start the node. Open source and enable metric reporting\n */\n @Override\n public void run() {\n\n try {\n configureMetrics();\n\n LOG.debug(\"Opening source\");\n this.source.open();\n } catch (IOException e) {\n LOG.error(\"Failed to open source: \" + e.getMessage(), e);\n System.exit(ExitCodes.IO_ERROR);\n\n }\n\n }\n\n /**\n * Stop the node. Close the source and any sinks and disable metric reporting\n */\n public void shutdown() {\n if (source != null) {\n try {\n source.close();\n } catch (IOException e) {\n LOG.error(\"Source failed to close cleanly: \" + e.getMessage(), e);\n }\n }\n cleanupMetrics();\n }\n\n\n // GETTERS & SETTERS\n\n public Source getSource() {\n return source;\n }\n\n public PlumbingFactory<Sink> getSinkFactory() {\n return sinkFactory;\n }\n\n public NodeConfig getConf() {\n return conf;\n }\n\n public MetricRegistry getMetricRegistry() {\n return metricRegistry;\n }\n\n public List<ScheduledReporter> getMetricReporters() {\n return metricReporters;\n }\n\n public ScheduledReporter addMetricReporter(ScheduledReporter reporter) {\n this.metricReporters.add(reporter);\n return reporter;\n }\n\n}", "public class NodeConfig extends Configuration {\n\n public static final String SOURCE = \"sewer.source\";\n public static final String SINK = \"sewer.sink\";\n public static final String WAL_PATH = \"sewer.wal.path\";\n public static final String PLUGINS = \"sewer.plugins\";\n\n public static final String GRAPHITE_HOST = \"sewer.metrics.graphite.host\";\n public static final String GRAPHITE_PORT = \"sewer.metrics.graphite.port\";\n public static final String GRAPHITE_PREFIX = \"sewer.metrics.graphite.prefix\";\n\n public NodeConfig() {\n super();\n }\n\n public NodeConfig(boolean loadDefaults) {\n super(loadDefaults);\n }\n\n public NodeConfig(Configuration other) {\n super(other);\n }\n\n /**\n * Add the properties contained in file into this configuration\n * @param props\n */\n public void addResource(Properties props) {\n\n for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {\n String name = (String) e.nextElement();\n set(name, props.getProperty(name));\n }\n\n }\n\n}", "@DrainSink\npublic class SequenceFileSink extends BucketedSink {\n\n private static final Logger LOG = LoggerFactory.getLogger(SequenceFileSink.class);\n\n private static final VLongWritable ONE = new VLongWritable(1L);\n\n /**\n * Configured path to write to\n */\n protected String configPath;\n\n /**\n * Reference to {@link Path} object\n */\n protected Path dstPath;\n\n protected Writer writer;\n\n public SequenceFileSink(String[] args) {\n this.configPath = args[0];\n }\n\n @Override\n public void close() throws IOException {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"close() called; currently: \" + getStatusString());\n LOG.debug(\"Closing: \" + HdfsUtil.pathToString(dstPath));\n }\n\n if (writer != null) {\n writer.close();\n }\n nextBucket = null;\n setStatus(CLOSED);\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\"Closed: \" + HdfsUtil.pathToString(dstPath));\n }\n }\n\n @Override\n public void open() throws IOException {\n LOG.debug(\"open\");\n setStatus(OPENING);\n if (nextBucket == null) {\n generateNextBucket();\n }\n createWriter();\n setStatus(FLOWING);\n }\n\n protected void createWriter() throws IOException {\n\n Configuration conf = Node.getInstance().getConf();\n\n CompressionCodec codec = HdfsUtil.createCodec();\n dstPath = new Path(nextBucket + \".seq\");\n\n writer = SequenceFile.createWriter(\n conf,\n Writer.file(dstPath),\n Writer.keyClass(Node.getInstance().getSource().getEventClass()),\n Writer.valueClass(VLongWritable.class),\n Writer.compression(CompressionType.BLOCK, codec)\n );\n\n if (LOG.isInfoEnabled()) {\n LOG.info(\"Opened: \" + HdfsUtil.pathToString(dstPath));\n }\n\n nextBucket = null;\n }\n\n @Override\n public String getFileExt() {\n return \".seq\";\n }\n\n @Override\n public String generateNextBucket() {\n nextBucket = BucketPath.escapeString(configPath);\n return nextBucket;\n }\n\n @Override\n public void append(Event event) throws IOException {\n writer.append(event, ONE);\n }\n\n}", "public class TransactionSource extends Source {\n\n private static final Logger LOG = LoggerFactory.getLogger(TransactionSource.class);\n\n private Transaction tx;\n\n private Path path;\n private String bucket;\n private String ext;\n private Sink sink;\n\n public TransactionSource(Transaction tx) {\n\n this.tx = tx;\n\n this.path = tx.createTxPath();\n this.bucket = tx.getBucket();\n this.ext = tx.getFileExt();\n }\n\n @Override\n public void close() throws IOException {\n if (sink != null && sink.getStatus() != CLOSED) {\n sink.close();\n }\n }\n\n /**\n * Opens the SequenceFile and drains its contents to the configured Sink\n */\n @Override\n public void open() throws IOException {\n LOG.debug(\"Going to drain \" + path.toString() + \" to bucket \" + bucket);\n setStatus(FLOWING);\n\n sink = getSinkFactory().build();\n if (sink instanceof SequenceFileSink || sink instanceof DfsSink) {\n\n // before we do anything, let's delete the existing destination file so\n // we don't have any problems\n final Path destFile = new Path(bucket + ext);\n deleteExistingFile(destFile);\n\n copySequenceFileToDfs(path, destFile);\n\n } else {\n copySequenceFileToSink();\n }\n\n setStatus(CLOSED);\n }\n\n /**\n * Copy a file directly to output, byte by byte\n *\n * @param input\n * @param output\n * @throws IOException\n */\n private void copySequenceFileToDfs(Path input, Path output) throws IOException {\n Configuration conf = new Configuration();\n output.getFileSystem(conf).copyFromLocalFile(input, output);\n }\n\n /**\n * Read a sequence file and copy it to the subsink\n *\n * @throws IOException\n */\n private void copySequenceFileToSink() throws IOException {\n\n if (sink instanceof BucketedSink && bucket != null) {\n ((BucketedSink) sink).setNextBucket(bucket);\n }\n sink.open();\n\n Reader reader = null;\n try {\n try {\n reader = createReader();\n } catch (IOException e) {\n // May occur if the file wasn't found or is zero bytes (never received any data)\n // This generally happens if the server was stopped improperly (kill -9, crash, reboot)\n LOG.warn(\"Failed to open tx \" + tx + \" at \" + tx.createTxPath().toString()\n + \"; this usually means the file is 0 bytes or the header is corrupted/incomplete\", e);\n return;\n }\n setStatus(FLOWING);\n\n Event event = null;\n VLongWritable lng = new VLongWritable();\n try {\n event = tx.newEvent();\n } catch (Exception e) {\n // Should really never happen, since the Event class should always be available\n throw new IOException(\"Failed to create Event class\", e);\n }\n\n\n while (true) {\n\n try {\n if (!reader.next(event, lng)) {\n break;\n }\n } catch (IOException e) {\n if (e instanceof EOFException) {\n LOG.warn(\"Caught EOF reading from buffer; skipping to close\");\n break;\n } else if (e instanceof ChecksumException) {\n LOG.warn(\"Caught ChecksumException reading from buffer; skipping to close\");\n break;\n }\n throw e;\n }\n\n sink.append(event);\n }\n\n\n } finally {\n if (reader != null) {\n try {\n reader.close();\n } catch (IOException e) {\n // safe to ignore (hopefully :)\n // because at this point, we only care about errors when closing the sink\n }\n }\n }\n\n\n }\n\n /**\n * Try to delete the existing file. Throws exception if it takes more than 10 seconds\n * @throws IOException\n */\n private void deleteExistingFile(final Path file) throws IOException {\n\n TimeoutThread t = new TimeoutThread() {\n @Override\n public void work() throws Exception {\n try {\n HdfsUtil.deletePath(file);\n } catch (InterruptedException e) {\n throw new IOException(\"Interrupted trying to delete \" + file, e);\n }\n }\n };\n if (!t.await(10, TimeUnit.SECONDS)) {\n setStatus(ERROR);\n throw new IOException(\"Error trying to delete \" + file, t.getError());\n }\n }\n\n private Reader createReader() throws IOException {\n Configuration conf = Node.getInstance().getConf();\n return new SequenceFile.Reader(conf, Reader.file(path));\n }\n\n @Override\n public Class<?> getEventClass() {\n return ByteArrayEvent.class;\n }\n\n}", "public class BackoffHelper {\n\n private int failures;\n private Stopwatch stopwatch;\n\n public BackoffHelper() {\n failures = 0;\n stopwatch = new Stopwatch();\n stopwatch.start();\n }\n\n /**\n * Increments failure count, prints a diagnostic message and sleeps for some amount of time\n * based on the number of failures that have occurred. Max sleep time is 30 seconds.\n *\n * @param t\n * @param log\n * @param msg\n * @param retryCanceled\n * @throws InterruptedException\n */\n public void handleFailure(Throwable t, Logger log, String msg, boolean retryCanceled) throws InterruptedException {\n\n failures++;\n if (log.isWarnEnabled()) {\n log.warn(msg + \", failures = \" + failures + \" (\" + message(t) + \")\", t);\n }\n\n if (retryCanceled) {\n return;\n }\n\n int backoff = 5000;\n if (failures > 30) {\n backoff = 10000;\n\n } else if (failures > 100) {\n backoff = 30000;\n }\n\n log.info(\"Sleeping for \" + backoff + \"ms before retry\");\n Thread.sleep(backoff);\n }\n\n private String message(Throwable t) {\n if (t.getMessage() != null) {\n return t.getMessage();\n }\n return t.getClass().getCanonicalName();\n }\n\n /**\n * After successfully completing the action, print a diagnostic message if necessary\n *\n * @param log\n * @param msg\n */\n public void resolve(Logger log, String msg) {\n\n if (!log.isDebugEnabled() && (failures == 0 || !log.isInfoEnabled())) {\n return;\n }\n\n // will always be shown if debug is enabled\n log.debug(msg + \" after \" + failures + \" failures (\" + getElapsedTime() + \")\");\n }\n\n public int getNumFailures() {\n return failures;\n }\n\n public String getElapsedTime() {\n return stopwatch.toString();\n }\n\n}" ]
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import net.pixelcop.sewer.DrainSink; import net.pixelcop.sewer.PlumbingBuilder; import net.pixelcop.sewer.PlumbingFactory; import net.pixelcop.sewer.Sink; import net.pixelcop.sewer.node.ExitCodes; import net.pixelcop.sewer.node.Node; import net.pixelcop.sewer.node.NodeConfig; import net.pixelcop.sewer.sink.SequenceFileSink; import net.pixelcop.sewer.source.TransactionSource; import net.pixelcop.sewer.util.BackoffHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper;
if (drainingTx != null) { failedTransactions.add(drainingTx); drainingTx = null; } saveOpenTransactionsToDisk(); return; } if (drainingTx == null) { continue; } setStatus(DRAINING); // drain it if (!drainTx()) { // drain failed (interrupted, tx man shutting down), stick tx at end of queue (front ??) failedTransactions.add(drainingTx); drainingTx = null; saveOpenTransactionsToDisk(); return; } drainingTx.deleteTxFiles(); drainingTx = null; saveOpenTransactionsToDisk(); setStatus(IDLE); } } /** * Save all transactions we know about to disk */ protected void saveOpenTransactionsToDisk() { synchronized (DEFAULT_WAL_PATH) { File txLog = getTxLog(); if (LOG.isDebugEnabled()) { LOG.debug("Saving transaction queues to disk " + txLog.toString()); } List<Transaction> txList = new ArrayList<Transaction>(); if (drainingTx != null) { if (LOG.isTraceEnabled()) { LOG.trace("Found tx currently being drained"); } txList.add(drainingTx); } if (!transactions.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace("Found " + transactions.size() + " presently open transactions"); } txList.addAll(transactions.values()); } if (!failedTransactions.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace("Found " + failedTransactions.size() + " lost transactions"); } txList.addAll(failedTransactions); } try { new ObjectMapper().writeValue(txLog, txList); LOG.trace("save complete"); } catch (IOException e) { LOG.error("Failed to write txn.log: " + e.getMessage(), e); } } } /** * Load transaction log from disk so we can restart them */ protected void loadTransctionsFromDisk() { File txLog = getTxLog(); if (LOG.isDebugEnabled()) { LOG.debug("Loading transaction queues from disk " + txLog.toString()); } try { ArrayList<Transaction> recovered = new ObjectMapper().readValue(txLog, new TypeReference<ArrayList<Transaction>>() {}); LOG.info("Loaded " + recovered.size() + " txns from disk"); failedTransactions.addAll(recovered); } catch (FileNotFoundException e) { LOG.debug(e.getMessage()); return; // no biggie, just doesn't exist yet } catch (Exception e) { LOG.error("Failed to load txn.log: " + e.getMessage()); System.exit(ExitCodes.STARTUP_ERROR); } } protected File getTxLog() { return new File(getWALPath() + "/txn.log"); } /** * Drains the currently selected Transaction. Returns on completion or if interrupted */ private boolean drainTx() { // drain this tx to sink LOG.debug("Draining tx " + drainingTx);
BackoffHelper backoff = new BackoffHelper();
8
bretthshelley/Maven-IIB9-Plug-In
src/main/java/ch/sbb/maven/plugins/iib/mojos/PackageBarMojo.java
[ "public static String validateCreateOrPackageBar(String createOrPackageBar, Log log) throws MojoFailureException\n{\n if (createOrPackageBar != null && !createOrPackageBar.trim().isEmpty())\n {\n if (createOrPackageBar.trim().equalsIgnoreCase(\"create\")\n || createOrPackageBar.trim().equalsIgnoreCase(\"createbar\")) {\n return \"create\";\n }\n if (createOrPackageBar.trim().equalsIgnoreCase(\"package\")\n || createOrPackageBar.trim().equalsIgnoreCase(\"packagebar\")) {\n return \"package\";\n }\n }\n\n logErrorStart(log);\n String[] messages = { getArgumentMissingString(\"createOrPackageBar\") };\n logErrorBaseProblem(log, messages);\n\n String tagName = \"createOrPackageBar\";\n String exampleText1 = \"create\";\n String exampleTagString1 = getExampleTagString(tagName, exampleText1);\n String exampleText2 = \"package\";\n String exampleTagString2 = getExampleTagString(tagName, exampleText2);\n logErrorExample(log, new String[] { exampleTagString1, \"OR\", exampleTagString2 });\n\n String[] instructions = new String[]\n {\n \"The 'createOrPackageBar' configuration value tells the plugin whether to \",\n \"execute mqsiCreateBar which compiles messages flows or to\",\n \"execute packageBar which does not compile message flows.\",\n \"Note that the 'create' (mqsiCreateBar) approach is preferred but slower,\",\n \"while the 'package' approach is faster but does not compile message flows.\"\n };\n logErrorInstructions(log, instructions);\n\n logErrorFinish(log);\n\n throw new MojoFailureException(getArgumentMissingString(\"createOrPackageBar\"));\n\n\n}", "public static void validatePathToMqsiProfileScript(String pathToMqsiProfileScript, Log log) throws MojoFailureException\n{\n if (pathToMqsiProfileScript == null || pathToMqsiProfileScript.trim().equals(\"\"))\n {\n logErrorStart(log);\n String[] messages = { getArgumentMissingString(\"pathToMqsiProfileScript\") };\n logErrorBaseProblem(log, messages);\n String tagName = \"pathToMqsiProfileScript\";\n String exampleText1 = \"C:\\\\Program Files\\\\IBM\\\\MQSI\\\\9.0.0.2\\\\bin\\\\mqsiprofile.cmd\";\n String exampleTagString1 = getExampleTagString(tagName, exampleText1);\n logErrorExample(log, new String[] { exampleTagString1 });\n String[] instructions = new String[]\n {\n \"The 'pathToMqsiProfileScript' configuration value tells the plugin where to \",\n \"execute the mqsiprofile command or shell script. It is necessary to execute\",\n \"this command prior to executing mqsicreatebar...\"\n };\n logErrorInstructions(log, instructions);\n logErrorFinish(log);\n throw new MojoFailureException(getArgumentMissingString(\"copyDependentJarsLocation\"));\n }\n File file = new File(pathToMqsiProfileScript);\n if (!file.exists())\n {\n logErrorStart(log);\n String[] messages = { getFileMissingString(\"pathToMqsiProfileScript\", pathToMqsiProfileScript) };\n logErrorBaseProblem(log, messages);\n String tagName = \"pathToMqsiProfileScript\";\n String exampleText1 = \"C:\\\\Program Files\\\\IBM\\\\MQSI\\\\9.0.0.2\\\\bin\\\\mqsiprofile.cmd\";\n String exampleTagString1 = getExampleTagString(tagName, exampleText1);\n logErrorExample(log, new String[] { exampleTagString1 });\n String[] instructions = new String[]\n {\n \"The 'pathToMqsiProfileScript' configuration value tells the plugin where to \",\n \"execute the mqsiprofile command or shell script. \"\n };\n logErrorInstructions(log, instructions);\n logErrorFinish(log);\n throw new MojoFailureException(getArgumentMissingString(\"copyDependentJarsLocation\"));\n }\n\n}", "public class DependenciesManager {\n private TreeSet<String> apps = new TreeSet<String>();\n private TreeSet<String> libs = new TreeSet<String>();\n private TreeSet<String> javaProjects = new TreeSet<String>();\n\n private MavenProject project;\n private File workspace;\n private Log log;\n\n public DependenciesManager() {\n super();\n }\n\n\n public DependenciesManager(MavenProject project, File workspace, Log log) throws MojoFailureException {\n super();\n this.project = project;\n this.workspace = workspace;\n this.log = log;\n determineDependencies();\n }\n\n public String getApp()\n {\n return project.getArtifactId();\n }\n\n public Collection<String> getDependentApps()\n {\n Set<String> dependentApps = new TreeSet<String>();\n dependentApps.addAll(apps);\n dependentApps.remove(project.getArtifactId());\n return dependentApps;\n }\n\n public Collection<String> getDependentLibs()\n {\n Set<String> dependentLibs = new TreeSet<String>();\n dependentLibs.addAll(libs);\n return dependentLibs;\n }\n\n public Collection<String> getDependentJavaProjects()\n {\n Set<String> projects = new TreeSet<String>();\n projects.addAll(javaProjects);\n return projects;\n }\n\n private void determineEclipseProjectDependencies() throws MojoFailureException\n {\n determineEclipseProjectDependencies(project.getArtifactId());\n }\n\n private void determineDependencies() throws MojoFailureException {\n\n determineEclipseProjectDependencies();\n\n // / let's add this project itself, either as an application or a\n if (EclipseProjectUtils.isApplication(new File(workspace, project.getArtifactId()), getLog()))\n {\n apps.add(project.getArtifactId());\n }\n else if (EclipseProjectUtils.isLibrary(new File(workspace, project.getArtifactId()), getLog()))\n {\n libs.add(project.getArtifactId());\n }\n else if (EclipseProjectUtils.isJavaProject(new File(workspace, project.getArtifactId()), getLog()))\n {\n javaProjects.add(project.getArtifactId());\n }\n else\n {\n // / make the assumption that the project itself is an application\n apps.add(project.getArtifactId());\n }\n\n for (Dependency dependency : project.getDependencies()) {\n\n // only check for dependencies with scope \"compile\"\n if (!dependency.getScope().equals(\"compile\")) {\n continue;\n }\n\n // the projectName is the directoryName is the artifactId\n String projectName = dependency.getArtifactId();\n\n if (EclipseProjectUtils.isApplication(new File(workspace, projectName), getLog())) {\n apps.add(projectName);\n }\n else if (EclipseProjectUtils.isLibrary(new File(workspace, projectName), getLog())) {\n libs.add(projectName);\n }\n\n }\n\n\n }\n\n\n public void fixIndirectLibraryReferences(File projectDirectory) throws Exception\n {\n new EclipseProjectFixUtil().fixIndirectLibraryReferences(projectDirectory, libs, log);\n }\n\n /**\n * @param projectDirectory\n * @throws MojoFailureException\n */\n private void determineEclipseProjectDependencies(String projectDirectory) throws MojoFailureException\n {\n File projectDir = new File(workspace, projectDirectory);\n String[] projectNames = EclipseProjectUtils.getDependentProjectNames(projectDir);\n for (String projectName : projectNames)\n {\n if (EclipseProjectUtils.isApplication(new File(workspace, projectName), getLog()))\n {\n apps.add(projectName);\n\n }\n else if (EclipseProjectUtils.isLibrary(new File(workspace, projectName), getLog()))\n {\n libs.add(projectName);\n }\n determineEclipseProjectDependencies(projectName);\n }\n\n }\n\n\n private Log getLog() {\n return log;\n }\n\n\n}", "public class DirectoriesUtil {\n\n public static final String REGEX = \"\\\\s*,[,\\\\s]*\";\n\n private List<File> tempPomFiles = new ArrayList<File>();\n\n public void renamePomXmlFiles(File workspace, Log log) throws IOException\n {\n // / remove .pom from directories\n File[] projectDirectories = workspace.listFiles();\n for (File projectDirectory : projectDirectories)\n {\n if (!projectDirectory.isDirectory()) {\n continue;\n }\n if (projectDirectory.getName().startsWith(\".\"))\n {\n continue;\n }\n\n String pomPath = projectDirectory.getAbsolutePath() + File.separator + \"pom.xml\";\n File pomFile = new File(pomPath);\n log.info(\"seeking file \" + pomFile + \" to temporarily rename\");\n if (!pomFile.exists()) {\n continue;\n }\n\n String tempPomPath = projectDirectory.getAbsolutePath() + File.separator + \"pom-xml-temp.txt\";\n\n File tempPomFile = new File(tempPomPath);\n log.info(\"-->copying file \" + pomFile + \" to \" + tempPomPath);\n\n FileUtils.copyFile(pomFile, tempPomFile, true);\n tempPomFiles.add(tempPomFile);\n log.info(\"-->deleting file: \" + pomFile.getAbsolutePath());\n try\n {\n FileUtils.forceDelete(pomFile);\n } catch (IOException e)\n {\n String message = \"This plugin attempts to remove pom.xml files from the workspace.\\n\";\n message += \"The pom.xml files are the temporarily stored in the user.home directory at \" + System.getProperty(\"user.home\") + \"\\n\";\n message += \"It failed to delete the file \" + pomFile.getAbsolutePath() + \"\\n\";\n message += \"Please check to ensure that no process is blocking the file's (\" + pomFile.getAbsolutePath() + \") deletion.\\n\";\n message += \"Please check to ensure that no process is blocking the file's deletion.\\n\";\n message += \"The presence of the pom.xml file(s) will cause the mqsicreatebar command to fail.\\n\";\n message += \"Error: \" + e.toString();\n log.warn(message);\n throw e;\n }\n\n }\n\n\n }\n\n\n public static String[] getFilesAndRegexes(String commaSeparatedDirectories)\n {\n if (commaSeparatedDirectories == null || commaSeparatedDirectories.trim().isEmpty()) {\n return new String[0];\n }\n\n return commaSeparatedDirectories.split(REGEX);\n\n }\n\n\n public void restorePomFiles(File workspace, Log log) throws IOException\n {\n\n for (File tempPomFile : tempPomFiles)\n {\n String pomFilePath = tempPomFile.getAbsolutePath();\n pomFilePath = pomFilePath.substring(0, pomFilePath.lastIndexOf(File.separator));\n pomFilePath += File.separator + \"pom.xml\";\n\n File origFile = new File(pomFilePath);\n FileUtils.copyFile(tempPomFile, origFile);\n FileUtils.forceDelete(tempPomFile);\n }\n\n }\n}", "public enum MqsiCommand {\n mqsicreatebar,\n mqsideploy\n\n}", "public class MqsiCommandLauncher {\n\n\n /**\n * \n * @param log\n * @param pathToMqsiProfileScript\n * @param mqsiPrefixCommands\n * @param mqsiCommand\n * @param commands\n * @param mqsiReplacementCommand\n * @throws MojoFailureException\n */\n public void execute(Log log, String pathToMqsiProfileScript, String mqsiPrefixCommands, MqsiCommand mqsiCommand, String[] commands, String mqsiReplacementCommand) throws MojoFailureException\n {\n\n\n final ArrayList<String> osCommands = new ArrayList<String>();\n\n addMqsiSetProfileCommands(log, pathToMqsiProfileScript, mqsiPrefixCommands, osCommands);\n\n\n osCommands.add(mqsiCommand.toString());\n for (String c : commands)\n {\n osCommands.add(c);\n }\n logGeneratedCommands(log, osCommands);\n\n // / now we check to see if the user has chosen to run a separate mqsiReplacement command to override the default command\n // if replacement commands are set, then we replace the commands with what has been entered\n // this gives the user an opportunity to 'tweak' the mqsi commands being run\n\n if (mqsiReplacementCommand != null && !mqsiReplacementCommand.trim().isEmpty())\n {\n osCommands.clear();\n addMqsiSetProfileCommands(log, pathToMqsiProfileScript, mqsiPrefixCommands, osCommands);\n String[] replacementCommands = new CommandParser().parseCommands(mqsiReplacementCommand);\n for (String replacementCommand : replacementCommands)\n {\n osCommands.add(replacementCommand);\n }\n logReplacementCommands(log, osCommands);\n }\n\n\n final ProcessBuilder builder = new ProcessBuilder(osCommands);\n\n TimeElapsedThread thread = new TimeElapsedThread(log);\n try\n {\n builder.redirectErrorStream(true);\n builder.redirectOutput(Redirect.PIPE);\n\n\n thread.start();\n Process process = builder.start();\n\n final InputStream in = process.getInputStream();\n\n BufferedReader brStandardOut = new BufferedReader(new InputStreamReader(in, \"UTF-8\"));\n StringBuilder out = new StringBuilder();\n String standardOutLine = null;\n while ((standardOutLine = brStandardOut.readLine()) != null)\n {\n log.info(standardOutLine);\n out.append(standardOutLine + \"\\n\");\n }\n process.waitFor();\n thread.interrupt();\n\n log.info(\"process ended with a \" + process.exitValue() + \" value\");\n\n if (process.exitValue() != 0)\n {\n throw new MojoFailureException(out.toString());\n }\n\n\n } catch (Exception e)\n {\n log.info(\"unable to execute \" + mqsiCommand + \" with arguments \" + commands);\n throw new MojoFailureException(\"Unable to execute command(s): \" + osCommands + \" : \" + e);\n }\n\n\n }\n\n private void addMqsiSetProfileCommands(Log log, String pathToMqsiProfileScript, String mqsiPrefixCommands, final ArrayList<String> osCommands) throws MojoFailureException {\n if (OSValidator.isWindows())\n {\n\n if (!FileUtils.fileExists(pathToMqsiProfileScript))\n {\n String message = \"The mqsiprofile script could not be found or reached at the path \" + pathToMqsiProfileScript;\n throw new MojoFailureException(message);\n }\n\n\n osCommands.add(\"cmd\");\n osCommands.add(\"/c\");\n osCommands.add(pathToMqsiProfileScript);// \"\\\"C:\\\\Program Files\\\\IBM\\\\MQSI\\\\9.0.0.2\\\\bin\\\\mqsiprofile.cmd\\\"\");\n osCommands.add(\"&\");\n osCommands.add(\"cmd\");\n osCommands.add(\"/c\");\n }\n else\n {\n if (mqsiPrefixCommands == null || mqsiPrefixCommands.trim().isEmpty())\n {\n String message = \"The configuration parameter 'mqsiPrefixCommands' is needed for this operating system. This configuration parameter is a \";\n message += \"comma-separated set of commands to run before executing a specific mqsicommand. The command needs to typically execute mqsiprofile and setup the mqsicommand\";\n throw new MojoFailureException(message);\n\n\n }\n String[] prefixCommands = mqsiPrefixCommands.split(Pattern.quote(\",\"));\n for (String prefixCommand : prefixCommands)\n {\n if (prefixCommand == null || prefixCommand.trim().isEmpty()) {\n continue;\n }\n log.info(\"adding '\" + prefixCommand + \"' to commands array\");\n osCommands.add(prefixCommand);\n }\n\n }\n }\n\n public void logGeneratedCommands(Log log, List<String> osCommands)\n {\n\n String launchMessage = \"\\n\\n\"\n + \"generated mqsiCommand follows...\\n\"\n + \"--------------------------------\\n\\n\";\n launchMessage += new CommandParser().toSingleLineCommand(osCommands);\n launchMessage += \"\\n\\n\";\n launchMessage += \"--------------------------------\\n\";\n log.info(launchMessage);\n }\n\n\n public void logReplacementCommands(Log log, List<String> osCommands)\n {\n String launchMessage = \"\\n\\n\"\n + \"replacement mqsiCommand follows...\\n\"\n + \"--------------------------------\\n\\n\";\n launchMessage += new CommandParser().toSingleLineCommand(osCommands);\n launchMessage += \"\\n\\n\";\n launchMessage += \"--------------------------------\\n\";\n log.info(launchMessage);\n }\n\n\n class TimeElapsedThread extends Thread\n {\n private long startTime = -1;\n private long sleepTime = 20000;\n Log log;\n\n TimeElapsedThread(Log log)\n {\n this.log = log;\n }\n\n @Override\n public void run()\n {\n try\n {\n startTime = System.currentTimeMillis();\n\n while (true)\n {\n Thread.sleep(sleepTime);\n\n long timeElapsed = System.currentTimeMillis() - startTime;\n long minutes = timeElapsed / 60000;\n long seconds = (timeElapsed - (minutes * 60000)) / 1000;\n String message = \"\";\n if (minutes == 0)\n {\n message += seconds + \" seconds elapsed...\";\n }\n else if (minutes == 1)\n {\n if (seconds < 2)\n {\n message += minutes + \" minute elapsed...\";\n }\n else\n {\n message += minutes + \" minute and \" + seconds + \" seconds elapsed...\";\n }\n\n }\n else\n {\n if (seconds < 2)\n {\n message += minutes + \" minutes elapsed...\";\n }\n else\n {\n message += minutes + \" minutes and \" + seconds + \" seconds elapsed...\";\n }\n }\n log.info(message);\n\n }\n\n\n } catch (Exception ie)\n {\n log.info(\"shutting down timer\");\n }\n\n\n }\n\n\n }\n\n\n static class OSValidator {\n\n private static String OS = System.getProperty(\"os.name\").toLowerCase();\n\n public static boolean isWindows() {\n\n return (OS.indexOf(\"win\") >= 0);\n }\n\n public static boolean isMac() {\n\n return (OS.indexOf(\"mac\") >= 0);\n\n }\n\n public static boolean isUnix() {\n\n return (OS.indexOf(\"nix\") >= 0 || OS.indexOf(\"nux\") >= 0 || OS.indexOf(\"aix\") > 0);\n }\n\n public static boolean isSolaris() {\n\n return (OS.indexOf(\"sunos\") >= 0);\n\n }\n\n }\n\n\n}", "public class SkipUtil {\n\n @SuppressWarnings(\"rawtypes\")\n static LinkedHashMap<Class, String> classGoalMap = new LinkedHashMap<Class, String>();\n List<String> skipGoals = new ArrayList<String>();\n String skipToGoal = null;\n\n static\n {\n classGoalMap.put(InitializeBarBuildWorkspaceMojo.class, \"initialize\");\n classGoalMap.put(PrepareBarBuildWorkspaceMojo.class, \"generate-resources\");\n classGoalMap.put(ValidateBarBuildWorkspaceMojo.class, \"process-resources\");\n classGoalMap.put(PackageBarMojo.class, \"compile\");\n classGoalMap.put(String.class, \"test-compile\");\n classGoalMap.put(ApplyBarOverridesMojo.class, \"process-classes\");\n classGoalMap.put(ValidateClassloaderApproachMojo.class, \"process-classes\");\n classGoalMap.put(MqsiDeployMojo.class, \"pre-integration-test\");\n classGoalMap.put(Integer.class, \"integration-test\");\n classGoalMap.put(Double.class, \"verify\");\n classGoalMap.put(DeployBarMojo.class, \"deploy\");\n\n\n }\n\n private static String getValidGoals()\n {\n boolean first = true;\n StringBuilder sb = new StringBuilder();\n for (String goal : classGoalMap.values())\n {\n if (!first)\n {\n sb.append(\",\");\n }\n sb.append(goal);\n first = false;\n }\n return sb.toString();\n }\n\n\n @SuppressWarnings(\"rawtypes\")\n public boolean isSkip(Class clazz)\n {\n // / determine goals to skip from comma-separated list\n String skip = System.getProperty(\"skip\");\n if (skip != null && !skip.trim().isEmpty())\n {\n String[] sa = skip.split(Pattern.quote(\",\"));\n for (String goal : sa)\n {\n if (goal == null) {\n continue;\n }\n if (goal.trim().isEmpty()) {\n continue;\n }\n goal = goal.trim().toLowerCase();\n if (!classGoalMap.values().contains(goal)) {\n throw new RuntimeException(\"The '-Dskip=...' value(s) must be a comma-separated list of goal(s) from the group:\" + getValidGoals());\n\n }\n skipGoals.add(goal);\n }\n }\n\n // / determine goals to skip from comma-separated list\n String skipTo = System.getProperty(\"skipTo\");\n if (skipTo != null && !skipTo.trim().isEmpty())\n {\n skipTo = skipTo.toLowerCase().trim();\n\n if (!classGoalMap.values().contains(skipTo))\n {\n throw new RuntimeException(\"The '-DskipTo=...' value must be a single goal from the group:\" + getValidGoals());\n }\n skipToGoal = skipTo;\n\n }\n\n\n if (skipGoals.isEmpty() && skipToGoal == null) {\n return false;\n }\n\n String currentGoal = classGoalMap.get(clazz);\n if (skipGoals.contains(currentGoal))\n {\n return true;\n }\n\n // / see if skipToGoal\n if (skipToGoal == null)\n {\n return false;\n }\n\n\n // / go through the list to determine if goal is before current\n if (skipToGoal.equals(currentGoal)) {\n return false;\n }\n\n List<String> goalsBefore = new ArrayList<String>();\n List<String> goalsAfter = new ArrayList<String>();\n boolean skipToGoalFound = false;\n for (String goal : classGoalMap.values())\n {\n if (goal.equals(skipToGoal))\n {\n skipToGoalFound = true;\n continue;\n }\n if (skipToGoalFound)\n {\n goalsAfter.add(goal);\n }\n else\n {\n goalsBefore.add(goal);\n }\n }\n\n if (goalsBefore.contains(currentGoal)) {\n return true;\n }\n if (goalsAfter.contains(currentGoal)) {\n return false;\n }\n return false;\n\n\n }\n\n\n}" ]
import static ch.sbb.maven.plugins.iib.utils.ConfigurationValidator.validateCreateOrPackageBar; import static ch.sbb.maven.plugins.iib.utils.ConfigurationValidator.validatePathToMqsiProfileScript; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; import ch.sbb.maven.plugins.iib.utils.DependenciesManager; import ch.sbb.maven.plugins.iib.utils.DirectoriesUtil; import ch.sbb.maven.plugins.iib.utils.MqsiCommand; import ch.sbb.maven.plugins.iib.utils.MqsiCommandLauncher; import ch.sbb.maven.plugins.iib.utils.SkipUtil; import com.ibm.broker.config.appdev.CommandProcessorPublicWrapper;
package ch.sbb.maven.plugins.iib.mojos; /** * Packages or Creates a .bar file. */ @Mojo(name = "package-bar", defaultPhase = LifecyclePhase.COMPILE) public class PackageBarMojo extends AbstractMojo { /** * indicates whether this MOJO will use MQSI commands to perform tasks or default to original SBB approach. * */ @Parameter(property = "createOrPackageBar", required = false, defaultValue = "create") protected String createOrPackageBar; private boolean create; /** * indicates the absolute file path to the location of the mqsiprofile command or shell script. */ @Parameter(property = "pathToMqsiProfileScript", defaultValue = "\"C:\\Program Files\\IBM\\MQSI\\9.0.0.2\\bin\\mqsiprofile.cmd\"", required = false) protected String pathToMqsiProfileScript; /** * a comma-separated list of commands that will be issued to the underlying os before launching the mqsi* command. * This will substitute for the Windows approach covered by the 'pathToMqsiProfileScript' value. These * commands should be operating system specific and * execute the mqsiprofile command as well as setup the launch of the followup mqsi command * */ @Parameter(property = "mqsiPrefixCommands", required = false) protected String mqsiPrefixCommands; @Parameter(property = "mqsiCreateBarReplacementCommand", required = false, defaultValue = "") protected String mqsiCreateBarReplacementCommand; @Parameter(property = "mqsiCreateBarCompileOnlyReplacementCommand", required = false, defaultValue = "") protected String mqsiCreateBarCompileOnlyReplacementCommand; /** * The name of the BAR (compressed file format) archive file where the * result is stored. */ @Parameter(property = "barName", defaultValue = "${project.build.directory}/${project.artifactId}-${project.version}.bar", required = true) protected File barName; /** * The name of the trace file to use when packaging bar files */ @Parameter(property = "packageBarTraceFile", defaultValue = "${project.build.directory}/packagebartrace.txt", required = true) protected File packageBarTraceFile; /** * The name of the trace file to use when packaging bar files */ @Parameter(property = "createBarTraceFile", defaultValue = "${project.build.directory}/createbartrace.txt", required = true) protected File createBarTraceFile; /** * The path of the workspace in which the projects are extracted to be built. */ @Parameter(property = "workspace", required = true) protected File workspace; /** * The Maven Project Object */ @Parameter(property = "project", required = true, readonly = true) protected MavenProject project; /** * The Maven Session Object */ @Parameter(property = "session", required = true, readonly = true) protected MavenSession session; /** * The Maven PluginManager Object */ @Component protected BuildPluginManager buildPluginManager; DependenciesManager dependenciesManager; private List<String> getApplicationAndLibraryParams() throws MojoFailureException { dependenciesManager = new DependenciesManager(project, workspace, getLog()); List<String> params = new ArrayList<String>(); params.add("-k"); params.add(dependenciesManager.getApp()); // if there are applications, add them if (!dependenciesManager.getDependentApps().isEmpty()) { params.addAll(dependenciesManager.getDependentApps()); } // if there are libraries, add them if (!dependenciesManager.getDependentLibs().isEmpty()) { // instead of adding the dependent libraries ( which don't make it into the appzip - fix the // indirect references problem by altering the project's .project file try { dependenciesManager.fixIndirectLibraryReferences(project.getBasedir()); } catch (Exception e) { // TODO handle exception throw new MojoFailureException("problem fixing Indirect Library References", e); } // params.add("-y"); // params.addAll(dependenciesManager.getDependentLibs()); } // if (dependenciesManager.getDependentApps().isEmpty() && dependenciesManager.getDependentLibs().isEmpty()) { // throw new MojoFailureException("unable to determine apps or libraries to packagebar/createbar"); // } return params; } protected List<String> constructPackageBarParams() throws MojoFailureException { List<String> params = new ArrayList<String>(); // bar file name - required params.add("-a"); params.add(barName.getAbsolutePath()); // workspace parameter - required createWorkspaceDirectory(); params.add("-w"); params.add(workspace.toString()); // object names - required params.addAll(getApplicationAndLibraryParams()); // always trace the packaging process params.add("-v"); params.add(packageBarTraceFile.getAbsolutePath()); return params; } protected List<String> constructCreateBarParams() throws MojoFailureException { List<String> params = new ArrayList<String>(); // bar file name - required // workspace parameter - required createWorkspaceDirectory(); params.add("-data"); params.add(workspace.toString()); params.add("-b"); params.add(barName.getAbsolutePath()); params.add("-a"); params.add(project.getName()); params.add("-cleanBuild"); params.addAll(getApplicationAndLibraryParams()); // always trace the packaging process params.add("-trace"); params.add("-v"); params.add(createBarTraceFile.getAbsolutePath()); return params; } protected List<String> constructCreateBarCompileOnlyParams() throws MojoFailureException { List<String> params = new ArrayList<String>(); params.add("-data"); params.add(workspace.toString()); params.add("-compileOnly"); return params; } /** * @param params * @throws MojoFailureException * @throws IOException */ private void executeMqsiCreateBar(List<String> params) throws MojoFailureException, IOException { DirectoriesUtil util = new DirectoriesUtil(); try { // / the better approach is simply to rename the pom.xml files as pom-xml-temp.txt // / and run maven with a "mvn [goal] -f pom.xml.txt" util.renamePomXmlFiles(workspace, getLog()); new MqsiCommandLauncher().execute( getLog(), pathToMqsiProfileScript, mqsiPrefixCommands,
MqsiCommand.mqsicreatebar,
4
cm-heclouds/JAVA-HTTP-SDK
javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/datastreams/DeleteDatastreamsApi.java
[ "public abstract class AbstractAPI<T> {\n public String key;\n public String url;\n public Method method;\n public ObjectMapper mapper = initObjectMapper();\n\n private ObjectMapper initObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n //关闭字段不识别报错\n objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n //调整默认时区为北京时间\n TimeZone timeZone = TimeZone.getTimeZone(\"GMT+8\");\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\n dateFormat.setTimeZone(timeZone);\n objectMapper.setDateFormat(dateFormat);\n objectMapper.setTimeZone(timeZone);\n return objectMapper;\n }\n}", "public class OnenetApiException extends RuntimeException {\n\t private String message = null;\n\t public String getMessage() {\n\t\treturn message;\n\t}\n\t\tpublic OnenetApiException( String message) {\n\t this.message = message;\n\t }\n}", "public class HttpDeleteMethod extends BasicHttpMethod {\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\n\tpublic HttpDeleteMethod(Method method) {\n\t\tsuper(method);\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\tpublic void setEntity(String json) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\tpublic void setEntity(Map<String, String> stringMap, Map<String, String> fileMap) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\tpublic void sethttpMethod(Method method) {\n\t\t// TODO Auto-generated method stub\n\n\t}\n\n\tpublic HttpResponse execute() throws Exception {\n\t\tHttpResponse httpResponse = null;\n\t\thttpClient = HttpClients.createDefault();\n\t\thttpResponse = httpClient.execute(httpRequestBase);\n\t\tint statusCode = httpResponse.getStatusLine().getStatusCode();\n\t\tif (statusCode != HttpStatus.SC_OK && statusCode != 221) {\n\t\t\tString response = EntityUtils.toString(httpResponse.getEntity());\n\t\t\tlogger.error(\"request failed status:{}, response::{}\",statusCode, response);\n\t\t\tthrow new OnenetApiException(\"request failed: \" + response);\n\t\t}\n\t\treturn httpResponse;\n\n\t}\n}", "public enum Method{\n POST,GET,DELETE,PUT\n}", "public class BasicResponse<T> {\n\tpublic int errno;\n\tpublic String error;\n @JsonProperty(\"data\")\n public Object dataInternal;\n public T data;\n @JsonIgnore\n public String json;\n\n\tpublic String getJson() {\n\t\treturn json;\n\t}\n\n\tpublic void setJson(String json) {\n\t\tthis.json = json;\n\t}\n\n\tpublic int getErrno() {\n return errno;\n }\n\n public void setErrno(int errno) {\n this.errno = errno;\n }\n\n public String getError() {\n return error;\n }\n\n public void setError(String error) {\n this.error = error;\n }\n\n @JsonGetter(\"data\")\n public Object getDataInternal() {\n return dataInternal;\n }\n @JsonSetter(\"data\")\n public void setDataInternal(Object dataInternal) {\n this.dataInternal = dataInternal;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n}", "public class Config {\n\tprivate final static Properties properties;\n private static org.slf4j.Logger logger = LoggerFactory.getLogger(Config.class);\n\tstatic {\n//\t\tLogger.getRootLogger().setLevel(Level.OFF);\n\t\tInputStream in = Config.class.getClassLoader().getResourceAsStream(\"config.properties\");\n\t\tproperties = new Properties();\n\t\ttry {\n\t\t\tproperties.load(in);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"init config error\", e);\n\t\t}\n\t}\n\n\t/**\n\t * 读取以逗号分割的字符串,作为字符串数组返回\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static List<String> getStringList(String conf) {\n\t\treturn Arrays.asList(StringUtils.split(properties.getProperty(conf), \",\"));\n\t}\n\n\t/**\n\t * 读取字符串\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static String getString(String conf) {\n\t\treturn properties.getProperty(conf);\n\t}\n\n\t/**\n\t * 读取整数\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static int getInt(String conf) {\n\t\tint ret = 0;\n\t\ttry {\n\t\t\tret = Integer.parseInt(getString(conf));\n\t\t} catch (NumberFormatException e) {\n\t\t\tlogger.error(\"format error\", e);\n\t\t}\n\t\treturn ret;\n\t}\n\n\t/**\n\t * 读取布尔值\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static boolean getBoolean(String conf) {\n\t\treturn Boolean.parseBoolean(getString(conf));\n\t}\n}" ]
import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import cmcc.iot.onenet.javasdk.api.AbstractAPI; import cmcc.iot.onenet.javasdk.exception.OnenetApiException; import cmcc.iot.onenet.javasdk.http.HttpDeleteMethod; import cmcc.iot.onenet.javasdk.request.RequestInfo.Method; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.utils.Config;
package cmcc.iot.onenet.javasdk.api.datastreams; public class DeleteDatastreamsApi extends AbstractAPI{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); private String devId; private HttpDeleteMethod HttpMethod; private String datastreamId; /** * @param devId * @param datastreamId * @param key */ public DeleteDatastreamsApi(String devId, String datastreamId,String key) { this.devId = devId; this.datastreamId = datastreamId; this.key=key; this.method = Method.DELETE; Map<String, Object> headmap = new HashMap<String, Object>(); HttpMethod = new HttpDeleteMethod(method); headmap.put("api-key", key); HttpMethod.setHeader(headmap); this.url = Config.getString("test.url") + "/devices/" + devId+"/datastreams/"+datastreamId; HttpMethod.setcompleteUrl(url,null); }
public BasicResponse<Void> executeApi() {
4
shiziqiu/shiziqiu-configuration
shiziqiu-configuration-console/src/main/java/com/shiziqiu/configuration/console/web/controller/GroupController.java
[ "public class ResultT<T> {\n\n\tpublic static final ResultT<String> SUCCESS = new ResultT<String>(null);\n\tpublic static final ResultT<String> FAIL = new ResultT<String>(500, null);\n\t\n\tprivate int code;\n\tprivate String msg;\n\tprivate T content;\n\t\n\tpublic ResultT(){}\n\t\n\tpublic ResultT(int code, String msg) {\n\t\tthis.code = code;\n\t\tthis.msg = msg;\n\t}\n\tpublic ResultT(T content) {\n\t\tthis.code = 200;\n\t\tthis.content = content;\n\t}\n\n\tpublic int getCode() {\n\t\treturn code;\n\t}\n\n\tpublic void setCode(int code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic String getMsg() {\n\t\treturn msg;\n\t}\n\n\tpublic void setMsg(String msg) {\n\t\tthis.msg = msg;\n\t}\n\n\tpublic T getContent() {\n\t\treturn content;\n\t}\n\n\tpublic void setContent(T content) {\n\t\tthis.content = content;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ResultT [code=\" + code + \", msg=\" + msg + \", content=\"\n\t\t\t\t+ content + \"]\";\n\t}\n\t\n}", "public class ShiZiQiuConfGroup implements Serializable{\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 112412412412412L;\n\t\n\tprivate String groupName;\n\tprivate String groupTitle;\n\t \n\tpublic ShiZiQiuConfGroup() {\n\t\tsuper();\n\t}\n\n\tpublic ShiZiQiuConfGroup(String groupName, String groupTitle) {\n\t\tsuper();\n\t\tthis.groupName = groupName;\n\t\tthis.groupTitle = groupTitle;\n\t}\n\t\n\tpublic String getGroupName() {\n\t\treturn groupName;\n\t}\n\tpublic void setGroupName(String groupName) {\n\t\tthis.groupName = groupName;\n\t}\n\tpublic String getGroupTitle() {\n\t\treturn groupTitle;\n\t}\n\tpublic void setGroupTitle(String groupTitle) {\n\t\tthis.groupTitle = groupTitle;\n\t}\n\t \n}", "public interface ShiZiQiuConfGroupService {\n\n\tpublic List<ShiZiQiuConfGroup> findAll();\n\n\tpublic int save(ShiZiQiuConfGroup group);\n\n\tpublic int update(ShiZiQiuConfGroup group);\n\n\tpublic int remove(String groupName);\n\n\tpublic ShiZiQiuConfGroup get(String groupName);\n}", "public interface ShiZiQiuConfNodeService {\n\n\tpublic Map<String,Object> pageList(int offset, int pagesize, String nodeGroup, String nodeKey);\n\n\tpublic ResultT<String> deleteByKey(String nodeGroup, String nodeKey);\n\n\tpublic ResultT<String> add(ShiZiQiuConfNode node);\n\n\tpublic ResultT<String> update(ShiZiQiuConfNode node);\n\n\tpublic int pageListCount(int offset, int pagesize, String groupName, String nodeKey);\n}", "public class StringUtils {\n\n\tpublic static boolean isNotBlank(String str) {\n\t\treturn !StringUtils.isBlank(str);\n\t}\n\n\tpublic static boolean isBlank(String str) {\n\t\tint strLen;\n\t\tif (str == null || (strLen = str.length()) == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tfor (int i = 0; i < strLen; i++) {\n\t\t\tif ((Character.isWhitespace(str.charAt(i)) == false)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic static String trim(String str) {\n\t\treturn str == null ? null : str.trim();\n\t}\n}" ]
import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.shiziqiu.configuration.console.model.ResultT; import com.shiziqiu.configuration.console.model.ShiZiQiuConfGroup; import com.shiziqiu.configuration.console.service.ShiZiQiuConfGroupService; import com.shiziqiu.configuration.console.service.ShiZiQiuConfNodeService; import com.shiziqiu.configuration.util.StringUtils;
package com.shiziqiu.configuration.console.web.controller; /** * @title : GroupController * @author : crazy * @date : 2017年9月7日 上午9:57:18 * @Fun : */ @Controller @RequestMapping("/group") public class GroupController { @Resource private ShiZiQiuConfNodeService shiZiQiuConfNodeService; @Resource private ShiZiQiuConfGroupService shiZiQiuConfGroupService; @RequestMapping public String index(Model model) { List<ShiZiQiuConfGroup> list = shiZiQiuConfGroupService.findAll(); model.addAttribute("list", list); return "group/index"; } @RequestMapping("/save") @ResponseBody public ResultT<String> save(ShiZiQiuConfGroup shiZiQiuConfGroup){
if (null == shiZiQiuConfGroup.getGroupName() || StringUtils.isBlank(shiZiQiuConfGroup.getGroupName())) {
4
52North/geoar-app
src/main/java/org/n52/geoar/ar/view/ARObject.java
[ "public interface OpenGLCallable {\r\n\tvoid onPreRender(); // unused\r\n\r\n\tvoid render(final float[] projectionMatrix, final float[] viewMatrix,\r\n\t\t\tfinal float[] parentMatrix, final float[] lightPosition);\r\n}\r", "public class GLESCamera {\r\n\r\n\tprivate static class GeometryPlane {\r\n\t\tprivate static float[] mTmp1;\r\n\t\tprivate static float[] mTmp2;\r\n\t\tfinal float[] normal = new float[3];\r\n\t\tfloat dot = 0;\r\n\r\n\t\tboolean isOutside(float[] p) {\r\n\t\t\tfloat dist = p[0] * normal[0] + p[1] * normal[1] + p[2] * normal[2]\r\n\t\t\t\t\t+ dot;\r\n\t\t\treturn dist < 0;\r\n\t\t}\r\n\r\n\t\tvoid set(float[] p1, float[] p2, float[] p3) {\r\n\t\t\tmTmp1 = Arrays.copyOf(p1, 3);\r\n\t\t\tmTmp2 = Arrays.copyOf(p2, 3);\r\n\r\n\t\t\tmTmp1[0] -= mTmp2[0];\r\n\t\t\tmTmp1[1] -= mTmp2[1];\r\n\t\t\tmTmp1[2] -= mTmp2[2];\r\n\r\n\t\t\tmTmp2[0] -= p3[0];\r\n\t\t\tmTmp2[1] -= p3[1];\r\n\t\t\tmTmp2[2] -= p3[2];\r\n\r\n\t\t\t// cross product in order to calculate the normal\r\n\t\t\tnormal[0] = mTmp1[1] * mTmp2[2] - mTmp1[2] * mTmp2[1];\r\n\t\t\tnormal[1] = mTmp1[2] * mTmp2[0] - mTmp1[0] * mTmp2[2];\r\n\t\t\tnormal[2] = mTmp1[0] * mTmp2[1] - mTmp1[1] * mTmp2[0];\r\n\r\n\t\t\t// normalizing the result\r\n\t\t\t// According to Lint faster than FloatMath\r\n\t\t\tfloat a = (float) Math.sqrt(normal[0] * normal[0] + normal[1]\r\n\t\t\t\t\t* normal[1] + normal[2] * normal[2]);\r\n\t\t\tif (a != 0 && a != 1) {\r\n\t\t\t\ta = 1 / a;\r\n\t\t\t\tnormal[0] *= a;\r\n\t\t\t\tnormal[1] *= a;\r\n\t\t\t\tnormal[2] *= a;\r\n\t\t\t}\r\n\r\n\t\t\tdot = -(p1[0] * normal[0] + p1[1] * normal[1] + p1[2] * normal[2]);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static float zNear = 1.f;\r\n\tpublic static float zFar = 2000.f; \r\n//\t\t\tSettings.SIZE_AR_INTERPOLATION\r\n//\t\t\t+ Settings.RELOAD_DIST_AR;\r\n\t// // Viewport of OpenGL Viewport\r\n\t// public static int glViewportWidth;\r\n\t// public static int glViewportHeight;\r\n\r\n\tpublic static float[] projectionMatrix = new float[16];\r\n\r\n\t// Store the view matrix. This matrix transforms world space to eye space;\r\n\t// it positions things relative to our eye.\r\n\tpublic static float[] viewMatrix = new float[16];\r\n\t// public static float[] cameraPosition = new float[] { 0.f, 0f, 0.f };\r\n\tpublic static int[] viewportMatrix = new int[4];\r\n\t\r\n\tpublic static float[] cameraPosition = new float[]{0.0f, 1.6f, 0.0f};\t// TODO XXX 1.6 is no constant!\r\n\r\n\t// public static int[] viewPortMatrix;\r\n\r\n\tprivate final static float[][] planePoints = new float[8][3];\r\n\r\n\t// TODO FIXME XXX clipSpace needs to be setted with real frustum coordinates\r\n\tprivate final static float[][] clipSpace = new float[][] {\r\n\t\t\tnew float[] { 0, 0, 0 }, new float[] { 1, 0, 0 },\r\n\t\t\tnew float[] { 1, 1, 0 }, new float[] { 0, 1, 0 },\r\n\t\t\tnew float[] { 0, 0, 1 }, new float[] { 1, 0, 1 },\r\n\t\t\tnew float[] { 1, 1, 1 }, new float[] { 0, 1, 1 }, };\r\n\r\n\tprivate final static GeometryPlane[] frustumPlanes = new GeometryPlane[6];\r\n\r\n\tstatic {\r\n\t\tfor (int i = 0; i < 8; i++) {\r\n\t\t\tplanePoints[i] = new float[3];\r\n\t\t}\r\n\t\tfor (int i = 0; i < 6; i++) {\r\n\t\t\tfrustumPlanes[i] = new GeometryPlane();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static boolean frustumCulling(float[] positionVec) {\r\n\t\tfloat z = -positionVec[2];\r\n\t\tif (z > zFar || z < zNear)\r\n\t\t\treturn false;\r\n\t\treturn true;\r\n\t\t// float h = z * 2 * Math.tan(RealityCamera.)\r\n\t}\r\n\r\n\t// public static void gluLookAt(float[] m, float eyeX, float eyeY, float\r\n\t// eyeZ,\r\n\t// float centerX, float centerY, float centerZ, float upX, float upY,\r\n\t// float upZ) {\r\n\t//\r\n\t// // See the OpenGL GLUT documentation for gluLookAt for a description\r\n\t// // of the algorithm. We implement it in a straightforward way:\r\n\t//\r\n\t// float fx = centerX - eyeX;\r\n\t// float fy = centerY - eyeY;\r\n\t// float fz = centerZ - eyeZ;\r\n\t//\r\n\t// // Normalize f\r\n\t// float rlf = 1.0f / Matrix.length(fx, fy, fz);\r\n\t// fx *= rlf;\r\n\t// fy *= rlf;\r\n\t// fz *= rlf;\r\n\t//\r\n\t// // compute s = f x up (x means \"cross product\")\r\n\t// float sx = fy * upZ - fz * upY;\r\n\t// float sy = fz * upX - fx * upZ;\r\n\t// float sz = fx * upY - fy * upX;\r\n\t//\r\n\t// // and normalize s\r\n\t// float rls = 1.0f / Matrix.length(sx, sy, sz);\r\n\t// sx *= rls;\r\n\t// sy *= rls;\r\n\t// sz *= rls;\r\n\t//\r\n\t// // compute u = s x f\r\n\t// float ux = sy * fz - sz * fy;\r\n\t// float uy = sz * fx - sx * fz;\r\n\t// float uz = sx * fy - sy * fx;\r\n\t//\r\n\t// m[0] = sx;\r\n\t// m[1] = ux;\r\n\t// m[2] = -fx;\r\n\t// m[3] = 0.0f;\r\n\t//\r\n\t// m[4] = sy;\r\n\t// m[5] = uy;\r\n\t// m[6] = -fy;\r\n\t// m[7] = 0.0f;\r\n\t//\r\n\t// m[8] = sz;\r\n\t// m[9] = uz;\r\n\t// m[10] = -fz;\r\n\t// m[11] = 0.0f;\r\n\t//\r\n\t// m[12] = 0.0f;\r\n\t// m[13] = 0.0f;\r\n\t// m[14] = 0.0f;\r\n\t// m[15] = 1.0f;\r\n\t//\r\n\t// // Matrix.m\r\n\t// // gl.glMultMatrixf(m, 0);\r\n\t// // gl.glTranslatef(-eyeX, -eyeY, -eyeZ);\r\n\t// }\r\n\r\n\tpublic static boolean pointInFrustum(float[] p) {\r\n\t\tfor (int i = 0; i < frustumPlanes.length; i++) {\r\n\t\t\tif (!frustumPlanes[i].isOutside(p))\r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\tpublic static void resetProjectionMatrix() {\r\n\t\tMatrix.setIdentityM(projectionMatrix, 0);\r\n\t\tperspectiveMatrix(projectionMatrix, 0, RealityCamera.fovY,\r\n\t\t\t\tRealityCamera.aspect, zNear, zFar);\r\n\t}\r\n\r\n\tpublic static void resetViewMatrix() {\r\n\t\t// calculate the viewMatrix for OpenGL rendering\r\n\t\tMatrix.setIdentityM(viewMatrix, 0);\r\n\t}\r\n\r\n\tpublic static void resetViewportMatrix(int width, int height) {\r\n\t\tviewportMatrix = new int[] { 0, 0, width, height };\r\n\t}\r\n\r\n\tpublic static void updateFrustum(float[] projectionMatrix,\r\n\t\t\tfloat[] viewMatrix) {\r\n\t\tfloat[] projectionViewMatrix = new float[16];\r\n\t\tfloat[] invertPVMatrix = new float[16];\r\n\t\tMatrix.multiplyMM(projectionViewMatrix, 0, projectionMatrix, 0,\r\n\t\t\t\tviewMatrix, 0);\r\n\t\tMatrix.invertM(invertPVMatrix, 0, projectionViewMatrix, 0);\r\n\r\n\t\tfor (int i = 0; i < 8; i++) {\r\n\t\t\tfloat[] point = Arrays.copyOf(clipSpace[i], 3);\r\n\r\n\t\t\tfloat rw = point[0] * invertPVMatrix[3] + point[1]\r\n\t\t\t\t\t* invertPVMatrix[7] + point[2] * invertPVMatrix[11]\r\n\t\t\t\t\t+ invertPVMatrix[15];\r\n\r\n\t\t\tplanePoints[i] = clipSpace[i];\r\n\r\n\t\t\tfloat[] newPlanePoints = new float[3];\r\n\t\t\tnewPlanePoints[0] = (point[0] * invertPVMatrix[0] + point[1]\r\n\t\t\t\t\t* invertPVMatrix[4] + point[2] * invertPVMatrix[8] + invertPVMatrix[12])\r\n\t\t\t\t\t/ rw;\r\n\t\t\tnewPlanePoints[1] = (point[0] * invertPVMatrix[1] + point[1]\r\n\t\t\t\t\t* invertPVMatrix[5] + point[2] * invertPVMatrix[9] + invertPVMatrix[13])\r\n\t\t\t\t\t/ rw;\r\n\t\t\tnewPlanePoints[2] = (point[0] * invertPVMatrix[2] + point[1]\r\n\t\t\t\t\t* invertPVMatrix[6] + point[2] * invertPVMatrix[10] + invertPVMatrix[14])\r\n\t\t\t\t\t/ rw;\r\n\t\t\tplanePoints[i] = newPlanePoints;\r\n\t\t}\r\n\r\n\t\tfrustumPlanes[0].set(planePoints[1], planePoints[0], planePoints[2]);\r\n\t\tfrustumPlanes[1].set(planePoints[4], planePoints[5], planePoints[7]);\r\n\t\tfrustumPlanes[2].set(planePoints[0], planePoints[4], planePoints[3]);\r\n\t\tfrustumPlanes[3].set(planePoints[5], planePoints[1], planePoints[6]);\r\n\t\tfrustumPlanes[4].set(planePoints[2], planePoints[3], planePoints[6]);\r\n\t\tfrustumPlanes[5].set(planePoints[4], planePoints[0], planePoints[1]);\r\n\t}\r\n\r\n\t/**\r\n\t * Define a projection matrix in terms of a field of view angle, an aspect\r\n\t * ratio, and z clip planes SOURCE: Android 4.0.3 API-LEVEL 15\r\n\t * \r\n\t * @param m\r\n\t * the float array that holds the perspective matrix\r\n\t * @param offset\r\n\t * the offset into float array m where the perspective matrix\r\n\t * data is written\r\n\t * @param fovy\r\n\t * field of view in y direction, in degrees\r\n\t * @param aspect\r\n\t * width to height aspect ratio of the viewport\r\n\t * @param zNear\r\n\t * @param zFar\r\n\t */\r\n\tprivate static void perspectiveMatrix(float[] m, int offset, float fovy,\r\n\t\t\tfloat aspect, float zNear, float zFar) {\r\n\t\tfloat f = 1.0f / (float) Math.tan(fovy * (Math.PI / 360.0));\r\n\t\tfloat rangeReciprocal = 1.0f / (zNear - zFar);\r\n\r\n\t\tm[offset + 0] = f / aspect;\r\n\t\tm[offset + 1] = 0.0f;\r\n\t\tm[offset + 2] = 0.0f;\r\n\t\tm[offset + 3] = 0.0f;\r\n\r\n\t\tm[offset + 4] = 0.0f;\r\n\t\tm[offset + 5] = f;\r\n\t\tm[offset + 6] = 0.0f;\r\n\t\tm[offset + 7] = 0.0f;\r\n\r\n\t\tm[offset + 8] = 0.0f;\r\n\t\tm[offset + 9] = 0.0f;\r\n\t\tm[offset + 10] = (zFar + zNear) * rangeReciprocal;\r\n\t\tm[offset + 11] = -1.0f;\r\n\r\n\t\tm[offset + 12] = 0.0f;\r\n\t\tm[offset + 13] = 0.0f;\r\n\t\tm[offset + 14] = 2.0f * zFar * zNear * rangeReciprocal;\r\n\t\tm[offset + 15] = 0.0f;\r\n\r\n\t}\r\n\r\n\t/** private constructor -> just a static class */\r\n\tprivate GLESCamera() {\r\n\t}\r\n\r\n}", "public class DataSourceInstanceHolder implements Parcelable {\r\n\r\n\tpublic interface DataSourceSettingsChangedListener {\r\n\t\tvoid onDataSourceSettingsChanged();\r\n\t}\r\n\r\n\tprivate static int nextId = 0;\r\n\tprivate static final int CLEAR_CACHE = 1;\r\n\tprivate static final int CLEAR_CACHE_AFTER_DEACTIVATION_DELAY = 10000;\r\n\tprivate static final Logger LOG = LoggerFactory\r\n\t\t\t.getLogger(DataSourceInstanceHolder.class);\r\n\r\n\tprivate Handler dataSourceHandler = new Handler(new Handler.Callback() {\r\n\t\t@Override\r\n\t\tpublic boolean handleMessage(Message msg) {\r\n\t\t\tif (msg.what == CLEAR_CACHE) {\r\n\t\t\t\t// Delayed clearing of cache after datasource has been\r\n\t\t\t\t// deactivated\r\n\t\t\t\tdataCache.clearCache();\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t});\r\n\tprivate DataSource<? super Filter> dataSource;\r\n\tprivate boolean injected = false;\r\n\tprivate DataSourceHolder parentHolder;\r\n\tprivate final int id = nextId++;\r\n\tprivate DataCache dataCache;\r\n\tprivate Filter currentFilter;\r\n\tprivate Boolean hasSettings = null;\r\n\t@CheckManager\r\n\tprivate CheckList<DataSourceInstanceHolder>.Checker mChecker;\r\n\tprivate Exception lastError;\r\n\tprivate Set<DataSourceSettingsChangedListener> mSettingsChangedListeners = new HashSet<DataSourceInstanceHolder.DataSourceSettingsChangedListener>(\r\n\t\t\t0);\r\n\r\n\tpublic DataSourceInstanceHolder(DataSourceHolder parentHolder,\r\n\t\t\tDataSource<? super Filter> dataSource) {\r\n\t\tthis.parentHolder = parentHolder;\r\n\t\tthis.dataSource = dataSource;\r\n\t\ttry {\r\n\t\t\tthis.currentFilter = parentHolder.getFilterClass().newInstance();\r\n\t\t} catch (InstantiationException e) {\r\n\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\"Referenced filter has no appropriate constructor\");\r\n\t\t} catch (IllegalAccessException e) {\r\n\t\t\tthrow new RuntimeException(\r\n\t\t\t\t\t\"Referenced filter has no appropriate constructor\");\r\n\t\t}\r\n\r\n\t\tdataCache = new DataCache(this);\r\n\t}\r\n\r\n\t@CheckedChangedListener\r\n\tpublic void checkedChanged(boolean state) {\r\n\t\tif (state) {\r\n\t\t\tactivate();\r\n\t\t} else {\r\n\t\t\tdeactivate();\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Prevents datasource from getting unloaded. Should be called when\r\n\t * datasource is added to map/ar.\r\n\t */\r\n\tpublic void activate() {\r\n\t\tLOG.info(\"Activating data source instance \" + getName());\r\n\r\n\t\t// prevents clearing of cache by removing messages\r\n\t\tdataSourceHandler.removeMessages(CLEAR_CACHE);\r\n\t\tif (!injected) {\r\n\t\t\tparentHolder.perfomInjection(dataSource);\r\n\t\t\tinjected = true;\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Queues unloading of datasource and cached data\r\n\t */\r\n\tpublic void deactivate() {\r\n\t\t// Clears the cache 30s after calling this method\r\n\t\tLOG.info(\"Deactivating data source \" + getName());\r\n\t\tdataSourceHandler.sendMessageDelayed(\r\n\t\t\t\tdataSourceHandler.obtainMessage(CLEAR_CACHE),\r\n\t\t\t\tCLEAR_CACHE_AFTER_DEACTIVATION_DELAY);\r\n\t}\r\n\r\n\tpublic DataCache getDataCache() {\r\n\t\treturn dataCache;\r\n\t}\r\n\r\n\tpublic void createSettingsDialog(Context context) {\r\n\t\tSettingsResultListener resultListener = new SettingsResultListener() {\r\n\t\t\t@Override\r\n\t\t\tvoid onSettingsResult(int resultCode) {\r\n\t\t\t\tif (resultCode == Activity.RESULT_OK) {\r\n\t\t\t\t\tnotifySettingsChanged();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\tIntent intent = new Intent(context,\r\n\t\t\t\tDataSourceInstanceSettingsDialogActivity.class);\r\n\t\tintent.putExtra(\"dataSourceInstance\", this);\r\n\t\tintent.putExtra(\"resultListener\", resultListener); // unsure whether\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Intent uses weak\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// references too\r\n\t\tcontext.startActivity(intent);\r\n\t}\r\n\r\n\tpublic Filter getCurrentFilter() {\r\n\t\treturn currentFilter;\r\n\t}\r\n\r\n\tpublic DataSourceHolder getParent() {\r\n\t\treturn parentHolder;\r\n\t}\r\n\r\n\tpublic void addOnSettingsChangedListener(\r\n\t\t\tDataSourceSettingsChangedListener listener) {\r\n\t\tmSettingsChangedListeners.add(listener);\r\n\t}\r\n\r\n\tpublic void removeOnSettingsChangedListener(\r\n\t\t\tDataSourceSettingsChangedListener listener) {\r\n\t\tmSettingsChangedListeners.remove(listener);\r\n\t}\r\n\r\n\t/**\r\n\t * It does not only notify listeners, but also clears the current cache.\r\n\t * TODO\r\n\t */\r\n\tvoid notifySettingsChanged() {\r\n\t\tdataCache.setFilter(currentFilter);\r\n\t\tfor (DataSourceSettingsChangedListener listener : mSettingsChangedListeners) {\r\n\t\t\tlistener.onDataSourceSettingsChanged();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic String getName() {\r\n\t\tif (parentHolder.getNameCallbackMethod() != null) {\r\n\t\t\t// try to use name callback\r\n\t\t\ttry {\r\n\t\t\t\treturn (String) parentHolder.getNameCallbackMethod().invoke(\r\n\t\t\t\t\t\tdataSource);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tLOG.warn(\"Data Source \" + parentHolder.getName()\r\n\t\t\t\t\t\t+ \" NameCallback fails\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (parentHolder.instanceable()) {\r\n\t\t\treturn parentHolder.getName() + \" \" + id;\r\n\t\t} else {\r\n\t\t\treturn parentHolder.getName();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic DataSource<? super Filter> getDataSource() {\r\n\t\treturn dataSource;\r\n\t}\r\n\r\n\tpublic boolean hasSettings() {\r\n\t\tif (hasSettings == null) {\r\n\t\t\thasSettings = SettingsHelper.hasSettings(getCurrentFilter())\r\n\t\t\t\t\t|| SettingsHelper.hasSettings(getDataSource());\r\n\t\t}\r\n\r\n\t\treturn hasSettings;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int describeContents() {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void writeToParcel(Parcel dest, int flags) {\r\n\t\t// Parcel based on unique DataSourceHolder id\r\n\t\tdest.writeParcelable(parentHolder, 0);\r\n\t\tdest.writeInt(id);\r\n\t}\r\n\r\n\tpublic static final Parcelable.Creator<DataSourceInstanceHolder> CREATOR = new Parcelable.Creator<DataSourceInstanceHolder>() {\r\n\t\tpublic DataSourceInstanceHolder createFromParcel(Parcel in) {\r\n\t\t\tDataSourceHolder dataSource = in\r\n\t\t\t\t\t.readParcelable(DataSourceHolder.class.getClassLoader());\r\n\t\t\tint id = in.readInt();\r\n\t\t\t// Find DataSourceInstance with provided id\r\n\t\t\tfor (DataSourceInstanceHolder instance : dataSource.getInstances()) {\r\n\t\t\t\tif (instance.id == id) {\r\n\t\t\t\t\treturn instance;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tpublic DataSourceInstanceHolder[] newArray(int size) {\r\n\t\t\treturn new DataSourceInstanceHolder[size];\r\n\t\t}\r\n\t};\r\n\r\n\tpublic boolean isChecked() {\r\n\t\treturn mChecker.isChecked();\r\n\t}\r\n\r\n\tpublic void setChecked(boolean state) {\r\n\t\tmChecker.setChecked(state);\r\n\t}\r\n\r\n\tpublic void saveState(ObjectOutputStream objectOutputStream)\r\n\t\t\tthrows IOException {\r\n\r\n\t\t// Store filter, serializable\r\n\t\tobjectOutputStream.writeObject(currentFilter);\r\n\r\n\t\t// Store data source instance settings using settings framework\r\n\t\tSettingsHelper.storeSettings(objectOutputStream, this.dataSource);\r\n\r\n\t\tobjectOutputStream.writeBoolean(isChecked());\r\n\t}\r\n\r\n\tpublic void restoreState(ObjectInputStream objectInputStream)\r\n\t\t\tthrows IOException {\r\n\t\ttry {\r\n\t\t\t// restore filter, serializable\r\n\t\t\tcurrentFilter = (Filter) objectInputStream.readObject();\r\n\t\t\tdataCache.setFilter(currentFilter);\r\n\t\t} catch (ClassNotFoundException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\r\n\t\t// restore data source instance settings, settings framework\r\n\t\tSettingsHelper.restoreSettings(objectInputStream, this.dataSource);\r\n\r\n\t\tsetChecked(objectInputStream.readBoolean());\r\n\t}\r\n\r\n\tpublic void reportError(Exception e) {\r\n\t\tlastError = e;\r\n\t}\r\n\r\n\tpublic void clearError() {\r\n\t\tlastError = null;\r\n\t}\r\n\r\n\tpublic String getErrorString() {\r\n\t\tif (lastError == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tif (lastError instanceof SocketException) {\r\n\t\t\treturn GeoARApplication.applicationContext\r\n\t\t\t\t\t.getString(R.string.connection_error);\r\n\t\t} else if (lastError instanceof PluginException) {\r\n\t\t\treturn ((PluginException) lastError).getTitle();\r\n\t\t}\r\n\r\n\t\treturn GeoARApplication.applicationContext\r\n\t\t\t\t.getString(R.string.unknown_error);\r\n\t}\r\n\r\n\tpublic boolean hasErrorMessage() {\r\n\t\tif (lastError == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn lastError instanceof PluginException;\r\n\t}\r\n\r\n\tpublic String getErrorMessage() {\r\n\t\tif (lastError == null || !(lastError instanceof PluginException)) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\treturn lastError.toString();\r\n\t}\r\n}\r", "public class LocationHandler implements Serializable {\r\n\tprivate static final long serialVersionUID = 6337877169906901138L;\r\n\tprivate static final int DISABLE_LOCATION_UPDATES_MESSAGE = 1;\r\n\tprivate static final long DISABLE_LOCATION_UPDATES_DELAY = 12000;\r\n\tprivate static final Logger LOG = LoggerFactory\r\n\t\t\t.getLogger(LocationHandler.class);\r\n\r\n\tpublic interface OnLocationUpdateListener {\r\n\t\tvoid onLocationChanged(Location location);\r\n\t}\r\n\r\n\tprivate static LocationManager locationManager;\r\n\tprivate static final Object gpsStatusInfo = new Object();\r\n\tprivate static final Object gpsProviderInfo = new Object();\r\n\tprivate static List<OnLocationUpdateListener> listeners = new ArrayList<OnLocationUpdateListener>();\r\n\r\n\tprivate static boolean manualLocationMode;\r\n\tprivate static Location manualLocation;\r\n\r\n\tprivate static Handler disableUpdateHandler = new Handler() {\r\n\t\t@Override\r\n\t\tpublic void handleMessage(Message msg) {\r\n\t\t\tif (msg.what == DISABLE_LOCATION_UPDATES_MESSAGE) {\r\n\t\t\t\tonPause();\r\n\t\t\t} else {\r\n\t\t\t\tsuper.handleMessage(msg);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\tstatic {\r\n\t\tlocationManager = (LocationManager) GeoARApplication.applicationContext\r\n\t\t\t\t.getSystemService(Context.LOCATION_SERVICE);\r\n\t}\r\n\r\n\tprivate static LocationListener locationListener = new LocationListener() {\r\n\r\n\t\tpublic void onProviderDisabled(String provider) {\r\n\t\t\tInfoView.setStatus(R.string.gps_nicht_aktiviert, -1,\r\n\t\t\t\t\tgpsProviderInfo);\r\n\t\t}\r\n\r\n\t\tpublic void onProviderEnabled(String provider) {\r\n\t\t\tInfoView.setStatus(R.string.gps_aktiviert, 2000, gpsProviderInfo);\r\n\t\t}\r\n\r\n\t\tpublic void onStatusChanged(String provider, int status, Bundle extras) {\r\n\t\t\tif (status != LocationProvider.AVAILABLE) {\r\n\t\t\t\tInfoView.setStatus(R.string.warte_auf_gps_verf_gbarkeit, 5000,\r\n\t\t\t\t\t\tgpsStatusInfo);\r\n\t\t\t} else {\r\n\t\t\t\tInfoView.clearStatus(gpsStatusInfo);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void onLocationChanged(Location location) {\r\n\t\t\tfor (OnLocationUpdateListener listener : listeners) {\r\n\t\t\t\tlistener.onLocationChanged(location);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\t/**\r\n\t * Override with a user generated location fix\r\n\t * \r\n\t * @param location\r\n\t */\r\n\tpublic static void setManualLocation(Location location) {\r\n\t\tmanualLocationMode = true;\r\n\t\tonPause();\r\n\t\tmanualLocation = location;\r\n\t\tlocationListener.onLocationChanged(manualLocation);\r\n\t\tInfoView.setStatus(R.string.manual_position, -1, manualLocation);\r\n\t}\r\n\r\n\t/**\r\n\t * Override with a user generated location fix\r\n\t * \r\n\t * @param geoPoint\r\n\t */\r\n\tpublic static void setManualLocation(GeoLocation geoPoint) {\r\n\t\tmanualLocationMode = true;\r\n\t\tonPause();\r\n\t\tif (manualLocation == null) {\r\n\t\t\tmanualLocation = new Location(\"manual\");\r\n\t\t}\r\n\t\tmanualLocation.setLatitude(geoPoint.getLatitudeE6() / 1E6f);\r\n\t\tmanualLocation.setLongitude(geoPoint.getLongitudeE6() / 1E6f);\r\n\t\tlocationListener.onLocationChanged(manualLocation);\r\n\r\n\t\tInfoView.setStatus(R.string.manual_position, -1, manualLocation);\r\n\t}\r\n\r\n\t/**\r\n\t * Reregister location updates for real location provider\r\n\t */\r\n\tpublic static void disableManualLocation() {\r\n\t\tInfoView.clearStatus(manualLocation);\r\n\t\tmanualLocationMode = false;\r\n\t\tonResume();\r\n\t}\r\n\r\n\t/**\r\n\t * Performs processes needed to enable location updates\r\n\t */\r\n\tpublic static void onResume() {\r\n\t\tif (!listeners.isEmpty()) {\r\n\t\t\tif (!locationManager\r\n\t\t\t\t\t.isProviderEnabled(LocationManager.GPS_PROVIDER)) {\r\n\t\t\t\tInfoView.setStatus(R.string.gps_nicht_aktiviert, -1,\r\n\t\t\t\t\t\tgpsProviderInfo);\r\n\t\t\t}\r\n\t\t\tlocationManager.requestLocationUpdates(\r\n\t\t\t\t\tLocationManager.GPS_PROVIDER, 5000, 0, locationListener);\r\n\t\t\tLOG.debug(\"Requesting Location Updates\");\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Should be called if activity gets paused. Removes location updates\r\n\t */\r\n\tpublic static void onPause() {\r\n\t\tlocationManager.removeUpdates(locationListener);\r\n\t\tInfoView.clearStatus(gpsProviderInfo);\r\n\t\tLOG.debug(\"Removed Location Updates\");\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the last known location. Takes user generated locations into\r\n\t * account. Returns location fix from network provider if no GPS available\r\n\t * \r\n\t * @return\r\n\t */\r\n\tpublic static Location getLastKnownLocation() {\r\n\t\tif (manualLocationMode) {\r\n\t\t\treturn manualLocation;\r\n\t\t} else if (locationManager\r\n\t\t\t\t.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null) {\r\n\t\t\treturn locationManager\r\n\t\t\t\t\t.getLastKnownLocation(LocationManager.GPS_PROVIDER);\r\n\t\t} else {\r\n\t\t\treturn locationManager\r\n\t\t\t\t\t.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Register listener for location updates. Gets immediately called with the\r\n\t * last known location, if available\r\n\t * \r\n\t * @param listener\r\n\t */\r\n\tpublic static void addLocationUpdateListener(\r\n\t\t\tOnLocationUpdateListener listener) {\r\n\t\tboolean shouldResume = listeners.isEmpty();\r\n\t\tif (!listeners.contains(listener)) {\r\n\t\t\tlisteners.add(listener);\r\n\t\t\tif (getLastKnownLocation() != null) {\r\n\t\t\t\tlistener.onLocationChanged(getLastKnownLocation());\r\n\t\t\t}\r\n\t\t\tdisableUpdateHandler\r\n\t\t\t\t\t.removeMessages(DISABLE_LOCATION_UPDATES_MESSAGE);\r\n\t\t}\r\n\r\n\t\tif (shouldResume) {\r\n\t\t\tonResume();\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Removes location update listener\r\n\t * \r\n\t * @param listener\r\n\t */\r\n\tpublic static void removeLocationUpdateListener(\r\n\t\t\tOnLocationUpdateListener listener) {\r\n\t\tlisteners.remove(listener);\r\n\t\tif (listeners.isEmpty()) {\r\n\t\t\tdisableUpdateHandler.sendMessageDelayed(disableUpdateHandler\r\n\t\t\t\t\t.obtainMessage(DISABLE_LOCATION_UPDATES_MESSAGE),\r\n\t\t\t\t\tDISABLE_LOCATION_UPDATES_DELAY);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static void onSaveInstanceState(Bundle outState) {\r\n\t\tif (manualLocationMode) {\r\n\t\t\toutState.putParcelable(\"manualLocation\", manualLocation);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static void onRestoreInstanceState(Bundle savedInstanceState) {\r\n\t\tif (savedInstanceState.get(\"manualLocation\") != null) {\r\n\t\t\tsetManualLocation((Location) savedInstanceState\r\n\t\t\t\t\t.getParcelable(\"manualLocation\"));\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Registers location updates to actively receive a new single location fix.\r\n\t * The provided listener will be called once or never, depending on the\r\n\t * specified timeout.\r\n\t * \r\n\t * @param listener\r\n\t * @param timeoutMillis\r\n\t * Timeout in milliseconds\r\n\t */\r\n\tpublic static void getSingleLocation(\r\n\t\t\tfinal OnLocationUpdateListener listener, int timeoutMillis) {\r\n\r\n\t\t/**\r\n\t\t * Location update listener removing itself after first fix and\r\n\t\t * canceling scheduled runnable\r\n\t\t */\r\n\t\tclass SingleLocationUpdateListener implements OnLocationUpdateListener {\r\n\r\n\t\t\tRunnable cancelSingleUpdateRunnable;\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void onLocationChanged(Location location) {\r\n\t\t\t\t// Clear updates\r\n\t\t\t\tremoveLocationUpdateListener(this);\r\n\t\t\t\tdisableUpdateHandler\r\n\t\t\t\t\t\t.removeCallbacks(this.cancelSingleUpdateRunnable);\r\n\r\n\t\t\t\t// Call actual listener\r\n\t\t\t\tlistener.onLocationChanged(location);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfinal SingleLocationUpdateListener singleUpdateListener = new SingleLocationUpdateListener();\r\n\r\n\t\t// Runnable to be called delayed by timeoutMillis to cancel location\r\n\t\t// update\r\n\t\tfinal Runnable cancelSingleUpdateRunnable = new Runnable() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\tremoveLocationUpdateListener(singleUpdateListener);\r\n\t\t\t}\r\n\t\t};\r\n\t\tsingleUpdateListener.cancelSingleUpdateRunnable = cancelSingleUpdateRunnable;\r\n\r\n\t\t// init updates\r\n\t\taddLocationUpdateListener(singleUpdateListener);\r\n\t\tdisableUpdateHandler.postDelayed(cancelSingleUpdateRunnable,\r\n\t\t\t\ttimeoutMillis);\r\n\t}\r\n}\r", "public abstract class RenderFeature2 extends Spatial implements\r\n\t\tDataSourceVisualizationGL, OpenGLCallable, OnInitializeInGLThread {\r\n\r\n\r\n\t/** Static constants */\r\n\tprotected static final int SIZE_OF_POSITION = 3;\r\n\tprotected static final int SIZE_OF_NORMAL = 3;\r\n\tprotected static final int SIZE_OF_COLOR = 4;\r\n\tprotected static final int SIZE_OF_TEXCOORD = 2;\r\n\t\r\n\tprotected static final int SIZE_OF_FLOAT = 4;\r\n\tprotected static final int SIZE_OF_INT = 4;\r\n\tprotected static final int SIZE_OF_SHORT = 2;\r\n\r\n\t/**\r\n\t * \r\n\t * @author Arne de Wall\r\n\t * \r\n\t */\r\n\tprivate abstract class FeatureGeometry {\r\n\r\n\t\tprotected int verticesCount;\r\n\t\tprotected boolean hasNormals;\r\n\t\tprotected boolean hasColors;\r\n\t\tprotected boolean hasTextureCoords;\r\n\r\n\t\tabstract void render();\r\n\t}\r\n\r\n\t/**\r\n\t * \r\n\t * @author Arne de Wall\r\n\t * \r\n\t */\r\n\t@Deprecated\r\n\tprivate final class FeatureGeometryVBOandIBO extends FeatureGeometry {\r\n\r\n\t\tprotected class BufferDetails {\r\n\t\t\tpublic final Buffer buffer;\r\n\t\t\tpublic final short bufferType;\r\n\t\t\tpublic final int bufferHandle;\r\n\t\t\tpublic final int byteSize;\r\n\t\t\tpublic final int target;\r\n\r\n\t\t\tpublic BufferDetails(final float[] data, final int bufferHandle,\r\n\t\t\t\t\tfinal int target) {\r\n\t\t\t\tfinal FloatBuffer floatBuffer = ByteBuffer\r\n\t\t\t\t\t\t.allocateDirect(data.length * SIZE_OF_FLOAT)\r\n\t\t\t\t\t\t.order(ByteOrder.nativeOrder()).asFloatBuffer();\r\n\t\t\t\tfloatBuffer.put(data).compact().position(0);\r\n\t\t\t\tthis.buffer = floatBuffer;\r\n\t\t\t\tthis.bufferType = FLOAT_BUFFER;\r\n\t\t\t\tthis.byteSize = SIZE_OF_FLOAT;\r\n\t\t\t\tthis.target = target;\r\n\t\t\t\tthis.bufferHandle = bufferHandle;\r\n\t\t\t}\r\n\r\n\t\t\t@SuppressWarnings(\"unused\")\r\n\t\t\tpublic BufferDetails(final int[] data, final int bufferHandle,\r\n\t\t\t\t\tfinal int target) {\r\n\t\t\t\tfinal IntBuffer integerBuffer = ByteBuffer\r\n\t\t\t\t\t\t.allocateDirect(data.length * SIZE_OF_INT)\r\n\t\t\t\t\t\t.order(ByteOrder.nativeOrder()).asIntBuffer();\r\n\t\t\t\tintegerBuffer.put(data).compact().position(0);\r\n\t\t\t\tthis.buffer = integerBuffer;\r\n\t\t\t\tthis.bufferType = INT_BUFFER;\r\n\t\t\t\tthis.byteSize = SIZE_OF_INT;\r\n\t\t\t\tthis.target = target;\r\n\t\t\t\tthis.bufferHandle = bufferHandle;\r\n\t\t\t}\r\n\r\n\t\t\tpublic BufferDetails(final short[] data, final int bufferHandle,\r\n\t\t\t\t\tfinal int target) {\r\n\t\t\t\tfinal ShortBuffer shortBuffer = ByteBuffer\r\n\t\t\t\t\t\t.allocateDirect(data.length * SIZE_OF_SHORT)\r\n\t\t\t\t\t\t.order(ByteOrder.nativeOrder()).asShortBuffer();\r\n\t\t\t\tshortBuffer.put(data).compact().position(0);\r\n\t\t\t\tthis.buffer = shortBuffer;\r\n\t\t\t\tthis.bufferType = SHORT_BUFFER;\r\n\t\t\t\tthis.byteSize = SIZE_OF_SHORT;\r\n\t\t\t\tthis.target = target;\r\n\t\t\t\tthis.bufferHandle = bufferHandle;\r\n\t\t\t}\r\n\r\n\t\t\tvoid bindBuffer() {\r\n\t\t\t\tGLES20.glBindBuffer(target, bufferHandle);\r\n\t\t\t\tGLES20.glBufferData(target, buffer.capacity() * byteSize,\r\n\t\t\t\t\t\tbuffer, GLES20.GL_STATIC_DRAW);\r\n\t\t\t\tGLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tstatic final short FLOAT_BUFFER = 100;\r\n\t\tstatic final short INT_BUFFER = 101;\r\n\t\tstatic final short SHORT_BUFFER = 102;\r\n\r\n\t\tprotected BufferDetails verticesDetails;\r\n\t\tprotected BufferDetails colorsDetails;\r\n\t\tprotected BufferDetails normalsDetails;\r\n\t\tprotected BufferDetails textureDetails;\r\n\t\tprotected BufferDetails indicesDetails;\r\n\r\n\t\tprotected FeatureGeometryVBOandIBO(final float[] vertices,\r\n\t\t\t\tfinal float[] colors, final float[] normals,\r\n\t\t\t\tfinal float[] textureCoords, final short[] indices) {\r\n\t\t\tif (vertices.length % 3 != 0)\r\n\t\t\t\tthrow new IllegalArgumentException(\r\n\t\t\t\t\t\t\"[RENDERFEATURE] vertices-array size must be a multiple of three\");\r\n\r\n\t\t\tthis.hasColors = (colors != null && renderer.supportsColors);\r\n\t\t\tthis.hasNormals = (normals != null && renderer.supportsNormals);\r\n\t\t\tthis.hasTextureCoords = (textureCoords != null && renderer.supportsTextures);\r\n\r\n\t\t\tthis.verticesCount = vertices.length / SIZE_OF_POSITION;\r\n\t\t\tinitBuffers(vertices, colors, normals, textureCoords, indices);\r\n\t\t}\r\n\r\n\t\tprivate void initBuffers(final float[] vertices, final float[] colors,\r\n\t\t\t\tfinal float[] normals, final float[] textureCoords,\r\n\t\t\t\tfinal short[] indices) {\r\n\r\n\t\t\tfinal int bufferCount = 1 + (hasColors ? 1 : 0)\r\n\t\t\t\t\t+ (hasNormals ? 1 : 0) + (hasTextureCoords ? 1 : 0) + 1;\r\n\r\n\t\t\t/** generate buffers on OpenGL */\r\n\t\t\tfinal int bufferObjects[] = new int[bufferCount];\r\n\t\t\tGLES20.glGenBuffers(bufferCount, bufferObjects, 0);\r\n\t\t\tfor (int i = 0; i < bufferCount; i++) {\r\n\t\t\t\tif (bufferObjects[i] < 1)\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tthrow new Exception(\r\n\t\t\t\t\t\t\t\t\"[RENDERFEATURE] initBuffers() -> (Buffer < 1) No Buffer created! \");\r\n\t\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tint nextBuffer = 0;\r\n\r\n\t\t\t/** generate and bind vertices FloatBuffer */\r\n\t\t\tverticesDetails = new BufferDetails(vertices,\r\n\t\t\t\t\tbufferObjects[nextBuffer++], GLES20.GL_ARRAY_BUFFER);\r\n\t\t\tverticesDetails.bindBuffer();\r\n\r\n\t\t\tif (hasColors) {\r\n\t\t\t\t/** generate and bind colors FloatBuffer */\r\n\t\t\t\tcolorsDetails = new BufferDetails(colors,\r\n\t\t\t\t\t\tbufferObjects[nextBuffer++], GLES20.GL_ARRAY_BUFFER);\r\n\t\t\t\tcolorsDetails.bindBuffer();\r\n\t\t\t}\r\n\r\n\t\t\tif (hasNormals) {\r\n\t\t\t\t/** generate and bind normals FloatBuffer */\r\n\t\t\t\tnormalsDetails = new BufferDetails(normals,\r\n\t\t\t\t\t\tbufferObjects[nextBuffer++], GLES20.GL_ARRAY_BUFFER);\r\n\t\t\t\tnormalsDetails.bindBuffer();\r\n\t\t\t}\r\n\r\n\t\t\tif (hasTextureCoords) {\r\n\t\t\t\t/** generate and bind texture coordinates FloatBuffer */\r\n\t\t\t\ttextureDetails = new BufferDetails(textureCoords,\r\n\t\t\t\t\t\tbufferObjects[nextBuffer++], GLES20.GL_ARRAY_BUFFER);\r\n\t\t\t\ttextureDetails.bindBuffer();\r\n\t\t\t}\r\n\r\n\t\t\tindicesDetails = new BufferDetails(indices,\r\n\t\t\t\t\tbufferObjects[nextBuffer++], GLES20.GL_ARRAY_BUFFER);\r\n\t\t\tindicesDetails.bindBuffer();\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tvoid render() {\r\n\t\t\t/** bind the named vertices buffer object */\r\n\t\t\trenderer.setVertices(verticesDetails.bufferHandle);\r\n\t\t\tif (hasColors) {\r\n\t\t\t\t/** bind the named color buffer object */\r\n\t\t\t\trenderer.setColors(colorsDetails.bufferHandle);\r\n\t\t\t}\r\n\t\t\tif (hasNormals) {\r\n\t\t\t\t/** bind the named normal buffer object */\r\n\t\t\t\trenderer.setNormals(normalsDetails.bufferHandle);\r\n\t\t\t}\r\n\t\t\tif (hasTextureCoords) {\r\n\t\t\t\t// FIXME NOT IMPLEMENTED YET !\r\n\t\t\t\t// renderer.setTextureCoords(textureDetails.bufferHandle);\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * bind the named indices buffer object and draw the elements in\r\n\t\t\t * respect to the GLES20 drawingMode\r\n\t\t\t */\r\n\t\t\tGLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER,\r\n\t\t\t\t\tindicesDetails.bufferHandle);\r\n\t\t\tGLES20.glDrawElements(drawingMode,\r\n\t\t\t\t\tindicesDetails.buffer.capacity(), GLES20.GL_UNSIGNED_SHORT,\r\n\t\t\t\t\t0);\r\n\r\n\t\t\tGLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);\r\n\t\t\tGLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate final class FeatureGeometryStride extends FeatureGeometry {\r\n\r\n\t\tprivate final FloatBuffer strideBuffer;\r\n\r\n\t\tprotected FeatureGeometryStride(final float[] vertices,\r\n\t\t\t\tfinal float[] colors, final float[] normals,\r\n\t\t\t\tfinal float[] textureCoords) {\r\n\t\t\tif (vertices.length % 3 != 0)\r\n\t\t\t\tthrow new IllegalArgumentException(\r\n\t\t\t\t\t\t\"[RENDERFEATURE] vertices-array size must be a multiple of three\");\r\n\r\n\t\t\tthis.hasColors = (colors != null && renderer.supportsColors);\r\n\t\t\tthis.hasNormals = (normals != null && renderer.supportsNormals);\r\n\t\t\tthis.hasTextureCoords = (textureCoords != null && renderer.supportsTextures);\r\n\r\n\t\t\tthis.verticesCount = vertices.length / SIZE_OF_POSITION;\r\n\t\t\tthis.strideBuffer = initInterleavedBuffer(vertices, colors,\r\n\t\t\t\t\tnormals, textureCoords);\r\n\t\t}\r\n\r\n\t\tprivate FloatBuffer initInterleavedBuffer(final float[] vertices,\r\n\t\t\t\tfinal float[] colors, final float[] normals,\r\n\t\t\t\tfinal float[] textureCoords) {\r\n\r\n\t\t\tfinal int bufferLength = vertices.length\r\n\t\t\t\t\t+ (hasColors ? colors.length : 0)\r\n\t\t\t\t\t+ (hasNormals ? normals.length : 0)\r\n\t\t\t\t\t+ (hasTextureCoords ? textureCoords.length : 0);\r\n\r\n\t\t\tint verticesOffset = 0;\r\n\t\t\tint normalsOffset = 0;\r\n\t\t\tint colorsOffset = 0;\r\n\t\t\tint texturesOffset = 0;\r\n\r\n\t\t\tfinal FloatBuffer interleavedBuffer = ByteBuffer\r\n\t\t\t\t\t.allocateDirect(bufferLength * SIZE_OF_FLOAT)\r\n\t\t\t\t\t.order(ByteOrder.nativeOrder()).asFloatBuffer();\r\n\r\n\t\t\tfor (int i = 0; i < verticesCount; i++) {\r\n\t\t\t\tinterleavedBuffer.put(vertices, verticesOffset,\r\n\t\t\t\t\t\tSIZE_OF_POSITION);\r\n\t\t\t\tverticesOffset += SIZE_OF_POSITION;\r\n\t\t\t\tif (hasColors) {\r\n\t\t\t\t\tinterleavedBuffer\r\n\t\t\t\t\t\t\t.put(colors, colorsOffset, SIZE_OF_COLOR);\r\n\t\t\t\t\tcolorsOffset += SIZE_OF_COLOR;\r\n\t\t\t\t}\r\n\t\t\t\tif (hasNormals) {\r\n\t\t\t\t\tinterleavedBuffer.put(normals, normalsOffset,\r\n\t\t\t\t\t\t\tSIZE_OF_NORMAL);\r\n\t\t\t\t\tnormalsOffset += SIZE_OF_NORMAL;\r\n\t\t\t\t}\r\n\t\t\t\tif (hasTextureCoords) {\r\n\t\t\t\t\tinterleavedBuffer.put(textureCoords, texturesOffset,\r\n\t\t\t\t\t\t\tSIZE_OF_TEXCOORD);\r\n\t\t\t\t\ttexturesOffset += SIZE_OF_TEXCOORD;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tinterleavedBuffer.position(0);\r\n\t\t\treturn interleavedBuffer;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tvoid render() {\r\n\t\t\t// @formatter:off\r\n\t\t\tfinal int stride = (SIZE_OF_POSITION\r\n\t\t\t\t\t+ (hasColors ? SIZE_OF_COLOR : 0)\r\n\t\t\t\t\t+ (hasNormals ? SIZE_OF_NORMAL : 0) \r\n\t\t\t\t\t+ (hasTextureCoords ? SIZE_OF_TEXCOORD : 0))\r\n\t\t\t\t\t* SIZE_OF_FLOAT;\r\n\t\t\t// @formatter:on\r\n\r\n\t\t\tint bufferPosition = 0;\r\n\t\t\t/** defines the array of generic vertex attribute data */\r\n\t\t\tstrideBuffer.position(bufferPosition);\r\n\t\t\tfinal int positionhandle = renderer.getPositionHandle();\r\n\t\t\tGLES20.glEnableVertexAttribArray(positionhandle);\r\n\t\t\tGLES20.glVertexAttribPointer(positionhandle, SIZE_OF_POSITION,\r\n\t\t\t\t\tGLES20.GL_FLOAT, false, stride, strideBuffer);\r\n\t\t\tbufferPosition += SIZE_OF_POSITION;\r\n\r\n\t\t\tif (hasColors) {\r\n\t\t\t\t/** defines the array of color attribute data */\r\n\t\t\t\tstrideBuffer.position(bufferPosition);\r\n\t\t\t\tfinal int colorhandle = renderer.getColorHandle();\r\n\t\t\t\tGLES20.glEnableVertexAttribArray(colorhandle);\r\n\t\t\t\tGLES20.glVertexAttribPointer(colorhandle, SIZE_OF_COLOR,\r\n\t\t\t\t\t\tGLES20.GL_FLOAT, false, stride, strideBuffer);\r\n\t\t\t\tbufferPosition += SIZE_OF_COLOR;\r\n\t\t\t}\r\n\r\n\t\t\tif (hasNormals) {\r\n\t\t\t\t/** defines the array of vertices normals */\r\n\t\t\t\tstrideBuffer.position(bufferPosition);\r\n\t\t\t\tfinal int normalhandle = renderer.getNormalHandle();\r\n\t\t\t\tGLES20.glEnableVertexAttribArray(normalhandle);\r\n\t\t\t\tGLES20.glVertexAttribPointer(normalhandle, SIZE_OF_NORMAL,\r\n\t\t\t\t\t\tGLES20.GL_FLOAT, false, stride, strideBuffer);\r\n\t\t\t\tbufferPosition += SIZE_OF_NORMAL;\r\n\t\t\t}\r\n\r\n\t\t\tif (hasTextureCoords) {\r\n\t\t\t\t// FIXME texture handling here\r\n\t\t\t\tstrideBuffer.position(bufferPosition);\r\n\t\t\t\tfinal int textureCoordinateHandle = renderer\r\n\t\t\t\t\t\t.getTextureCoordinateHandle();\r\n\t\t\t\tGLES20.glEnableVertexAttribArray(textureCoordinateHandle);\r\n\t\t\t\tGLES20.glVertexAttribPointer(textureCoordinateHandle,\r\n\t\t\t\t\t\tSIZE_OF_TEXCOORD, GLES20.GL_FLOAT, false, stride,\r\n\t\t\t\t\t\tstrideBuffer);\r\n\t\t\t\tbufferPosition += SIZE_OF_TEXCOORD;\r\n\t\t\t}\r\n\r\n\t\t\t/** render primitives from array data */\r\n\t\t\tGLES20.glDrawArrays(drawingMode, 0, verticesCount);\r\n\t\t}\r\n\t}\r\n\r\n\t/** Feature geometries and shader settings */\r\n\tprotected FeatureGeometry geometry;\r\n\tprotected FeatureShader renderer;\r\n\tprotected BoundingBox boundingBox; // unused\r\n\r\n\tprotected final Stack<OpenGLCallable> childrenFeatures = new Stack<OpenGLCallable>();\r\n\r\n\t/** Model Matrix of this feature */\r\n\tprivate final float[] modelMatrix = new float[16];\r\n\t/** Model-View-Projection Matrix of our feature */\r\n\tprivate final float[] mvpMatrix = new float[16];\r\n\t/** temporary Matrix for caching */\r\n\tprivate final float[] tmpMatrix = new float[16];\r\n\r\n\t/** GL drawing mode - default triangles */\r\n\tprotected int drawingMode = GLES20.GL_TRIANGLES;\r\n\t/** GL for features rendering */\r\n\tprotected boolean enableBlending = true;\r\n\tprotected boolean enableDepthTest = true;\r\n\tprotected boolean enableDepthMask = true;\r\n\tprotected boolean enableCullFace = false;\r\n\t\r\n\tprotected float heightOffset = 0.0f;\r\n\t/** alpha value for Blending */\r\n\tprotected Float alpha; \r\n\t/** color of the object */\r\n\tprotected int androidColor; \r\n\r\n\tprotected boolean isInitialized = false;\r\n\tprivate Texture texture;\r\n\r\n\t@Deprecated\r\n\tprotected void setRenderObjectives(float[] vertices, float[] colors,\r\n\t\t\tfloat[] normals, float[] textureCoords, short[] indices) {\r\n\t\tif (indices == null || indices.length == 0) {\r\n\t\t\tsetRenderObjectives(vertices, colors, normals, textureCoords);\r\n\t\t} else {\r\n\r\n\t\t\tif (renderer == null) {\r\n\t\t\t\trenderer = BilligerColorShader.getInstance();\r\n\t\t\t}\r\n\t\t\t// renderer.onCreateInGLESThread();\r\n\t\t\tgeometry = new FeatureGeometryVBOandIBO(vertices, colors, normals,\r\n\t\t\t\t\ttextureCoords, indices);\r\n\t\t\tboundingBox = new BoundingBox(vertices);\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void setRenderObjectives(float[] vertices, float[] colors,\r\n\t\t\tfloat[] normals, float[] textureCoords) {\r\n\t\t// TODO XXX FIXME not elegant here, maybe this is\r\n\t\t// Jep\r\n\t\tif (renderer == null) {\r\n\t\t\tif (textureCoords != null && texture != null) {\r\n\t\t\t\trenderer = TextureFeatureShader.getInstance();\r\n\t\t\t} else {\r\n\t\t\t\trenderer = BilligerLightShader.getInstance();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// renderer.onCreateInGLESThread();\r\n\t\tgeometry = new FeatureGeometryStride(vertices, colors, normals,\r\n\t\t\t\ttextureCoords);\r\n\t\tboundingBox = new BoundingBox(vertices);\r\n\r\n\t\tisInitialized = true;\r\n\t}\r\n\r\n\tpublic float[] onScreenCoordsUpdate() {\r\n\t\tif (modelMatrix == null || GLESCamera.projectionMatrix == null\r\n\t\t\t\t|| GLESCamera.viewportMatrix == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tfloat[] output = new float[3];\r\n\t\tint res = GLU.gluProject(position[0], position[1], position[2],\r\n\t\t\t\tmodelMatrix, 0, GLESCamera.projectionMatrix, 0,\r\n\t\t\t\tGLESCamera.viewportMatrix, 0, output, 0);\r\n\r\n\t\tif (res == GL10.GL_FALSE)\r\n\t\t\treturn null;\r\n\t\treturn output;\r\n\t}\r\n\r\n\tpublic void transform() {\r\n\t\t// TODO\r\n\t\t// gl.glTranslatef(tx, ty, tz);\r\n\t\t// gl.glRotatef(rz, 0, 0, 1);\r\n\t\t// gl.glRotatef(ry, 0, 1, 0);\r\n\t\t// gl.glRotatef(rx, 1, 0, 0);\r\n\t\t// gl.glScalef(sx, sy, sz);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void render(final float[] projectionMatrix,\r\n\t\t\tfinal float[] viewMatrix, final float[] parentMatrix,\r\n\t\t\tfinal float[] lightPosition) {\r\n\t\tif (!isInitialized)\r\n\t\t\treturn;\r\n\t\t\r\n\t\t/** set the matrices to identity matrix */\r\n\t\tMatrix.setIdentityM(modelMatrix, 0);\r\n\t\tMatrix.setIdentityM(mvpMatrix, 0);\r\n\t\tMatrix.setIdentityM(tmpMatrix, 0);\r\n\t\t/** translate feature to the position relative to the device */\r\n\t\t// TODO i think position[0] must be translated negatively -> Check\r\n\t\tMatrix.translateM(modelMatrix, 0, position[0], position[1], position[2]);\r\n\r\n\t\tif (parentMatrix != null) {\r\n\t\t\tMatrix.multiplyMM(tmpMatrix, 0, parentMatrix, 0, modelMatrix, 0);\r\n\t\t\tSystem.arraycopy(tmpMatrix, 0, modelMatrix, 0, 16);\r\n\t\t\tMatrix.setIdentityM(tmpMatrix, 0);\r\n\t\t}\r\n\r\n\t\tMatrix.multiplyMM(modelMatrix, 0, viewMatrix, 0, modelMatrix, 0);\r\n\t\tMatrix.multiplyMM(mvpMatrix, 0, projectionMatrix, 0, modelMatrix, 0);\r\n\r\n\t\trender(mvpMatrix, modelMatrix, lightPosition);\r\n\t\t\r\n\t\tfor(OpenGLCallable childFeature : childrenFeatures){\r\n\t\t\tchildFeature.render(projectionMatrix, viewMatrix, modelMatrix, lightPosition);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void render(float[] mvpMatrix) {\r\n\t\t/** sets the program object as part of current rendering state */\r\n\t\tif (!isInitialized)\r\n\t\t\treturn;\r\n\t\trenderer.useProgram();\r\n\t\t\r\n\t\tif(enableBlending){\r\n\t\t\tGLES20.glEnable(GLES20.GL_BLEND);\r\n\t\t}\r\n\t\tif(enableCullFace){\r\n\t\t\tGLES20.glEnable(GLES20.GL_CULL_FACE);\r\n\t\t}\r\n\r\n\t\tif (texture != null) {\r\n\t\t\t// Set the active texture unit to texture unit 0.\r\n\t\t\tGLES20.glActiveTexture(GLES20.GL_TEXTURE0);\r\n\t\t\tGLES20.glUniform1i(renderer.getTextureUniform(), 0);\r\n\r\n\t\t\t// // Bind the texture to this unit.\r\n\t\t\t// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,\r\n\t\t\t// textureDetails.textureId);\r\n\r\n\t\t\ttexture.bindTexture();\r\n\t\t}\r\n\t\trenderer.setModelViewProjectionMatrix(mvpMatrix);\r\n\t\t\r\n\t\t/** render the geometry of this feature */\r\n\t\tif (geometry != null)\r\n\t\t\tgeometry.render();\r\n\t}\r\n\t\r\n\r\n\tpublic void render(float[] mvpMatrix, float[] mvMatrix,\r\n\t\t\tfloat[] lightPosition) {\r\n\t\t/** sets the program object as part of current rendering state */\r\n\t\trenderer.useProgram();\r\n\t\t\r\n\t\tif(enableBlending){\r\n\t\t\tGLES20.glEnable(GLES20.GL_BLEND);\r\n\t\t}\r\n\t\tif(enableCullFace){\r\n\t\t\tGLES20.glEnable(GLES20.GL_CULL_FACE);\r\n\t\t}\r\n\r\n\t\trenderer.setLightPositionVec(lightPosition);\r\n\t\t\r\n\t\tif (texture != null) {\r\n\t\t\t// Set the active texture unit to texture unit 0.\r\n\t\t\tGLES20.glActiveTexture(GLES20.GL_TEXTURE0);\r\n\t\t\tGLES20.glUniform1i(renderer.getTextureUniform(), 0);\r\n\r\n\t\t\t// // Bind the texture to this unit.\r\n\t\t\t// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,\r\n\t\t\t// textureDetails.textureId);\r\n\r\n\t\t\ttexture.bindTexture();\r\n\t\t}\r\n\r\n\t\trenderer.setModelViewMatrix(mvMatrix);\r\n\t\trenderer.setModelViewProjectionMatrix(mvpMatrix);\r\n\r\n\t\t/** render the geometry of this feature */\r\n\t\tif (geometry != null)\r\n\t\t\tgeometry.render();\r\n\t\t\r\n\t\tGLES20.glDisable(GLES20.GL_BLEND);\r\n\t\tGLES20.glDisable(GLES20.GL_CULL_FACE);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void enableCullface(boolean cullface) {\r\n\t\tthis.enableCullFace = cullface;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void enableBlending(boolean blending, float alpha) {\r\n\t\tthis.enableBlending = blending;\r\n\t\tthis.alpha = alpha;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void enableDepthtest(boolean depthTest) {\r\n\t\tthis.enableDepthTest = depthTest;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setDrawingMode(int drawingMode) {\r\n\t\tthis.drawingMode = drawingMode;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setColor(int androidColor) {\r\n\t\tthis.androidColor = androidColor;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setColor(float[] colorArray) {\r\n\t\tthrow new UnsupportedOperationException();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setTextureCallback(Callable<Bitmap> callback) {\r\n\t\tthis.texture = Texture.createInstance(callback);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void setSubVisualization(DataSourceVisualizationGL subVisualizationGL) {\r\n\t\tif (this.childrenFeatures.contains(subVisualizationGL))\r\n\t\t\treturn;\r\n\t\tthis.childrenFeatures.add((OpenGLCallable) subVisualizationGL);\r\n\t}\r\n\r\n\tpublic void setLightPosition(float[] lightPosInEyeSpace) {\r\n\t\tGLES20.glUniform3f(renderer.getLightPosHandle(), lightPosInEyeSpace[0],\r\n\t\t\t\tlightPosInEyeSpace[1], lightPosInEyeSpace[2]);\r\n\t}\r\n}\r" ]
import java.util.List; import javax.microedition.khronos.opengles.GL10; import org.n52.geoar.ar.view.gl.ARSurfaceViewRenderer.OpenGLCallable; import org.n52.geoar.ar.view.gl.GLESCamera; import org.n52.geoar.newdata.DataSourceInstanceHolder; import org.n52.geoar.newdata.SpatialEntity2; import org.n52.geoar.newdata.Visualization; import org.n52.geoar.newdata.Visualization.FeatureVisualization; import org.n52.geoar.newdata.vis.DataSourceVisualization.DataSourceVisualizationCanvas; import org.n52.geoar.tracking.location.LocationHandler; import org.n52.geoar.view.geoar.gl.mode.RenderFeature2; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.location.Location; import android.opengl.GLU; import android.opengl.Matrix; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup.LayoutParams; import android.widget.RelativeLayout; import com.vividsolutions.jts.geom.Geometry;
/** * Copyright 2012 52°North Initiative for Geospatial Open Source Software GmbH * * 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 org.n52.geoar.ar.view; /** * * @author Arne de Wall <a.dewall@52North.org> * */ public class ARObject implements OpenGLCallable { private static float getScaleByDistance(float distance) { // XXX TODO FIXME reworking scaling function int x = org.n52.geoar.view.geoar.Settings.BUFFER_MAPINTERPOLATION; if (distance > x) { return 0.5f; } float scale = 1 - (distance / (x * 2)); return Math.max(0.5f, scale); } private static Paint distancePaint = new Paint(); static { distancePaint.setAntiAlias(true); distancePaint.setColor(Color.GRAY); distancePaint.setAlpha(100); } /** Model Matrix of this feature */ private final float[] modelMatrix = new float[16]; /** Model view Matrix of this feature */ private final float[] modelViewMatrix = new float[16]; /** Model-View-Projection Matrix of our feature */ private final float[] mvpMatrix = new float[16]; /** temporary Matrix for caching */ private final float[] tmpMatrix = new float[16]; private float distanceTo; private float featureDetailsScale; private final float[] newPosition = new float[4]; private final float[] screenCoordinates = new float[3]; private volatile boolean isInFrustum = false; // XXX Why mapping by Class? Compatible with multiinstancedatasources? // private final Map<Class<? extends ItemVisualization>, VisualizationLayer> // visualizationLayers = new HashMap<Class<? extends ItemVisualization>, // VisualizationLayer>(); private final SpatialEntity2<? extends Geometry> entity; private DataSourceVisualizationCanvas canvasFeature; private List<RenderFeature2> renderFeatures; private FeatureVisualization visualization; private View featureDetailView; private Bitmap featureDetailBitmap; private DataSourceInstanceHolder dataSourceInstance; // TODO FIXME XXX task: ARObject gains most functionalities of RenderFeature // (-> RenderFeature to be more optional) public ARObject(SpatialEntity2<? extends Geometry> entity, Visualization.FeatureVisualization visualization, List<RenderFeature2> features, DataSourceVisualizationCanvas canvasFeature, DataSourceInstanceHolder dataSourceInstance) { this.entity = entity; this.renderFeatures = features; this.canvasFeature = canvasFeature; this.visualization = visualization; this.dataSourceInstance = dataSourceInstance;
onLocationUpdate(LocationHandler.getLastKnownLocation());
3
kristian/JDigitalSimulator
src/main/java/lc/kra/jds/components/buildin/display/TenSegmentDisplay.java
[ "public static String getTranslation(String key) { return getTranslation(key, TranslationType.TEXT); }", "public static enum TranslationType { TEXT, ALTERNATIVE, TITLE, EXTERNAL, TOOLTIP, DESCRIPTION; }", "public abstract class Component implements Paintable, Locatable, Moveable, Cloneable, Serializable {\n\tprivate static final long serialVersionUID = 1l;\n\n\tpublic static final ComponentAttributes componentAttributes = null;\n\n\tprivate Point location;\n\tprotected PropertyChangeSupport change;\n\n\tpublic Component() { this.location = new Point(); }\n\tpublic Component(Point location) { this.setLocation(location); }\n\n\tpublic abstract Dimension getSize();\n\t@Override public void moveTo(Point location) { this.setLocation(location); }\n\t@Override public void moveRelative(Point location) {\n\t\tif(this.location.x+location.x<0||this.location.y+location.y<0)\n\t\t\tthrow new LocationOutOfBoundsException();\n\t\tPoint oldLocation = new Point(this.location);\n\t\tthis.location.translate(location.x, location.y);\n\t\tfirePropertyChange(\"location\", oldLocation, this.location);\n\t}\n\t@Override public final Point getLocation() { return this.location; }\n\t@Override public final void setLocation(Point location) throws LocationOutOfBoundsException {\n\t\tif(location.x<0||location.y<0)\n\t\t\tthrow new LocationOutOfBoundsException();\n\t\tfirePropertyChange(\"location\", new Point(this.location), this.location = location);\n\t}\n\n\tprotected void addPropertyChangeListener(PropertyChangeListener listener) {\n\t\tif(listener==null) return;\n\t\telse if(change==null) change = new PropertyChangeSupport(this);\n\t\tchange.addPropertyChangeListener(listener);\n\t}\n\tprotected void addPropertyChangeListener(String name, PropertyChangeListener listener) {\n\t\tif(listener==null) return;\n\t\telse if(change==null) change = new PropertyChangeSupport(this);\n\t\tchange.addPropertyChangeListener(name, listener);\n\t}\n\tprotected PropertyChangeListener[] getPropertyChangeListeners(String name) {\n\t\tif(change==null) return new PropertyChangeListener[0];\n\t\treturn change.getPropertyChangeListeners(name);\n\t}\n\tprotected void removePropertyChangeListener(PropertyChangeListener listener) {\n\t\tif(listener==null||change==null) return;\n\t\tchange.removePropertyChangeListener(listener);\n\t}\n\tprotected void removePropertyChangeListener(String name, PropertyChangeListener listener) {\n\t\tif(listener==null||change==null) return;\n\t\tchange.removePropertyChangeListener(name, listener);\n\t}\n\n\tprivate void firePropertyChange(String name, Object oldValue, Object newValue) {\n\t\tif(change==null||(oldValue!=null&&newValue!=null&&oldValue.equals(newValue)))\n\t\t\treturn;\n\t\tchange.firePropertyChange(name, oldValue, newValue);\n\t}\n\n\tpublic abstract void calculate();\n\n\tpublic final ComponentAttributes getAttributes() { return Component.getAttributes(this.getClass()); }\n\tpublic final static ComponentAttributes getAttributes(Class<? extends Component> cls) {\n\t\treturn getField(cls, \"componentAttributes\", new ComponentAttributes(cls.getSimpleName(), \"group.general\"));\n\t}\n\n\t@Override public Component clone() throws CloneNotSupportedException {\n\t\tComponent clone = null;\n\t\tif((clone=(Component)Utilities.copy(this)) instanceof Sociable)\n\t\t\tfor(Contact contact:((Sociable)clone).getContacts())\n\t\t\t\tcontact.removeWires();\n\t\treturn clone;\n\t}\n\n\tprivate void writeObject(ObjectOutputStream out) throws IOException {\n\t\tPropertyChangeSupport change = this.change;\n\t\tif(Utilities.isCopying())\n\t\t\tthis.change = null;\n\t\tout.defaultWriteObject();\n\t\tthis.change = change;\n\t}\n\n\tpublic static Set<Component> clone(Collection<Component> components) throws CloneNotSupportedException {\n\t\tHashMap<Component, Component> clonedComponents = new HashMap<Component, Component>();\n\t\tfor(Component component:components) {\n\t\t\tComponent clone = component.clone();\n\t\t\tclonedComponents.put(component, clone);\n\t\t}\n\t\tHashMap<Component, List<Wire>> clones = new HashMap<Component, List<Wire>>(); List<Wire> wires;\n\t\tfor(Component component:components) {\n\t\t\tComponent clone = clonedComponents.get(component);\n\t\t\tclones.put(clone, wires=new Vector<Wire>());\n\t\t\tif(component instanceof Sociable) {\n\t\t\t\tIterator<Contact> contacts = Arrays.asList(((Sociable)component).getContacts()).iterator(),\n\t\t\t\t\t\tclonedContacts = Arrays.asList(((Sociable)clone).getContacts()).iterator();\n\t\t\t\tfor(;contacts.hasNext()&&clonedContacts.hasNext();) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tContact contact = contacts.next(), clonedContact = clonedContacts.next();\n\t\t\t\t\t\tif(contact instanceof OutputContact)\n\t\t\t\t\t\t\tfor(Wire wire:contact.getWires()) {\n\t\t\t\t\t\t\t\tComponent target = wire.getTarget().getComponent(),\n\t\t\t\t\t\t\t\t\t\tcloneTarget = clonedComponents.get(target);\n\t\t\t\t\t\t\t\tif(cloneTarget!=null) {\n\t\t\t\t\t\t\t\t\tIterator<Contact> targetContacts = Arrays.asList(((Sociable) target).getContacts()).iterator(),\n\t\t\t\t\t\t\t\t\t\t\tcloneTargetContacts = Arrays.asList(((Sociable) cloneTarget).getContacts()).iterator();\n\t\t\t\t\t\t\t\t\tfor(;targetContacts.hasNext()&&cloneTargetContacts.hasNext();) {\n\t\t\t\t\t\t\t\t\t\tContact targetContact = targetContacts.next(),\n\t\t\t\t\t\t\t\t\t\t\t\tcloneTargetContact = cloneTargetContacts.next();\n\t\t\t\t\t\t\t\t\t\tif(targetContact instanceof InputContact&&targetContact.equals(wire.getTarget())) {\n\t\t\t\t\t\t\t\t\t\t\twires.add(new Wire(clonedContact, cloneTargetContact));\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\tcatch (WireNotConnectable e) {\n\t\t\t\t\t\t//well, wire could not be connected... will never happen?\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new HashSet<Component>(clonedComponents.values());\n\t}\n\n\t@Target(ElementType.TYPE)\n\t@Retention(RetentionPolicy.RUNTIME)\n\tpublic static @interface HiddenComponent{}\n\n\tpublic static class ComponentAttributes {\n\t\tpublic final String key, name, group, description, author;\n\t\tpublic final int version;\n\t\tpublic ComponentAttributes(String name, String group) { this(name, group, 0); }\n\t\tpublic ComponentAttributes(String name, String group, int version) { this(name, group, null, null, version); }\n\t\tpublic ComponentAttributes(String name, String group, String description, String author, int version) { this(name.replaceAll(\"\\\\W\", new String()), name, group, description, author, version); }\n\t\tpublic ComponentAttributes(String key, String name, String group) { this(key, name, group, 0); }\n\t\tpublic ComponentAttributes(String key, String name, String group, int version) { this(key, name, group, null, null, version); }\n\t\tpublic ComponentAttributes(String key, String name, String group, String description, String author, int version) {\n\t\t\tthis.key = key;\n\t\t\tthis.name = name;\n\t\t\tthis.group = group;\n\t\t\tthis.description = description;\n\t\t\tthis.author = author;\n\t\t\tthis.version = version;\n\t\t}\n\t\t@Override public int hashCode() { return (key+group).hashCode(); }\n\t\t@Override public boolean equals(Object object) {\n\t\t\tif(super.equals(object))\n\t\t\t\treturn true;\n\t\t\tif(!(object instanceof ComponentAttributes))\n\t\t\t\treturn false;\n\t\t\tComponentAttributes attributes = (ComponentAttributes) object;\n\t\t\treturn key.equals(attributes.key)&&group.equals(attributes.group);\n\t\t}\n\t}\n\n\tpublic static class ComponentFlavor extends DataFlavor {\n\t\tprivate static ComponentFlavor flavour;\n\t\tpublic ComponentFlavor() { super(Component.class, \"Component\");\t}\n\t\tpublic static ComponentFlavor getFlavor() {\n\t\t\tif(flavour==null)\n\t\t\t\tflavour = new ComponentFlavor();\n\t\t\treturn flavour;\n\t\t}\n\t}\n}", "public interface Sociable {\n\tpublic Contact[] getContacts();\n}", "public abstract class Contact implements Cloneable, Paintable, Locatable, Charged, Serializable {\n\tprivate static final long serialVersionUID = 1l;\n\n\tprotected static final int CONTACT_SIZE = 4;\n\n\tprotected List<Wire> wires;\n\n\tpublic Contact() { wires = new ArrayList<Wire>(); }\n\tpublic Contact(Wire wire) throws WireNotConnectable {\n\t\tthis();\n\t\tthis.setWire(wire);\n\t}\n\n\tpublic void setWire(Wire wire) throws WireNotConnectable { setWires(wire); }\n\tpublic void setWires(Wire... wires) throws WireNotConnectable { this.setWires(Arrays.asList(wires)); }\n\tpublic void setWires(List<Wire> wires) throws WireNotConnectable {\n\t\tthis.wires.clear();\n\t\tfor(Wire wire:wires)\n\t\t\taddWire(wire);\n\t}\n\tpublic void addWire(Wire wire) throws WireNotConnectable {\n\t\tif(!this.wires.contains(wire))\n\t\t\tthis.wires.add(wire);\n\t}\n\tpublic Wire getWire() { return !isWired()?null:this.wires.get(0); }\n\tpublic List<Wire> getWires() { return this.wires; }\n\tpublic boolean isWired() { return countWires()!=0; }\n\tpublic int countWires() { return wires.size(); }\n\tpublic boolean removeWire(Wire wire) { return this.wires.remove(wire); }\n\tpublic void removeWires() { this.wires.clear(); }\n\n\tpublic abstract Component getComponent();\n\n\t@Override public abstract float getVoltage();\n\t@Override public boolean isCharged() throws ForbiddenVoltageLevel {\n\t\tfloat voltage = Math.abs(getVoltage());\n\t\t//everything between below 1 is 0\n\t\treturn Math.floor(voltage)!=0;\n\t}\n\n\t@Override public void paint(Graphics g) {\n\t\ttry { validateLocation(); }\n\t\tcatch(LocationOutOfBoundsException e) {\n\t\t\treturn; //this location does not exist for this component\n\t\t}\n\t\tPoint location = getLocation();\n\t\tg.setColor(Color.BLACK);\n\t\tg.fillRect(location.x-CONTACT_SIZE/2, location.y-CONTACT_SIZE/2,\n\t\t\t\tCONTACT_SIZE, CONTACT_SIZE);\n\t}\n\n\tprotected abstract void validateLocation() throws LocationOutOfBoundsException;\n\n\t@Override public Contact clone() throws CloneNotSupportedException {\n\t\tContact clone = (Contact)super.clone();\n\t\tclone.wires = new ArrayList<Wire>(); //do not clone wires!\n\t\treturn clone;\n\t}\n\n\tprivate void writeObject(ObjectOutputStream out) throws IOException {\n\t\tList<Wire> wires = this.wires;\n\t\tif(Utilities.isCopying()) //do not clone wires!\n\t\t\tthis.wires = new ArrayList<Wire>();\n\t\tout.defaultWriteObject();\n\t\tthis.wires = wires;\n\t}\n}", "public class ContactList<Type extends Contact> implements Cloneable, Serializable, Iterable<Type> {\n\tprivate static final long serialVersionUID = 1l;\n\n\tpublic enum Alignment { HORIZONTAL, VERTICAL; }\n\n\tprivate LinkedList<Type> contacts;\n\tprivate Class<Type> cls;\n\tprivate Component component;\n\n\tpublic ContactList(Component component, Class<Type> cls) { this(component, cls, 0); }\n\tpublic ContactList(Component component, Class<Type> cls, int count) {\n\t\tthis.component = component; this.cls = cls;\n\t\tcontacts = new LinkedList<Type>();\n\t\tsetContacts(count);\tsetContactLocations();\n\t}\n\n\tpublic Type getContact(int index) { return contacts.get(index); }\n\tpublic int getContactsCount() { return contacts.size(); }\n\tpublic boolean setContacts(int count) {\n\t\tif(count<0) throw new IllegalArgumentException(\"Only positive number of contacts allowed.\");\n\t\twhile(contacts.size()>count) {\n\t\t\tContact contact = contacts.getLast();\n\t\t\tfor(Wire wire=null;(wire=contact.getWire())!=null;)\n\t\t\t\twire.removeWire();\n\t\t\tcontacts.remove(contact);\n\t\t}\n\t\ttry {\n\t\t\tConstructor<Type> constructor = cls.getConstructor(Component.class);\n\t\t\twhile(contacts.size()<count)\n\t\t\t\tthis.contacts.add(constructor.newInstance(component));\n\t\t} catch(Exception e) { return false; }\n\t\treturn true;\n\t}\n\n\tpublic void setContactLocations() { this.setContactLocations(new Point()); }\n\tpublic void setContactLocations(Point location) { this.setContactLocations(location, Alignment.VERTICAL); }\n\tpublic void setContactLocations(Alignment alignment) { this.setContactLocations(new Point(), alignment); }\n\tpublic void setContactLocations(Point location, Alignment alignment) { setContactLocations(component, contacts.toArray(new Contact[0]), location, alignment); }\n\tpublic static <Type extends Contact> void setContactLocations(Component component, Type[] contacts) { setContactLocations(component, contacts, new Point()); }\n\tpublic static <Type extends Contact> void setContactLocations(Component component, Type[] contacts, Point location) { setContactLocations(component, contacts, location, Alignment.VERTICAL); }\n\tpublic static <Type extends Contact> void setContactLocations(Component component, Type[] contacts, Alignment alignment) { setContactLocations(component, contacts, new Point(), alignment); }\n\tpublic static <Type extends Contact> void setContactLocations(Component component, Type[] contacts, Point location, Alignment alignment) {\n\t\tfloat intervalX, intervalY, positionX, positionY;\n\t\tintervalX = intervalY = positionX = positionY = 0f;\n\t\tswitch(alignment) {\n\t\tcase HORIZONTAL: intervalX = (float)(component.getSize().width+1-location.x)/(contacts.length+1); intervalY = 0; break;\n\t\tcase VERTICAL: intervalX = 0; intervalY = (float)(component.getSize().height+1-location.y)/(contacts.length+1); break; }\n\t\tfor(Contact contact:contacts) {\n\t\t\tpositionX += intervalX; positionY += intervalY;\n\t\t\tcontact.setLocation(Guitilities.addPoints(location, new Point((int)positionX,\n\t\t\t\t\t(int)positionY)));\n\t\t}\n\t}\n\n\tpublic Contact[] toArray() { return contacts.toArray(new Contact[0]); }\n\t@Override public Iterator<Type> iterator() { return contacts.iterator(); }\n\n\tpublic void paintSolderingJoints(Graphics graphics) { this.paintSolderingJoints(graphics, 5, 5); }\n\tpublic void paintSolderingJoints(Graphics graphics, int marginLeft, int marginRight) {\n\t\tContactUtilities.paintSolderingJoints(graphics, marginLeft, marginRight, contacts.toArray(new Contact[0]));\n\t}\n\n\t@Override public ContactList<Type> clone() throws CloneNotSupportedException {\n\t\treturn cloneForComponent(null);\n\t}\n\tpublic ContactList<Type> cloneForComponent(Component component) throws CloneNotSupportedException {\n\t\t@SuppressWarnings(\"unchecked\") ContactList<Type> clone = (ContactList<Type>)super.clone();\n\t\tclone.contacts = new LinkedList<Type>();\n\t\tfor(Type contact:contacts)\n\t\t\tclone.contacts.add(ContactUtilities.cloneForComponent(contact, component));\n\t\tclone.component = component;\n\t\treturn clone;\n\t}\n}", "public class ContactUtilities {\n\tpublic static Contact[] concatenateContacts(Contact contact, Contact[] contacts) { return concatenateContacts(new Contact[]{contact}, contacts); }\n\tpublic static Contact[] concatenateContacts(Contact[]... contacts) {\n\t\tint length = 0; for(Contact[] contact:contacts) length += contact.length;\n\t\tint offset = 0; Contact[] concatenated = new Contact[length];\n\t\tfor(Contact[] contact:contacts) {\n\t\t\tSystem.arraycopy(contact, 0, concatenated, offset, contact.length);\n\t\t\toffset += contact.length;\n\t\t}\n\t\treturn concatenated;\n\t}\n\n\tpublic static void paintSolderingJoint(Graphics graphics, Contact contact) { paintSolderingJoints(graphics, contact); }\n\tpublic static void paintSolderingJoint(Graphics graphics, int marginLeft, int marginRight, Contact contact) { paintSolderingJoints(graphics, marginLeft, marginRight, contact); }\n\tpublic static void paintSolderingJoints(Graphics graphics, Contact... contacts) { paintSolderingJoints(graphics, 5, 5, contacts); }\n\tpublic static void paintSolderingJoints(Graphics graphics, int marginLeft, int marginRight, Contact... contacts) {\n\t\tfor(Contact contact:contacts) {\n\t\t\tPoint location = contact.getLocation();\n\t\t\tint width = contact.getComponent().getSize().width;\n\t\t\tif(location.x<width/2)\n\t\t\t\tgraphics.drawLine(location.x, location.y, location.x+marginLeft, location.y);\n\t\t\telse graphics.drawLine(location.x-marginRight, location.y, location.x, location.y);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"unchecked\") protected static <Type extends Contact> Type clone(Type contact) throws CloneNotSupportedException {\n\t\treturn (Type)contact.clone();\n\t}\n\t@SuppressWarnings(\"unchecked\") protected static <Type extends Contact> Type cloneForComponent(Type contact, Component component) throws CloneNotSupportedException {\n\t\tif(contact instanceof ComponentContact)\n\t\t\treturn (Type)((ComponentContact)contact).cloneForComponent(component);\n\t\telse return (Type)contact.clone();\n\t}\n\n\tprotected static <Type extends Contact> Type[] clone(Type[] contacts) throws CloneNotSupportedException {\n\t\tif(contacts==null) throw new CloneNotSupportedException();\n\t\tClass<?> type = contacts.getClass().getComponentType();\n\t\t@SuppressWarnings(\"unchecked\") Type[] clone = (Type[])Array.newInstance(type, contacts.length);\n\t\tfor(int index=0;index<contacts.length;index++)\n\t\t\tclone[index] = ContactUtilities.clone(contacts[index]);\n\t\treturn clone;\n\t}\n\tprotected static <Type extends Contact> Type[] cloneForComponent(Type[] contacts, Component component) throws CloneNotSupportedException {\n\t\tif(contacts==null) throw new CloneNotSupportedException();\n\t\tClass<?> type = contacts.getClass().getComponentType();\n\t\t@SuppressWarnings(\"unchecked\") Type[] clone = (Type[])Array.newInstance(type, contacts.length);\n\t\tfor(int index=0;index<contacts.length;index++)\n\t\t\tclone[index] = ContactUtilities.cloneForComponent(contacts[index], component);\n\t\treturn clone;\n\t}\n\n\tprotected static <Type extends Contact> ContactList<Type> clone(ContactList<Type> contacts) throws CloneNotSupportedException {\n\t\treturn contacts.clone();\n\t}\n\tprotected static <Type extends Contact> ContactList<Type> cloneForComponent(ContactList<Type> contacts, Component component) throws CloneNotSupportedException {\n\t\treturn contacts.cloneForComponent(component);\n\t}\n}", "public class InputContact extends ComponentContact implements Cloneable {\n\tprivate static final long serialVersionUID = 1l;\n\n\tpublic InputContact(Component component) { super(component); }\n\tpublic InputContact(Component component, Point location) { super(component, location); }\n\n\t@Override public void addWire(Wire wire) throws WireNotConnectable {\n\t\tif(countWires()>=1)\n\t\t\tthrow new WireNotConnectable(\"Is is only allowed to connect one wire to an input contact.\");\n\t\telse if(wire.getTarget()!=this)\n\t\t\tthrow new WireNotConnectable(\"This contact needs to be the target contact to be connected with an wire.\");\n\t\telse if(wire.getSource()!=null&&wire.getSource().getClass().equals(InputContact.class))\n\t\t\tthrow new WireNotConnectable(\"This contact can not be connected to another input contact.\");\n\t\telse super.addWire(wire);\n\t}\n\n\t@Override public float getVoltage() {\n\t\tif(!isWired())\n\t\t\treturn Float.NaN;\n\t\t/*Contact contact = getWire().getSource();\n\t\tif(contact.equals(this)) {\n\t\t\tSystem.err.println(\"Wrong wiring!\");\n\t\t\treturn Float.NaN;\n\t\t}*/\n\t\treturn getWire().getVoltage();\n\t}\n\t@Override\n\tpublic boolean isCharged() throws ForbiddenVoltageLevel {\n\t\tfloat voltage = Math.abs(getVoltage());\n\t\t//forbidden voltage level between 0.4 and 2.4\n\t\tif((voltage<0.4&&voltage>2.4)||voltage>5)\n\t\t\tthrow new ForbiddenVoltageLevel(voltage, new float[]{0f, 0.4f, 2.4f, 5f});\n\t\treturn super.isCharged(); //check for NaN\n\t}\n\n\t@Override public void paint(Graphics g) {\n\t\ttry { validateLocation(); }\n\t\tcatch(LocationOutOfBoundsException e) {\n\t\t\treturn; //this location does not exist for this component\n\t\t} finally { super.paint(g); }\n\t\tPoint location = getLocation();\n\t\tg.setColor(Color.GRAY);\n\t\tg.fillRect(location.x-CONTACT_SIZE/2+1, location.y-CONTACT_SIZE/2+1,\n\t\t\t\tCONTACT_SIZE-2, CONTACT_SIZE-2);\n\t}\n}" ]
import lc.kra.jds.contacts.InputContact; import static lc.kra.jds.Utilities.getTranslation; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Polygon; import lc.kra.jds.Utilities.TranslationType; import lc.kra.jds.components.Component; import lc.kra.jds.components.Sociable; import lc.kra.jds.contacts.Contact; import lc.kra.jds.contacts.ContactList; import lc.kra.jds.contacts.ContactUtilities;
/* * JDigitalSimulator * Copyright (C) 2017 Kristian Kraljic * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package lc.kra.jds.components.buildin.display; /** * Ten segment display (build-in component) * @author Kristian Kraljic (kris@kra.lc) */ public class TenSegmentDisplay extends Component implements Sociable { private static final long serialVersionUID = 2l; private static final String KEY; static { KEY = "component.display."+TenSegmentDisplay.class.getSimpleName().toLowerCase(); } public static final ComponentAttributes componentAttributes = new ComponentAttributes(KEY, getTranslation(KEY), "group.display", getTranslation(KEY, TranslationType.DESCRIPTION), "Kristian Kraljic (kris@kra.lc)", 1); private static final int POLYGONS_X[][] = { { 4, 8, 32, 36, 32, 8, 4}, {36, 40, 40, 36, 32, 32, 36}, {36, 40, 40, 36, 32, 32, 36}, { 4, 8, 32, 36, 32, 8, 4}, { 4, 8, 8, 4, 0, 0, 4}, { 4, 8, 8, 4, 0, 0, 4}, { 4, 8, 16, 20, 16, 8, 4}, {20, 24, 32, 36, 32, 24, 20}, {20, 23, 23, 20, 17, 17, 20}, {20, 23, 23, 20, 17, 17, 20}, }; private static final int POLYGONS_Y[][] = { { 4, 0, 0, 4, 8, 8, 4}, { 4, 8, 32, 36, 32, 8, 4}, {36, 40, 64, 68, 64, 40, 36}, {68, 64, 64, 68, 72, 72, 68}, {36, 40, 64, 68, 64, 40, 36}, { 4, 8, 32, 36, 32, 8, 4}, {36, 32, 32, 36, 40, 40, 36}, {36, 32, 32, 36, 40, 40, 36}, { 9, 12, 31, 34, 31, 12, 9}, {38, 41, 60, 63, 60, 41, 38}, }; private Dimension size; private InputContact[] inputs; public TenSegmentDisplay() { size = new Dimension(60, 80); inputs = new InputContact[10]; for(int input=0;input<inputs.length;input++) inputs[input] = new InputContact(this); ContactList.setContactLocations(this, inputs); } @Override public void paint(Graphics graphics) { graphics.setColor(Color.BLACK); graphics.drawRect(10, 0, size.width-10, size.height); for(int input=0;input<inputs.length;input++) { Polygon polygon = new Polygon(POLYGONS_X[input], POLYGONS_Y[input], 7); polygon.translate(15, 4); if(inputs[input].isCharged()) { graphics.setColor(Color.RED); graphics.fillPolygon(polygon); } graphics.setColor(Color.BLACK); graphics.drawPolyline(polygon.xpoints, polygon.ypoints, polygon.npoints); }
ContactUtilities.paintSolderingJoints(graphics, 10, 0, inputs);
6
rpgmakervx/slardar
src/main/java/org/easyarch/slardar/session/DBSessionFactory.java
[ "public class CacheEntity {\n\n private int size;\n\n private CacheMode mode;\n\n private boolean enable;\n\n public CacheEntity(int size, CacheMode mode, boolean enable) {\n this.size = size;\n this.mode = mode;\n this.enable = enable;\n if (size == 0){\n this.enable = false;\n }\n }\n\n public int getSize() {\n return size;\n }\n\n public void setSize(int size) {\n this.size = size;\n }\n\n public CacheMode getMode() {\n return mode;\n }\n\n public void setMode(CacheMode mode) {\n this.mode = mode;\n }\n\n public boolean isEnable() {\n return enable;\n }\n\n public void setEnable(boolean enable) {\n this.enable = enable;\n }\n}", "public abstract class AbstractExecutor {\n\n abstract public <T> T query(String sql, ResultSetHandler<T> rshandler, Object[] params);\n\n abstract public int alter(String sql,Object[] params);\n\n abstract public void alterBatch(String sql,Object[][]params);\n abstract public void rollback();\n\n abstract public void close();\n\n protected PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException {\n return conn.prepareStatement(sql);\n }\n protected PreparedStatement batchPrepareStatement(Connection conn, String sql) throws SQLException {\n return conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);\n }\n\n protected void fillStatement(PreparedStatement ps, Object[] params) {\n try {\n int paramLength = params == null ? 0 : params.length;\n ParameterMetaData meta = ps.getParameterMetaData();\n int count = meta.getParameterCount();\n if (params == null||meta == null||count == 0)\n return;\n if (paramLength != count) {\n throw new IllegalArgumentException(\"param length is \"+paramLength+\",but sql string has \"+count);\n }\n for (int index = 0; index < paramLength; index++) {\n if (params[index] == null) {\n ps.setNull(index + 1, Types.VARCHAR);\n continue;\n }\n ps.setObject(index + 1, params[index]);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n protected void fillStatementWithBean(PreparedStatement ps, Object bean) {\n if (bean == null)\n return;\n PropertyDescriptor[] descriptors = ReflectUtils.propertyDescriptors(bean.getClass());\n Object[] params = new Object[descriptors.length];\n for (int index = 0; index < params.length; index++) {\n Object value = ReflectUtils.getter(bean, descriptors[index].getName());\n params[index] = value;\n }\n fillStatement(ps, params);\n }\n\n protected void fillStatement(PreparedStatement ps, Object[][] params){\n try {\n int paramLength = params == null ? 0 : params.length;\n ParameterMetaData meta = ps.getParameterMetaData();\n int count = meta.getParameterCount();\n if (params == null||meta == null||count == 0)\n return;\n if (paramLength != count) {\n throw new IllegalArgumentException(\"your param not match query string's param\");\n }\n for (Object[] objs:params){\n for (int index = 0; index < paramLength; index++) {\n if (objs[index] == null) {\n ps.setNull(index, Types.VARCHAR);\n continue;\n }\n ps.setObject(index + 1, objs[index]);\n }\n ps.addBatch();\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}", "public class CachedExecutor extends AbstractExecutor {\n\n private Cache<String, Object> cache;\n\n private SqlExecutor executor;\n\n public CachedExecutor(SqlExecutor executor, CacheEntity entity) {\n this.executor = executor;\n this.cache = QueryCacheFactory.getInstance().createCache(entity);\n }\n\n /**\n * 缓存查询结果的执行器\n * @param sql\n * @param rshandler\n * @param params\n * @param <T>\n * @return\n */\n @Override\n public <T> T query(String sql, ResultSetHandler<T> rshandler, Object[] params) {\n String key = hybridInput(sql, params);\n T result = (T) cache.get(key);\n if (result != null) {\n return result;\n }\n result = executor.query(sql, rshandler, params);\n cache.set(key,result);\n return result;\n }\n\n @Override\n public int alter(String sql, Object[] params) {\n return executor.alter(sql, params);\n }\n\n @Override\n public void alterBatch(String sql, Object[][] params) {\n executor.alterBatch(sql,params);\n }\n\n @Override\n public void rollback() {\n executor.rollback();\n }\n\n @Override\n public void close() {\n executor.close();\n }\n\n /**\n * 将sql和参数混合得到hash值\n * @param sql\n * @param params\n * @return\n */\n public String hybridInput(String sql, Object[] params) {\n StringBuffer buffer = new StringBuffer();\n buffer.append(sql);\n for (Object obj : params) {\n buffer.append(CodecUtils.sha1Obj(obj));\n }\n return CodecUtils.sha1(buffer.toString());\n }\n}", "public class SqlExecutor extends AbstractExecutor{\n\n private Connection conn;\n\n public SqlExecutor(Connection conn){\n this.conn = conn;\n }\n\n /**\n *\n * @param sql\n * @param rshandler\n * @param params\n * @param <T>\n * @return\n */\n @Override\n public <T> T query(String sql, ResultSetHandler<T> rshandler, Object[] params) {\n PreparedStatement ps = null;\n ResultSet rs = null;\n try {\n ps = prepareStatement(conn, sql);\n fillStatement(ps,params);\n rs = ps.executeQuery();\n T result = rshandler.handle(rs);\n return result;\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n\n /**\n * 提供connection的修改操作\n * @param sql\n * @param params\n * @return\n */\n @Override\n public int alter(String sql,Object[] params){\n PreparedStatement ps = null;\n ResultSet rs = null;\n try {\n ps = prepareStatement(conn, sql);\n fillStatement(ps,params);\n return ps.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n ConnectionUtils.rollBack(conn);\n return -1;\n }\n }\n\n @Override\n public void rollback(){\n ConnectionUtils.close(conn);\n }\n\n @Override\n public void close(){\n ConnectionUtils.close(conn);\n }\n\n /**\n * 提供connection的批量修改操作\n * @param sql\n * @param params\n */\n @Override\n public void alterBatch(String sql,Object[][]params){\n PreparedStatement ps = null;\n ResultSet rs = null;\n try {\n ConnectionUtils.beginTransaction(conn);\n ps = batchPrepareStatement(conn, sql);\n fillStatement(ps,params);\n ps.executeBatch();\n ConnectionUtils.commit(conn);\n return ;\n } catch (SQLException e) {\n e.printStackTrace();\n ConnectionUtils.rollBack(conn);\n }finally {\n ConnectionUtils.close(rs);\n ConnectionUtils.close(ps);\n ConnectionUtils.close(conn);\n }\n }\n\n\n public static void main(String[] args) throws SQLException {\n ConnConfig.config(\"root\", \"123456\",\n \"jdbc:mysql://localhost:3306/shopping?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false\", \"com.mysql.jdbc.Driver\");\n DataSource dataSource = DBCPoolFactory.newCustomDBCPool(PoolConfig.config(200, 50, 5, 3 * 1000L));\n final SqlExecutor executor = new SqlExecutor(dataSource.getConnection());\n System.out.println(executor);\n ResultSetHandler<Integer> handler = new BaseTypeResultSetHandler(Integer.class);\n Integer count = executor.query(\"select count(1) from user where username = ?\", handler, new Object[]{\"code4j\"});\n System.out.println(count);\n// int result = executor.alter(connection,\"insert into user values(?,?,?,?,?)\",10,\"laisbfdsfk\",\"583110127\",\"13652212569\",30);\n// System.out.println(\"end \"+result);\n }\n}", "public class DefaultDBSession extends DBSessionAdapter {\n\n private SqlMapCacheFactory factory;\n\n private AbstractExecutor executor;\n\n private Configuration configuration;\n\n public DefaultDBSession(Configuration configuration, AbstractExecutor executor) {\n this.executor = executor;\n this.configuration = configuration;\n this.factory = SqlMapCacheFactory.getInstance();\n }\n\n @Override\n public <T> T selectOne(String bind, Class<T> clazz, Object... parameters) {\n List<T> list = this.selectList(bind, clazz, parameters);\n if (CollectionUtils.isEmpty(list)) {\n return null;\n }\n return list.get(0);\n }\n\n @Override\n public <T> T selectOne(String bindOrSql, Class<T> clazz, Map<String, Object> parameter) {\n return super.selectOne(bindOrSql, clazz, parameter);\n }\n\n @Override\n public <E> List<E> selectList(String bind, Class<E> clazz, Object... parameters) {\n SqlEntity entity = genEntity(bind,parameters);\n List<E> list = executor.query(entity.getPreparedSql(),\n new BeanListResultSetHadler<>(clazz),\n CollectionUtils.gatherMapListsValues(entity.getParams()));\n return list;\n }\n\n @Override\n public <E> List<E> selectList(String bind, Class<E> clazz, Map<String, Object> parameters) {\n Object[] params = CollectionUtils.gatherMapListsValues(parameters);\n SqlEntity entity = genEntity(bind,params);\n List<E> list = executor.query(entity.getPreparedSql(),\n new BeanListResultSetHadler<>(clazz),params);\n return list;\n }\n\n @Override\n public List<Map<String, Object>> selectMap(String bind, Object... parameters) {\n SqlEntity entity = genEntity(bind,parameters);\n List<Map<String, Object>> list = executor.query(entity.getPreparedSql(), new MapResultHandler(),\n CollectionUtils.gatherMapListsValues(entity.getParams()));\n return list;\n }\n\n @Override\n public List<Map<String, Object>> selectMap(String bind, Map<String, Object> parameters) {\n Object[] params = CollectionUtils.gatherMapListsValues(parameters);\n SqlEntity entity = genEntity(bind,params);\n List<Map<String, Object>> list = executor.query(entity.getPreparedSql(), new MapResultHandler(),params);\n return list;\n }\n\n @Override\n public int selectCount(String bind, Object... parameters) {\n SqlEntity entity = genEntity(bind,parameters);\n Integer count = executor.query(entity.getPreparedSql(),\n new BaseTypeResultSetHandler<>(Integer.class),\n CollectionUtils.gatherMapListsValues(entity.getParams()));\n return count;\n }\n\n @Override\n public int selectCount(String bind, Map<String, Object> parameters) {\n Object[] params = CollectionUtils.gatherMapListsValues(parameters);\n SqlEntity entity = genEntity(bind,params);\n Integer count = executor.query(entity.getPreparedSql(),\n new BaseTypeResultSetHandler<>(Integer.class),params);\n return count;\n }\n\n @Override\n public int update(String bind, Object... parameters) {\n SqlEntity entity = genEntity(bind,parameters);\n return executor.alter(entity.getPreparedSql(),\n CollectionUtils.gatherMapListsValues(entity.getParams()));\n }\n\n @Override\n public int update(String bind, Map<String, Object> parameter) {\n return super.update(bind, parameter);\n }\n\n @Override\n public int delete(String bind, Object... parameter) {\n return update(bind,parameter);\n }\n\n @Override\n public int delete(String bindOrSql, Map<String, Object> parameter) {\n return super.delete(bindOrSql, parameter);\n }\n\n @Override\n public int insert(String bind, Object... parameter) {\n return update(bind,parameter);\n }\n\n @Override\n public int insert(String bindOrSql, Map<String, Object> parameter) {\n return super.insert(bindOrSql, parameter);\n }\n\n @Override\n public Configuration getConfiguration() {\n return configuration;\n }\n\n @Override\n public void close() {\n executor.close();\n }\n\n @Override\n public void rollback() {\n executor.rollback();\n }\n\n private SqlEntity genEntity(String bind, Object... parameters){\n if (!ReflectUtils.isUnifiedCollection(parameters, Parameter.class)){\n throw new IllegalArgumentException(\"All these paramters's type should be instanceof Parameter or null.\");\n }\n String[] tokens = bind.split(BIND_SEPARATOR);\n String interfaceName = tokens[0];\n String methodName = tokens[1];\n SqlBuilder builder = new SqlBuilder();\n SqlMapCache cache = factory.createCache(configuration.getCacheEntity());\n if (cache.isHit(interfaceName,methodName,parameters)) {\n SqlEntity entity = cache.getSqlEntity(interfaceName,methodName,parameters);\n builder.buildEntity(entity);\n }else{\n for (int index=0;index<parameters.length;index++){\n Parameter param = (Parameter) parameters[index];\n builder.buildParams(param.getValue(),param.getName());\n }\n }\n SqlEntity entity = new SqlEntity();\n entity.setParams(builder.getParameters());\n entity.setBinder(bind);\n //js解析会花较多时间\n configuration.parseMappedSql(entity);\n SqlEntity se = configuration.getMappedSql(interfaceName\n , methodName,entity.getParams().values());\n return builder.buildEntity(se);\n }\n}", "public class MapperDBSession extends DBSessionAdapter {\n\n private ProxyCacheFactory factory;\n\n private Configuration configuration;\n\n private AbstractExecutor executor;\n\n public MapperDBSession(Configuration configuration, AbstractExecutor executor) {\n this.executor = executor;\n this.configuration = configuration;\n factory = ProxyCacheFactory.getInstance();\n }\n\n @Override\n public <T> T selectOne(String sql, Class<T> clazz, Object... parameters) {\n return executor.query(sql,new BeanResultSetHadler<T>(clazz),parameters);\n }\n\n @Override\n public <E> List<E> selectList(String sql, Class<E> clazz, Object... parameters) {\n List<E> list = executor.query(sql, new BeanListResultSetHadler<>(clazz), parameters);\n return list;\n }\n\n @Override\n public int selectCount(String sql, Object... parameters) {\n return executor.query(sql, new BaseTypeResultSetHandler<>(Integer.class), parameters);\n }\n\n @Override\n public List<Map<String, Object>> selectMap(String sql, Object... parameters) {\n List<Map<String, Object>> list = executor.query(sql, new MapResultHandler(), parameters);\n return list;\n }\n\n @Override\n public int update(String sql, Object... parameter) {\n return executor.alter(sql, parameter);\n }\n\n @Override\n public int delete(String sql, Object... parameter) {\n return update(sql, parameter);\n }\n\n @Override\n public int insert(String sql, Object... parameter) {\n return update(sql, parameter);\n }\n\n @Override\n public <T> T getMapper(Class<T> clazz) {\n ProxyCache proxyCache = factory.createCache(configuration.getCacheEntity());\n if (proxyCache.isHit(clazz)){\n return (T) proxyCache.get(clazz);\n }\n MapperProxyFactory<T> mapperProxyFactory = new MapperProxyFactory(configuration,clazz);\n return mapperProxyFactory.newInstance(this);\n }\n\n @Override\n public Configuration getConfiguration() {\n return configuration;\n }\n\n @Override\n public void close() {\n executor.close();\n }\n\n @Override\n public void rollback() {\n executor.rollback();\n }\n}" ]
import org.easyarch.slardar.entity.CacheEntity; import org.easyarch.slardar.jdbc.exec.AbstractExecutor; import org.easyarch.slardar.jdbc.exec.CachedExecutor; import org.easyarch.slardar.jdbc.exec.SqlExecutor; import org.easyarch.slardar.session.impl.DefaultDBSession; import org.easyarch.slardar.session.impl.MapperDBSession; import java.sql.SQLException;
package org.easyarch.slardar.session; /** * Description : * Created by xingtianyu on 16-12-29 * 上午12:11 * description: */ public class DBSessionFactory { private Configuration configuration; public DBSessionFactory(Configuration configuration){ this.configuration = configuration; } public DBSession newDefaultSession(){ return new DefaultDBSession(configuration,getExecutor()); } public DBSession newDelegateSession(){ return new MapperDBSession(configuration,getExecutor()); } private AbstractExecutor getExecutor(){ AbstractExecutor executor = null; CacheEntity entity = configuration.getCacheEntity(); try { if (entity.isEnable()){
executor = new CachedExecutor(new SqlExecutor(
3
maximeAudrain/jenerate
org.jenerate/src/java/org/jenerate/internal/ui/dialogs/factory/impl/CompareToDialogFactory.java
[ "public interface CommandIdentifier {\r\n\r\n /**\r\n * @return the unique string identifier of a command\r\n */\r\n String getIdentifier();\r\n\r\n}\r", "public enum MethodsGenerationCommandIdentifier implements CommandIdentifier {\r\n\r\n EQUALS_HASH_CODE(\"org.jenerate.commands.GenerateEqualsHashCodeCommand\"),\r\n TO_STRING(\"org.jenerate.commands.GenerateToStringCommand\"),\r\n COMPARE_TO(\"org.jenerate.commands.GenerateCompareToCommand\");\r\n\r\n private static final Map<String, MethodsGenerationCommandIdentifier> IDENTIFIERS = new HashMap<String, MethodsGenerationCommandIdentifier>();\r\n\r\n static {\r\n for (MethodsGenerationCommandIdentifier userActionIdentifier : MethodsGenerationCommandIdentifier.values()) {\r\n IDENTIFIERS.put(userActionIdentifier.getIdentifier(), userActionIdentifier);\r\n }\r\n }\r\n\r\n private final String identifier;\r\n\r\n private MethodsGenerationCommandIdentifier(String identifier) {\r\n this.identifier = identifier;\r\n }\r\n\r\n @Override\r\n public String getIdentifier() {\r\n return identifier;\r\n }\r\n\r\n public static MethodsGenerationCommandIdentifier getUserActionIdentifierFor(String identifier) {\r\n if (!IDENTIFIERS.containsKey(identifier)) {\r\n throw new IllegalArgumentException();\r\n }\r\n return IDENTIFIERS.get(identifier);\r\n }\r\n\r\n}\r", "public interface DialogStrategyManager {\r\n\r\n /**\r\n * Get the {@link DialogStrategy} for the given parameters\r\n * \r\n * @param commandIdentifier the unique identifier of a command\r\n * @param strategyIdentifier the unique identifier of a strategy\r\n * @return the {@link DialogStrategy} for the provided parameters\r\n * @throws IllegalStateException if no {@link DialogStrategy} could be found for a provided parameters\r\n */\r\n <U extends MethodGenerationData> DialogStrategy<U> getDialogStrategy(CommandIdentifier commandIdentifier,\r\n StrategyIdentifier strategyIdentifier);\r\n\r\n}\r", "public interface PreferencesManager {\r\n\r\n /**\r\n * Gets the current value for a specific preference\r\n * \r\n * @param preference the preference to get the value from\r\n * @return the value for this preference\r\n */\r\n <T> T getCurrentPreferenceValue(PluginPreference<T> preference);\r\n\r\n}\r", "public interface DialogFactoryHelper {\r\n\r\n /**\r\n * Check if the method specified with methodName and methodParameterType parameters is overridden and concrete in a\r\n * subclass of the original declared class, and that subclass is a superclass of objectClass.\r\n * \r\n * @param objectClass the class for which the code generation is in effect\r\n * @param methodName the name of the method to check\r\n * @param methodParameterTypes the fully qualified typenames of the method parameters to check\r\n * @param originalClassFullyQualifiedName the name of the original class where the method is implemented\r\n * @return {@code true} if the method is overridden in the superclass, {@code false} otherwise\r\n * @throws JavaModelException if a problem occurs\r\n */\r\n boolean isOverriddenInSuperclass(IType objectClass, String methodName, String[] methodParameterTypes,\r\n String originalClassFullyQualifiedName) throws JavaModelException;\r\n\r\n /**\r\n * Gets the fields of a class identifier by the {@link IType} objectClass.\r\n * \r\n * @param objectClass the class where to retrieve the fields from\r\n * @param preferencesManager the preference manager\r\n * @return all fields to be used by the {@link DialogFactory}\r\n * @throws JavaModelException if a problem occurs retrieving the class fields\r\n */\r\n IField[] getObjectClassFields(IType objectClass, PreferencesManager preferencesManager) throws JavaModelException;\r\n\r\n /**\r\n * @return the current {@link IDialogSettings}\r\n */\r\n IDialogSettings getDialogSettings();\r\n\r\n /**\r\n * Get all the positions where generated code can be inserted in a provided java class.\r\n * \r\n * @param objectClass the class where generated code will be inserted\r\n * @param excludedMethods the method to exclude from the possible position of insertion\r\n * @return the map of String insertion labels -> insertion positions\r\n * @throws JavaModelException if a problem occurs while computing the insertion positions\r\n */\r\n LinkedHashMap<String, IJavaElement> getInsertPositions(IType objectClass, Set<IMethod> excludedMethods)\r\n throws JavaModelException;\r\n}\r", "public class OrderableFieldDialogImpl<U extends MethodGenerationData> extends FieldDialogImpl<U> {\n\n private Button upButton;\n private Button downButton;\n\n public OrderableFieldDialogImpl(CommandIdentifier commandIdentifier, Shell parentShell, String dialogTitle,\n IField[] fields, LinkedHashSet<StrategyIdentifier> possibleStrategies, boolean disableAppendSuper,\n PreferencesManager preferencesManager, IDialogSettings dialogSettings,\n LinkedHashMap<String, IJavaElement> insertPositions, DialogStrategyManager dialogStrategyManager) {\n super(commandIdentifier, parentShell, dialogTitle, fields, possibleStrategies, disableAppendSuper,\n preferencesManager, dialogSettings, insertPositions, dialogStrategyManager);\n }\n\n @Override\n public void create() {\n super.create();\n\n Table fieldTable = fieldViewer.getTable();\n fieldTable.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(SelectionEvent e) {\n handleTableSelectionChanged();\n }\n });\n }\n\n private void handleTableSelectionChanged() {\n Table fieldTable = fieldViewer.getTable();\n TableItem[] items = fieldTable.getSelection();\n boolean validSelection = items != null && items.length > 0;\n boolean enableUp = validSelection;\n boolean enableDown = validSelection;\n if (validSelection) {\n int indices[] = fieldTable.getSelectionIndices();\n int max = fieldTable.getItemCount();\n enableUp = indices[0] != 0;\n enableDown = indices[indices.length - 1] < max - 1;\n }\n upButton.setEnabled(enableUp);\n downButton.setEnabled(enableDown);\n }\n\n @Override\n protected void addButtons(final Composite buttonComposite) {\n super.addButtons(buttonComposite);\n\n GridData data;\n upButton = new Button(buttonComposite, SWT.PUSH);\n upButton.setText(\"&Up\");\n upButton.setEnabled(false);\n upButton.addListener(SWT.Selection, new Listener() {\n\n @Override\n public void handleEvent(Event event) {\n moveSelectionUp();\n handleTableSelectionChanged();\n }\n });\n data = new GridData(GridData.FILL_HORIZONTAL);\n upButton.setLayoutData(data);\n\n downButton = new Button(buttonComposite, SWT.PUSH);\n downButton.setText(\"Do&wn\");\n downButton.setEnabled(false);\n downButton.addListener(SWT.Selection, new Listener() {\n\n @Override\n public void handleEvent(Event event) {\n moveSelectionDown();\n handleTableSelectionChanged();\n }\n });\n data = new GridData(GridData.FILL_HORIZONTAL);\n downButton.setLayoutData(data);\n }\n\n /**\n * Move the current selection in the field list up.\n */\n private void moveSelectionUp() {\n Table builderTable = fieldViewer.getTable();\n int indices[] = builderTable.getSelectionIndices();\n int newSelection[] = new int[indices.length];\n for (int i = 0; i < indices.length; i++) {\n int index = indices[i];\n if (index > 0) {\n move(builderTable.getItem(index), index - 1);\n newSelection[i] = index - 1;\n }\n }\n builderTable.setSelection(newSelection);\n }\n\n /**\n * Move the current selection in the field list down.\n */\n private void moveSelectionDown() {\n Table builderTable = fieldViewer.getTable();\n int indices[] = builderTable.getSelectionIndices();\n if (indices.length < 1) {\n return;\n }\n int newSelection[] = new int[indices.length];\n int max = builderTable.getItemCount() - 1;\n for (int i = indices.length - 1; i >= 0; i--) {\n int index = indices[i];\n if (index < max) {\n move(builderTable.getItem(index), index + 1);\n newSelection[i] = index + 1;\n }\n }\n builderTable.setSelection(newSelection);\n }\n\n /**\n * Moves an entry in the field table to the given index.\n */\n private void move(TableItem item, int index) {\n Object data = item.getData();\n boolean checked = fieldViewer.getChecked(data);\n item.dispose();\n fieldViewer.insert(data, index);\n fieldViewer.setChecked(data, checked);\n }\n}", "public interface JavaInterfaceCodeAppender {\r\n\r\n boolean isImplementedOrExtendedInSupertype(final IType objectClass, final String interfaceName) throws Exception;\r\n\r\n boolean isImplementedInSupertype(final IType objectClass, final String interfaceName) throws JavaModelException;\r\n\r\n void addSuperInterface(final IType objectClass, final String interfaceName)\r\n throws JavaModelException, InvalidInputException, MalformedTreeException;\r\n\r\n}\r" ]
import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Set; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.swt.widgets.Shell; import org.jenerate.internal.domain.data.CompareToGenerationData; import org.jenerate.internal.domain.identifier.CommandIdentifier; import org.jenerate.internal.domain.identifier.StrategyIdentifier; import org.jenerate.internal.domain.identifier.impl.MethodsGenerationCommandIdentifier; import org.jenerate.internal.manage.DialogStrategyManager; import org.jenerate.internal.manage.PreferencesManager; import org.jenerate.internal.ui.dialogs.factory.DialogFactory; import org.jenerate.internal.ui.dialogs.factory.DialogFactoryHelper; import org.jenerate.internal.ui.dialogs.impl.OrderableFieldDialogImpl; import org.jenerate.internal.util.JavaInterfaceCodeAppender;
package org.jenerate.internal.ui.dialogs.factory.impl; /** * {@link DialogFactory} implementation for the {@link CompareToDialog} * * @author maudrain */ public class CompareToDialogFactory extends AbstractDialogFactory<CompareToGenerationData> { private JavaInterfaceCodeAppender javaInterfaceCodeAppender; /** * Constructor * * @param dialogFactoryHelper the dialog factory helper * @param preferencesManager the preference manager * @param javaInterfaceCodeAppender the java interface code appender */
public CompareToDialogFactory(DialogStrategyManager dialogStrategyManager, DialogFactoryHelper dialogFactoryHelper,
2
FlyingPumba/SoundBox
src/com/arcusapp/soundbox/adapter/FoldersActivityAdapter.java
[ "public class SoundBoxApplication extends Application {\n private static Context appContext;\n\n public static final String ACTION_MAIN_ACTIVITY = \"com.arcusapp.soundbox.action.MAIN_ACTIVITY\";\n public static final String ACTION_FOLDERS_ACTIVITY = \"com.arcusapp.soundbox.action.FOLDERS_ACTIVITY\";\n public static final String ACTION_SONGSLIST_ACTIVITY = \"com.arcusapp.soundbox.action.SONGSLIST_ACTIVITY\";\n public static final String ACTION_ABOUT_ACTIVITY = \"com.arcusapp.soundbox.action.ABOUT_ACTIVITY\";\n public static final String ACTION_MEDIA_PLAYER_SERVICE = \"com.arcusapp.soundbox.action.MEDIA_PLAYER_SERVICE\";\n\n private static List<File> sdCards;\n\n private static int mForegroundActivities = 0;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n appContext = getApplicationContext();\n searchForSDCards();\n }\n\n public static Context getContext() {\n return appContext;\n }\n\n public static void notifyForegroundStateChanged(boolean inForeground) {\n int old = mForegroundActivities;\n if (inForeground) {\n mForegroundActivities++;\n } else {\n mForegroundActivities--;\n }\n\n if (old == 0 || mForegroundActivities == 0) {\n Intent intent = new Intent();\n intent.setAction(MediaPlayerService.CHANGE_FOREGROUND_STATE);\n intent.putExtra(MediaPlayerService.NOW_IN_FOREGROUND, mForegroundActivities == 0);\n appContext.startService(intent);\n }\n\n }\n\n public static List<File> getSDCards() {\n return sdCards;\n }\n\n public static List<File> getDefaultUserDirectoriesOptions() {\n List<File> defaultUserOptions = new ArrayList<File>();\n\n if(Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) {\n File musicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);\n defaultUserOptions.add(musicDirectory);\n }\n defaultUserOptions.addAll(sdCards);\n return defaultUserOptions;\n }\n\n private void searchForSDCards() {\n sdCards = new ArrayList<File>();\n File primarysdCard = Environment.getExternalStorageDirectory();\n String[] sdCardDirectories = DirectoryHelper.getStorageDirectories();\n String[] othersdCardDirectories = DirectoryHelper.getOtherStorageDirectories();\n\n sdCards.add(primarysdCard);\n for (String s : sdCardDirectories) {\n File directory = new File(s);\n if (!sdCards.contains(directory)) {\n sdCards.add(directory);\n }\n }\n for (String s : othersdCardDirectories) {\n File directory = new File(s);\n if (!sdCards.contains(directory)) {\n sdCards.add(directory);\n }\n }\n }\n}", "public class FoldersActivity extends Activity implements View.OnClickListener {\n\n private TextView txtDir;\n private ListView myListView;\n private FoldersActivityAdapter myAdapter;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_folders);\n\n txtDir = (TextView) findViewById(R.id.txtDir);\n myAdapter = new FoldersActivityAdapter(this, txtDir);\n myAdapter.registerDataSetObserver(new DataSetObserver() {\n @Override\n public void onChanged() {\n super.onChanged();\n\n if (myAdapter.getCount() > 0)\n myListView.setSelection(0);\n }\n });\n\n myListView = (ListView) findViewById(R.id.foldersActivityList);\n myListView.setAdapter(myAdapter);\n myListView.setOnItemClickListener(new OnItemClickListener() {\n\n @Override\n public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {\n myAdapter.onItemClick(position);\n }\n });\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n //getMenuInflater().inflate(R.menu.folders, menu);\n return true;\n }\n\n @Override\n public void onBackPressed() {\n myAdapter.backPressed();\n }\n\n @Override\n public void onClick(View v) {\n if (v.getId() == R.id.btnHomeFoldersActivity) {\n finish();\n } else if (v.getId() == R.id.btnPlayFolder) {\n myAdapter.playCurrentDirectory();\n }\n }\n}", "public class MediaProvider {\n\n private OnlyDirsFilter myFilter;\n private File defaultDirectory;\n private Uri defaultDirectoryUri;\n\n private Cursor myCursor;\n\n public MediaProvider() {\n myFilter = new OnlyDirsFilter();\n\n defaultDirectory = SoundBoxApplication.getSDCards().get(0);\n defaultDirectoryUri = MediaStore.Audio.Media.getContentUriForPath(defaultDirectory.getPath());\n }\n\n /**\n * Returns the id of all the Songs in the MediaStore.\n * \n * @return list with the ids\n */\n public List<String> getAllSongs() {\n List<String> songs = new ArrayList<String>();\n\n String[] cursorProjection = new String[] { MediaStore.Audio.Media._ID };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 \";\n String sortOrder = MediaStore.Audio.Media.TITLE;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, cursorProjection, selection, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return songs;\n }\n\n /**\n * Returns the name ({@linkplain MediaStore.Audio.Artists.ARTIST}) of all the Artists in the MediaStore.\n * \n * @return list with the names\n */\n public List<String> getAllArtists() {\n List<String> artists = new ArrayList<String>();\n\n String[] projection = { \"DISTINCT \" + MediaStore.Audio.Artists.ARTIST };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.ARTIST + \" not null \";\n String sortOrder = MediaStore.Audio.Artists.ARTIST;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n artists.add(myCursor.getString(0));\n }\n myCursor.close();\n return artists;\n }\n\n /**\n * Returns the name ({@linkplain MediaStore.Audio.Albums.ALBUM}) of all the Albums of the specified Artist in the MediaStore.\n * \n * @param artist the name of the Artist ({@linkplain MediaStore.Audio.Artists.ARTIST})\n * @return list with the names\n */\n public List<String> getAlbumsFromArtist(String artist) {\n List<String> albums = new ArrayList<String>();\n\n String[] projection = { \"DISTINCT \" + MediaStore.Audio.Artists.Albums.ALBUM };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.ARTIST + \" = ?\";\n String sortOrder = MediaStore.Audio.Artists.Albums.ALBUM;\n String[] selectionArgs = new String[] { artist };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n albums.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return albums;\n }\n\n /**\n * Returns the id ({@linkplain MediaStore.Audio.Media._ID}) of all the Songs of the specified Artist in the MediaStore.\n * \n * @param artist the name of the Artist ({@linkplain MediaStore.Audio.Artists.ARTIST})\n * @return list with the ids\n */\n public List<String> getSongsFromArtist(String artist) {\n List<String> ids = new ArrayList<String>();\n\n String[] projection = { MediaStore.Audio.Media._ID };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.ARTIST + \" = ?\";\n String sortOrder = MediaStore.Audio.Media.TITLE;\n String[] selectionArgs = new String[] { artist };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n ids.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return ids;\n }\n\n /**\n * Returns the id ({@linkplain MediaStore.Audio.Media._ID}) of all the Songs of the specified Album in the MediaStore.\n * \n * @param album the name of the Album ({@linkplain MediaStore.Audio.Albums.ALBUM})\n * @return list with the ids\n */\n public List<String> getSongsFromAlbum(String album) {\n List<String> ids = new ArrayList<String>();\n\n String[] projection = { MediaStore.Audio.Media._ID };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Artists.Albums.ALBUM + \" = ?\";\n String sortOrder = MediaStore.Audio.Media.TITLE;\n String[] selectionArgs = new String[] { album };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n ids.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return ids;\n }\n\n /**\n * Returns a list of PlaylistEntries for all the Playlists in the MediaStore.\n * \n * @return a list of PlaylistEntries. The value associated is the name of the Playlist ({@linkplain MediaStore.Audio.Playlists.NAME})\n */\n public List<PlaylistEntry> getAllPlayLists() {\n List<PlaylistEntry> playLists = new ArrayList<PlaylistEntry>();\n\n String[] projection = new String[] { MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, null, null, null);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n playLists.add(new PlaylistEntry(myCursor.getString(0),\n myCursor.getString(1)));\n }\n\n Collections.sort(playLists);\n\n myCursor.close();\n return playLists;\n }\n\n /**\n * Returns the id ({@linkplain MediaStore.Audio.Playlists.Members.AUDIO_ID}) of all the Songs of the specified Playlist in the MediaStore.\n * \n * @param playListID ({@linkplain MediaStore.Audio.Playlists._ID})\n * @return list with the ids\n */\n public List<String> getSongsFromPlaylist(String playListID) {\n List<String> ids = new ArrayList<String>();\n\n Uri specialUri = MediaStore.Audio.Playlists.Members.getContentUri(\"external\", Integer.parseInt(playListID));\n String[] projection = { MediaStore.Audio.Playlists.Members.AUDIO_ID, MediaStore.Audio.Playlists.Members.TITLE };\n String sortOrder = MediaStore.Audio.Playlists.Members.TITLE;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), specialUri, projection, null, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n ids.add(myCursor.getString(0));\n }\n\n myCursor.close();\n return ids;\n }\n\n public Song getSongFromID(String songID) {\n Song song;\n List<String> values = new ArrayList<String>();\n\n String[] projection = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,\n MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DATA };\n\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Media._ID + \" = ?\";\n String[] selectionArgs = new String[] { songID };\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, projection, selection, selectionArgs, null);\n myCursor = cl.loadInBackground();\n\n try {\n myCursor.moveToNext();\n for (int i = 0; i < myCursor.getColumnCount(); i++)\n values.add(myCursor.getString(i));\n if (values.size() > 0) {\n song = new Song(values.get(0), values.get(1), values.get(2), values.get(3), values.get(4));\n } else {\n song = new Song();\n }\n } catch (Exception ignored) {\n song = new Song();\n }\n\n myCursor.close();\n return song;\n }\n\n /**\n * Returns a list of SongEntries for the specified Songs.\n * \n * @param songsID list of ids ({@linkplain MediaStore.Audio.Media._ID})\n * @param projection one key from {@linkplain MediaStore.Audio.Media} to associate on the SongEntry's value\n * @return a list of SongEntries\n */\n public List<SongEntry> getValueFromSongs(List<String> songsID, String projection) {\n List<SongEntry> songs = new ArrayList<SongEntry>();\n\n String[] ids = new String[songsID.size()];\n ids = songsID.toArray(ids);\n\n String[] cursorProjection = new String[] { MediaStore.Audio.Media._ID, projection, MediaStore.Audio.Media.DATA };\n\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \" + MediaStore.Audio.Media._ID + \" IN (\";\n for (int i = 0; i < songsID.size() - 1; i++)\n {\n selection += \"?, \";\n }\n selection += \"?)\";\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), defaultDirectoryUri, cursorProjection, selection, ids, null);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(new SongEntry(myCursor.getString(0), myCursor.getString(1)));\n }\n\n Collections.sort(songs);\n\n myCursor.close();\n return songs;\n }\n\n /**\n * Returns the sub directories of a given directory\n * \n * @param directory the parent folder ({@linkplain File})\n * @return list with the subdirs\n */\n public List<File> getSubDirsInAFolder(File directory) {\n List<File> dirs = new ArrayList<File>();\n\n // list the directories inside the folder\n File list[] = directory.listFiles(myFilter);\n\n if (list != null) {\n\n Collections.addAll(dirs, list);\n\n // sort the directories alphabetically\n Collections.sort(dirs, new SortFileName());\n }\n return dirs;\n }\n\n /**\n * Returns a list of SongEntries for the Songs in the specified directory.\n * \n * @param directory the directory in which to search\n * @param projection one key from {@linkplain MediaStore.Audio.Media} to associate on the SongEntry's value\n * @return a list of SongEntries\n */\n public List<SongEntry> getSongsInAFolder(File directory, String projection) {\n List<SongEntry> songs = new ArrayList<SongEntry>();\n String folder = directory.getPath();\n\n String[] cursorProjection = new String[] { MediaStore.Audio.Media._ID, projection };\n String selection = MediaStore.Audio.Media.IS_MUSIC + \" != 0 AND \"\n + \"SUBSTR(\" + MediaStore.Audio.Media.DATA + \",0 , LENGTH('\" + folder + \"')+1) = '\" + folder + \"' AND \"\n + \"SUBSTR(\" + MediaStore.Audio.Media.DATA + \",LENGTH('\" + folder + \"')+1, 200) LIKE '/%.mp3' AND \"\n + \"SUBSTR(\" + MediaStore.Audio.Media.DATA + \",LENGTH('\" + folder + \"')+1, 200) NOT LIKE '/%/%.mp3'\";\n\n String sortOrder = MediaStore.Audio.Media.TITLE;\n\n CursorLoader cl = new CursorLoader(SoundBoxApplication.getContext(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cursorProjection, selection, null, sortOrder);\n myCursor = cl.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(new SongEntry(myCursor.getString(0), myCursor.getString(1)));\n }\n\n CursorLoader cl2 = new CursorLoader(SoundBoxApplication.getContext(), MediaStore.Audio.Media.INTERNAL_CONTENT_URI, cursorProjection, selection, null, sortOrder);\n myCursor = cl2.loadInBackground();\n\n while (myCursor.moveToNext()) {\n songs.add(new SongEntry(myCursor.getString(0), myCursor.getString(1)));\n }\n\n myCursor.close();\n return songs;\n }\n\n /**\n * Class to sort the files based on its names (alphabetically)\n */\n private class SortFileName implements Comparator<File> {\n @Override\n public int compare(File f1, File f2) {\n return f1.getName().compareTo(f2.getName());\n }\n }\n\n /**\n * Class to filter the Files that are not directories.\n */\n private class OnlyDirsFilter implements FileFilter {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.isDirectory() && !isProtected(pathname);\n }\n\n private boolean isProtected(File path) {\n return (!path.canRead() && !path.canWrite());\n }\n\n }\n}", "public class SongEntry extends MediaEntry {\n\n public SongEntry(String id, String value) {\n super(id, value);\n }\n}", "public class MediaEntryHelper<T extends MediaEntry> {\n public List<String> getValues(List<T> list) {\n List<String> values = new ArrayList<String>();\n for (MediaEntry me : list) {\n values.add(me.getValue());\n }\n\n return values;\n }\n\n public List<String> getIDs(List<T> list) {\n List<String> ids = new ArrayList<String>();\n for (MediaEntry me : list) {\n ids.add(me.getID());\n }\n\n return ids;\n }\n}" ]
import com.arcusapp.soundbox.activity.FoldersActivity; import com.arcusapp.soundbox.data.MediaProvider; import com.arcusapp.soundbox.model.SongEntry; import com.arcusapp.soundbox.util.MediaEntryHelper; import java.io.File; import java.util.ArrayList; import java.util.List; import android.provider.MediaStore; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.arcusapp.soundbox.R; import com.arcusapp.soundbox.SoundBoxApplication;
/* * SoundBox - Android Music Player * Copyright (C) 2013 Iván Arcuschin Moreno * * This file is part of SoundBox. * * SoundBox is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * SoundBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SoundBox. If not, see <http://www.gnu.org/licenses/>. */ package com.arcusapp.soundbox.adapter; public class FoldersActivityAdapter extends BaseAdapter { private FoldersActivity mActivity; private TextView txtCurrentDirectory; private List<File> subDirs;
private List<SongEntry> songs;
3
4FunApp/4Fun
client/FourFun/app/src/main/java/com/joker/fourfun/ui/MovieDetailActivity.java
[ "public class Constants {\n public static final String MAIN_ACTIVITY_BUNDLE = \"main_bundle\";\n public static final String MEDIA_BUNDLE = \"media_bundle\";\n public static final String MOVIE_BUNDLE = \"movie_bundle\";\n public static final String PICTURE_BUNDLE = \"picture_bundle\";\n public static final String PICTURE_DETAILS_BUNDLE = \"picture_details_bundle\";\n public static final String ZHIHU_IMG = \"zhihu_img\";\n public static final String PICTURE_ONE_IMG = \"picture_one\";\n public static final String PICTURE_DETAILS_IMG = \"picture_details_one\";\n public static final String MOVIE_DETAILS_BEAN = \"movie_detail_bean\";\n public static final String PICTURE_DETAILS_ONE_POSITION = \"picture_one_details\";\n public static final String TRANSIT_PIC = \"transit_pic\";\n\n // 注册登录状态码\n public static final int REGISTER_SUCCESS_CODE = 1050;\n public static final int LOGIN_SUCCESS_CODE = 1051;\n\n // 注册登录状态信息\n public static final String REGISTER_SUCCESS_MESSAGE = \"注册成功\";\n public static final String LOGIN_SUCCESS_MESSAGE = \"登录成功\";\n\n // 正则\n // 非空,非空格\n public static final String REGEXP_EMPTY = \"[^\\\\s]{1,}\";\n // 邮箱\n public static final String REGEXP_EMAIL = \"\\\\w[-\\\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\\\.)+[A-Za-z]{2,14}\";\n\n // SharedPreference 键值\n public static final String LOGIN_STATE = \"login_state\";\n}", "public abstract class BaseMvpActivity<V extends BaseView, T extends BaseMvpPresenter<V>> extends\n AppCompatActivity {\n @Inject\n protected T mPresenter;\n\n @Override\n @SuppressWarnings(\"unchecked\")\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n setContentViewAndInject(savedInstanceState);\n ButterKnife.bind(this);\n// mPresenter = initPresenter();\n mPresenter.attach((V) this);\n }\n\n protected ActivityComponent getComponent() {\n return DaggerActivityComponent.builder().activityModule(getModule()).appComponent(AppComponent\n .getInstance()).build();\n }\n\n protected ActivityModule getModule() {\n return new ActivityModule(this);\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n mPresenter.detach();\n }\n\n // 实例化presenter\n// protected abstract T initPresenter();\n\n // 设置布局文件\n protected abstract void setContentViewAndInject(Bundle savedInstanceState);\n}", "public class MovieDetailPresenter extends BaseMvpPresenter<MovieDetailContract.View> implements\n MovieDetailContract.Presenter {\n private UserService mService;\n\n @Inject\n MovieDetailPresenter(RetrofitUtil retrofitUtil) {\n mService = retrofitUtil.create(UserService.class);\n }\n\n @Override\n public void getMovie(Movie movie, String date) {\n if (movie == null) {\n Disposable subscribe = mService.movie(date)\n .onBackpressureLatest()\n .map(new HttpResultFunc<List<Movie>>())\n .compose(RxUtil.<List<Movie>>rxSchedulerTransformer())\n .subscribe(new Consumer<List<Movie>>() {\n @Override\n public void accept(List<Movie> movieList) throws Exception {\n mView.showContent(movieList.get(0));\n }\n });\n addSubscription(subscribe);\n } else {\n mView.showContent(movie);\n }\n }\n}", "public interface MovieDetailContract {\n interface View extends BaseView {\n void showContent(Movie movie);\n }\n\n interface Presenter extends BasePresenter<View> {\n void getMovie(Movie movie, String date);\n }\n}", "public class SystemUtil {\n public static final String RUNNING_FONT = \"running_font.ttf\";\n private static Toast mToast;\n\n private SystemUtil() {\n }\n\n /**\n * 网络是否连接\n *\n * @return\n */\n public static boolean isNetworkConnected() {\n ConnectivityManager connectivityManager = (ConnectivityManager) FourFun.getInstance()\n .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);\n return connectivityManager.getActiveNetworkInfo() != null;\n }\n\n /**\n * 获取项目缓存路径\n * @return\n */\n public static String getCacheFileDirPath() {\n Logger.e(FourFun.getInstance().getApplicationContext().getCacheDir().getPath());\n Logger.e(FourFun.getInstance().getApplicationContext().getCacheDir().getAbsolutePath());\n return FourFun.getInstance().getApplicationContext().getCacheDir().getPath();\n }\n\n /**\n * toast 优化显示\n *\n * @param content\n */\n public static void showToast(Context context, String content) {\n if (mToast == null) {\n mToast = Toast.makeText(FourFun.getInstance().getContext(), content, Toast\n .LENGTH_SHORT);\n } else {\n mToast.setText(content);\n }\n\n mToast.show();\n }\n\n /**\n * 取消 toast\n */\n public static void cancelToast() {\n if (mToast != null) {\n mToast.cancel();\n }\n }\n\n /**\n * 前几天的日期\n *\n * @param before 和今天相差的天数\n * @return\n */\n public static String beforeToday(int before) {\n Date now = new Date();\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.CHINA); //设置时间格式\n\n if (before < 0) {\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(now);\n calendar.add(Calendar.DATE, before);\n now = calendar.getTime();\n }\n\n return sdf.format(now);\n }\n\n /**\n * 像素转 sp\n *\n * @param context\n * @param textSizePixel\n * @return\n */\n public static int px2sp(Context context, float textSizePixel) {\n final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;\n return (int) (textSizePixel / fontScale + 0.5f);\n }\n\n /**\n * sp 转 px\n *\n * @param context\n * @param textSizeSp\n * @return\n */\n public static float sp2px(Context context, float textSizeSp) {\n final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;\n return (int) (textSizeSp * fontScale + 0.5f);\n }\n\n /**\n * dp 转 px\n *\n * @param dp\n * @return\n */\n public static int dp2px(float dp) {\n float DENSITY = Resources.getSystem().getDisplayMetrics().density;\n return Math.round(dp * DENSITY);\n }\n\n public static Typeface getTypeface(Context context) {\n return Typeface.createFromAsset(context.getAssets(), \"fonts/\" + RUNNING_FONT);\n }\n\n /**\n * 输入流转文件\n * @param file\n * @param stream\n */\n public static void inputStream2file(File file, InputStream stream) {\n OutputStream os = null;\n try {\n os = new FileOutputStream(file);\n int bytesRead = 0;\n byte[] buffer = new byte[1024];\n while ((bytesRead = stream.read(buffer)) != -1) {\n os.write(buffer, 0, bytesRead);\n }\n\n os.close();\n stream.close();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (os != null) {\n os.close();\n }\n if (stream != null) {\n stream.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n}" ]
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Layout; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.AbsoluteSizeSpan; import android.text.style.AlignmentSpan; import android.widget.TextView; import android.widget.Toast; import com.joker.fourfun.Constants; import com.joker.fourfun.R; import com.joker.fourfun.base.BaseMvpActivity; import com.joker.fourfun.model.Movie; import com.joker.fourfun.presenter.MovieDetailPresenter; import com.joker.fourfun.presenter.contract.MovieDetailContract; import com.joker.fourfun.utils.SystemUtil; import butterknife.BindView;
package com.joker.fourfun.ui; public class MovieDetailActivity extends BaseMvpActivity<MovieDetailContract.View, MovieDetailPresenter> implements MovieDetailContract.View { @BindView(R.id.tv_movie_content) TextView mTvMovieContent; private Movie mMovie; public static Intent newInstance(AppCompatActivity activity, Bundle bundle) { Intent intent = new Intent(activity, MovieDetailActivity.class); intent.putExtra(Constants.MOVIE_BUNDLE, bundle); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); analyseIntent();
String day = SystemUtil.beforeToday(0);
4
Ericsongyl/PullRefreshAndLoadMore
sample/src/main/java/com/nicksong/pullrefresh/activities/NestedScrollingActivity.java
[ "public class Fragment0 extends Fragment implements BaseHeaderView.OnRefreshListener, BaseFooterView.OnLoadListener {\n View view;\n\n ListView listView;\n BaseHeaderView headerView;\n BaseFooterView footerView;\n\n ArrayAdapter adapter;\n\n List<String> list = new ArrayList<String>();\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n view = inflater.inflate(R.layout.fragment0, container, false);\n listView = findViewById(R.id.list);\n headerView = findViewById(R.id.header);\n footerView = findViewById(R.id.footer);\n\n list = getData(15);\n\n adapter = new ArrayAdapter(getContext(), R.layout.item, list);\n\n listView.setAdapter(adapter);\n\n headerView.setOnRefreshListener(this);\n footerView.setOnLoadListener(this);\n return view;\n }\n\n @Override\n public void onRefresh(BaseHeaderView baseHeaderView) {\n baseHeaderView.postDelayed(new Runnable() {\n @Override\n public void run() {\n page = 1;\n List<String> datas = getData(5);\n list.clear();\n list.addAll(datas);\n adapter.notifyDataSetChanged();\n headerView.stopRefresh();\n }\n }, 3000);\n }\n\n @Override\n public void onLoad(BaseFooterView baseFooterView) {\n baseFooterView.postDelayed(new Runnable() {\n @Override\n public void run() {\n page++;\n List<String> datas = getData(5);\n list.addAll(datas);\n adapter.notifyDataSetChanged();\n footerView.stopLoad();\n }\n }, 3000);\n }\n\n\n int page = 1;\n\n private List<String> getData(int n) {\n List<String> datas = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n datas.add(\"第\" + page + \"页,第\" + i + \"条\");\n }\n return datas;\n }\n\n public <T> T findViewById(int id) {\n return (T) view.findViewById(id);\n\n }\n}", "public class Fragment2 extends Fragment implements BaseHeaderView.OnRefreshListener, BaseFooterView.OnLoadListener {\n View view;\n\n BaseHeaderView headerView;\n BaseFooterView footerView;\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n view = inflater.inflate(R.layout.fragment2, container, false);\n\n headerView = findViewById(R.id.header);\n footerView = findViewById(R.id.footer);\n\n headerView.setOnRefreshListener(this);\n footerView.setOnLoadListener(this);\n return view;\n }\n\n\n @Override\n public void onRefresh(BaseHeaderView baseHeaderView) {\n baseHeaderView.postDelayed(new Runnable() {\n @Override\n public void run() {\n headerView.stopRefresh();\n }\n }, 3000);\n }\n\n @Override\n public void onLoad(BaseFooterView baseFooterView) {\n baseFooterView.postDelayed(new Runnable() {\n @Override\n public void run() {\n footerView.stopLoad();\n }\n }, 3000);\n }\n\n\n public <T> T findViewById(int id) {\n return (T) view.findViewById(id);\n\n }\n}", "public class Fragment3 extends Fragment implements BaseHeaderView.OnRefreshListener, BaseFooterView.OnLoadListener {\n View view;\n\n BaseHeaderView headerView;\n BaseFooterView footerView;\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n view = inflater.inflate(R.layout.fragment3, container, false);\n\n headerView = findViewById(R.id.header);\n footerView = findViewById(R.id.footer);\n\n headerView.setOnRefreshListener(this);\n footerView.setOnLoadListener(this);\n return view;\n }\n\n\n @Override\n public void onRefresh(BaseHeaderView baseHeaderView) {\n baseHeaderView.postDelayed(new Runnable() {\n @Override\n public void run() {\n headerView.stopRefresh();\n }\n }, 3000);\n }\n\n @Override\n public void onLoad(BaseFooterView baseFooterView) {\n baseFooterView.postDelayed(new Runnable() {\n @Override\n public void run() {\n footerView.stopLoad();\n }\n }, 3000);\n }\n\n\n public <T> T findViewById(int id) {\n return (T) view.findViewById(id);\n\n }\n}", "public class Fragment1 extends Fragment implements BaseHeaderView.OnRefreshListener, BaseFooterView.OnLoadListener {\n View view;\n\n\n RecyclerView recyclerView;\n BaseHeaderView headerView;\n BaseFooterView footerView;\n\n RecyclerViewAdapter adapter;\n\n List<String> list = new ArrayList<String>();\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n view = inflater.inflate(R.layout.fragment1, container, false);\n\n\n recyclerView = findViewById(R.id.list);\n headerView = findViewById(R.id.header);\n footerView = findViewById(R.id.footer);\n\n list = getData(15);\n\n adapter = new RecyclerViewAdapter();\n adapter.setData(list);\n\n recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));\n recyclerView.setAdapter(adapter);\n\n headerView.setOnRefreshListener(this);\n footerView.setOnLoadListener(this);\n\n return view;\n }\n @Override\n public void onRefresh(BaseHeaderView baseHeaderView) {\n baseHeaderView.postDelayed(new Runnable() {\n @Override\n public void run() {\n page = 1;\n List<String> datas = getData(5);\n list.clear();\n list.addAll(datas);\n adapter.setData(list);\n headerView.stopRefresh();\n }\n }, 3000);\n }\n\n @Override\n public void onLoad(BaseFooterView baseFooterView) {\n baseFooterView.postDelayed(new Runnable() {\n @Override\n public void run() {\n page++;\n List<String> datas = getData(5);\n list.addAll(datas);\n adapter.notifyDataSetChanged();\n footerView.stopLoad();\n }\n }, 3000);\n }\n\n\n int page = 1;\n\n private List<String> getData(int n) {\n List<String> datas = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n datas.add(\"第\" + page + \"页,第\" + i + \"条\");\n }\n return datas;\n }\n\n class RecyclerViewAdapter extends StandardAdapter {\n @Override\n public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));\n }\n\n @Override\n public void onBindViewHolder(ItemViewHolder holder, int position) {\n super.onBindViewHolder(holder, position);\n\n ((TextView) holder.itemView).setText(getItem(position).toString());\n\n }\n }\n\n public <T> T findViewById(int id) {\n return (T) view.findViewById(id);\n\n }\n\n}", "public class Fragment4 extends Fragment implements BaseHeaderView.OnRefreshListener, BaseFooterView.OnLoadListener {\n View view;\n\n BaseHeaderView headerView;\n BaseFooterView footerView;\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n view = inflater.inflate(R.layout.fragment4, container, false);\n WebView webView = findViewById(R.id.webview);\n webView.setWebViewClient(new WebViewClient() {\n @Override\n public void onPageFinished(WebView view, String url){\n }\n\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n\n if (url.indexOf(\"objc://\") != -1) {\n return true;\n }\n return super.shouldOverrideUrlLoading(view, url);\n }\n });\n webView.loadUrl(\"http://www.baidu.com\");\n headerView = findViewById(R.id.header);\n footerView = findViewById(R.id.footer);\n\n headerView.setOnRefreshListener(this);\n footerView.setOnLoadListener(this);\n return view;\n }\n\n\n @Override\n public void onRefresh(BaseHeaderView baseHeaderView) {\n baseHeaderView.postDelayed(new Runnable() {\n @Override\n public void run() {\n headerView.stopRefresh();\n }\n }, 3000);\n }\n\n @Override\n public void onLoad(BaseFooterView baseFooterView) {\n baseFooterView.postDelayed(new Runnable() {\n @Override\n public void run() {\n footerView.stopLoad();\n }\n }, 3000);\n }\n\n\n public <T> T findViewById(int id) {\n return (T) view.findViewById(id);\n\n }\n}" ]
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.nicksong.pullrefresh.R; import com.nicksong.pullrefresh.fragment.Fragment0; import com.nicksong.pullrefresh.fragment.Fragment2; import com.nicksong.pullrefresh.fragment.Fragment3; import com.nicksong.pullrefresh.fragment.Fragment1; import com.nicksong.pullrefresh.fragment.Fragment4; import java.util.ArrayList;
package com.nicksong.pullrefresh.activities; /** * Modified by nicksong at 2016/12/20 */ public class NestedScrollingActivity extends AppCompatActivity { ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nestedscrolling); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ArrayList<Fragment> fragments = new ArrayList<>();
fragments.add(new Fragment0());
0
bkueng/clash_of_balls
src/com/sapos_aplastados/game/clash_of_balls/menu/MenuItemList.java
[ "public class Texture {\n\tprivate TextureBase m_texture;\n\t\n\tpublic int textureHandle() { return m_texture.textureHandle(); }\n\t\n\t//tex_coords can be null to use default tex coords\n\tpublic Texture(TextureBase t) {\n\t\tm_texture = t;\n\t}\n\t\n\tpublic void useTexture(RenderHelper renderer) {\n m_texture.useTexture(renderer);\n //here would the texture coords be applied, but we use the same for \n //all textures so the default coordinates are applied in ShaderManager\n //when changing the shader\n\t}\n\n}", "public class VertexBufferFloat {\n\tprivate FloatBuffer m_data;\n\tprivate static final int bytes_per_float = 4;\n\tprivate final int m_num_components_per_item;\n\t\n\tpublic static final float[] sprite_position_data = new float[] \n\t\t\t{\n\t\t\t0.0f, 0.0f, 0.0f, // triangle strip: bottom left start, clockwise\n\t\t\t0.0f, 1.0f, 0.0f,\n\t\t\t1.0f, 0.0f, 0.0f,\n\t\t\t1.0f, 1.0f, 0.0f\n\t\t\t};\n\t\n\tpublic static final float[] sprite_tex_coords = new float[] \n\t\t\t{ \n\t\t\t0.0f, 0.0f, // triangle strip: bottom left start, clockwise\n\t\t\t0.0f, 1.0f,\n\t\t\t1.0f, 0.0f,\n\t\t\t1.0f, 1.0f\n\t\t\t};\n\t\n\tpublic VertexBufferFloat(float[] data, int num_components_per_item) {\n\t\tm_num_components_per_item = num_components_per_item;\n\t\tm_data = ByteBuffer.allocateDirect(\n\t\t\t\tdata.length * bytes_per_float)\n\t\t\t\t.order(ByteOrder.nativeOrder()).asFloatBuffer();\n\t\tm_data.put(data).position(0);\n\t}\n\t\n\tpublic FloatBuffer data() { return m_data; }\n\t\n\t\n\t//send data to shader\n\tpublic void apply(int shader_attr_handle) {\n \t// Pass in the texture coordinate information\n\t\tm_data.position(0);\n \tGLES20.glVertexAttribPointer(shader_attr_handle\n \t\t\t, m_num_components_per_item, GLES20.GL_FLOAT, false, \n \t\t\t0, m_data);\n\n \tGLES20.glEnableVertexAttribArray(shader_attr_handle);\n\t}\n}", "public class RenderHelper {\n\tprivate static final String LOG_TAG = \"RenderHelper\";\n\t\n\tprivate ShaderManager m_shader_manager;\n\t\n\tpublic float m_screen_width;\n\tpublic float m_screen_height;\n\t\n\tprivate float m_time_accumulator = 0.f;\n\t\n\tprivate static final int mat_size = 16; // = 4x4\n\t\n\tprivate float[] m_projection_mat = new float[mat_size];\n\t\n\t//model view matrix stack\n\tprivate float[] m_model_mat;\n\tprivate int m_cur_model_mat_pos;\n\tprivate int m_max_model_mat_pos;\n\t\n\tpublic ShaderManager shaderManager() { return m_shader_manager; }\n\t\n\tpublic RenderHelper(ShaderManager shader_manager, float screen_width, \n\t\t\tfloat screen_height) {\n\t\tm_shader_manager = shader_manager;\n\t\t\n\t\tfinal int init_model_mat_count = 6;\n\t\tm_model_mat = new float[init_model_mat_count*mat_size];\n\t\tm_cur_model_mat_pos=0;\n\t\tm_max_model_mat_pos = mat_size*(init_model_mat_count - 1);\n\t\tMatrix.setIdentityM(m_model_mat, m_cur_model_mat_pos);\n\t\t\n\t\tonSurfaceChanged(screen_width, screen_height);\n\t}\n\t\n\tpublic void onSurfaceChanged(float screen_width, float screen_height) {\n\t\tm_screen_width = screen_width;\n\t\tm_screen_height = screen_height;\n\t}\n\t\n\tpublic void move(float dsec) {\n\t\tm_time_accumulator += dsec;\n\t}\n\t\n\t//use an ARGB int value to init float array of 4 values (RGBA)\n\tpublic static void initColorArray(int color, float[] out_color) {\n\t\tout_color[0] = (float)((color >> 16) & 0xFF) / 255.f;\n\t\tout_color[1] = (float)((color >> 8) & 0xFF) / 255.f;\n\t\tout_color[2] = (float)(color & 0xFF) / 255.f;\n\t\tout_color[3] = (float)(color >>> 24) / 255.f;\n\t}\n\t//convert from float RGBA to int ARGB\n\tpublic static int getColor(float[] color) {\n\t\tint r = (int)(color[0]*255.f);\n\t\tint g = (int)(color[1]*255.f);\n\t\tint b = (int)(color[2]*255.f);\n\t\tint a = (int)(color[3]*255.f);\n\t\treturn (a<<24) | (r<<16) | (g<<8) | b;\n\t}\n\tpublic static final float color_white[] = new float[]\n\t\t\t{ 1.0f, 1.0f, 1.0f, 1.0f }; //RGBA\n\t\n\t\n\t/* projection matrix */\n\tpublic void useOrthoProjection() {\n\t\tMatrix.orthoM(m_projection_mat, 0, 0.f, m_screen_width, 0.f\n\t\t\t\t, m_screen_height, 0.f, 1.f);\n\t\tmodelMatSetIdentity();\n\t}\n\t\n\t\n\t/* Model view matrix stack */\n\tpublic float[] modelMat() { return m_model_mat; }\n\tpublic int modelMatPos() { return m_cur_model_mat_pos; }\n\t\n\t//returns the new modelMat position\n\t//creates a copy of the current matrix on top of the stack\n\tpublic int pushModelMat() {\n\t\tif(m_cur_model_mat_pos >= m_max_model_mat_pos)\n\t\t\tresizeModelMat(m_model_mat.length*2);\n\t\tfor(int i=0; i<mat_size; ++i) {\n\t\t\tm_model_mat[m_cur_model_mat_pos+i+mat_size] = \n\t\t\t\t\tm_model_mat[m_cur_model_mat_pos+i];\n\t\t}\n\t\tm_cur_model_mat_pos+=mat_size;\n\t\treturn m_cur_model_mat_pos;\n\t}\n\t\n\tpublic int popModelMat() {\n\t\t\n\t\tm_cur_model_mat_pos-=mat_size;\n\t\t\n\t\treturn m_cur_model_mat_pos;\n\t}\n\t\n\t//model matrix operations\n\tpublic void modelMatScale(float scale_x, float scale_y, float scale_z) {\n\t\tMatrix.scaleM(m_model_mat, m_cur_model_mat_pos, scale_x, scale_y, scale_z);\n\t}\n\tpublic void modelMatTranslate(float x, float y, float z) {\n\t\tMatrix.translateM(m_model_mat, m_cur_model_mat_pos, x, y, z);\n\t}\n\tprivate float[] m_tmp_rot_mat = new float[mat_size];\n\t\n\tpublic void modelMatRotate(float alpha_degree, float x, float y, float z) {\n Matrix.setRotateM(m_tmp_rot_mat, 0, alpha_degree, x, y, z);\n pushModelMat();\n Matrix.multiplyMM(m_model_mat, m_cur_model_mat_pos-mat_size\n \t\t, m_model_mat, m_cur_model_mat_pos, m_tmp_rot_mat, 0);\n popModelMat();\n\t}\n\tpublic void modelMatSetIdentity() {\n\t\t//we can directly set the projection matrix here because\n\t\t// proj mat * Identity = proj mat\n\t\tfor(int i=0; i<mat_size; ++i) \n\t\t\tm_model_mat[m_cur_model_mat_pos+i] = m_projection_mat[i];\n\t}\n\t\n\t\n\tprivate void resizeModelMat(int new_size) {\n\t\t\n\t\tLog.w(LOG_TAG, \"need to resize model view matrix. new size=\"+new_size);\n\t\t\n\t\tfloat new_mat[]=new float[new_size];\n\t\tfor(int i=0; i<Math.min(new_size, m_model_mat.length); ++i)\n\t\t\tnew_mat[i] = m_model_mat[i];\n\t\tm_model_mat = new_mat;\n\t\t\n\t\tm_max_model_mat_pos = m_model_mat.length-mat_size;\n\t}\n\t\n\t\n\t//call this right before rendering the object to apply the projection \n\t//& model matrices\n\tpublic void apply() {\n\t\t\n\t\tif(m_shader_manager.u_time_handle != -1)\n\t\t\tGLES20.glUniform1f(m_shader_manager.u_time_handle, m_time_accumulator);\n\t\t\n // Pass in the matrix to the shader.\n GLES20.glUniformMatrix4fv(m_shader_manager.u_MVPMatrix_handle, 1, false\n \t\t, m_model_mat, m_cur_model_mat_pos);\n\t}\n}", "public class Vector {\n\t\n\t// 2D vector\n\tpublic float x;\n\tpublic float y;\n\n\tpublic Vector() {\n\t\tx = 0.0f;\n\t\ty = 0.0f;\n\t}\n\tpublic Vector(Vec2 v) {\n\t\tx = v.x;\n\t\ty = v.y;\n\t}\n\n\tpublic Vector(float fx, float fy) {\n\t\tx = fx;\n\t\ty = fy;\n\t}\n\n\tpublic Vector(Vector src) {\n\t\tx = src.x;\n\t\ty = src.y;\n\t}\n\n\tpublic void set(Vector src) {\n\t\tx = src.x;\n\t\ty = src.y;\n\t}\n\n\tpublic void set(float fx, float fy) {\n\t\tx = fx;\n\t\ty = fy;\n\t}\n\n\t\n\tpublic float length() { \n\t\treturn FloatMath.sqrt((x * x) + (y * y));\n\t}\n\t\n\tpublic float lengthSquared() { \n\t\treturn (x * x) + (y * y);\n\t}\n\n\tpublic void normalize() {\n\t\tfloat len = length();\n\n\t\tif (len != 0.0f) {\n\t\t\tx /= len;\n\t\t\ty /= len;\n\t\t} else {\n\t\t\tx = 0.0f;\n\t\t\ty = 0.0f;\n\t\t}\n\t}\n\t\n\tpublic float distSquared(Vector p) {\n\t\treturn (x-p.x) * (x-p.x) + (y-p.y) * (y-p.y);\n\t}\n\tpublic float dist(Vector p) {\n\t\treturn FloatMath.sqrt((x-p.x) * (x-p.x) + (y-p.y) * (y-p.y));\n\t}\n\n\tpublic float angle() {\n\t\treturn (float) Math.atan2(y, x);\n\t}\n\t\n\tpublic void add(Vector vector) {\n\t\tx += vector.x;\n\t\ty += vector.y;\n\t}\n\tpublic void add(float fx, float fy) {\n\t\tx+=fx;\n\t\ty+=fy;\n\t}\n\n\tpublic void sub(Vector vector) {\n\t\tx -= vector.x;\n\t\ty -= vector.y;\n\t}\n\tpublic void sub(float fx, float fy) {\n\t\tx-=fx;\n\t\ty-=fy;\n\t}\n\n\n\tpublic void mul(Vector vector) {\n\t\tx *= vector.x;\n\t\ty *= vector.y; \n\t}\n\t \n\tpublic void mul(float scalar) {\n\t\tx *= scalar;\n\t\ty *= scalar;\n\t}\n\n\tpublic float dot(Vector vector) {\n\t\treturn (x * vector.x) + (y * vector.y);\n\t}\n\n\tpublic void rotate(float dAlfa_rad) {\n\t\tfloat nCos = FloatMath.cos(dAlfa_rad);\n\t\tfloat nSin = FloatMath.sin(dAlfa_rad);\n\t\t\n\t\tfloat iX = x * nCos - y * nSin;\n\t\tfloat iY = y * nCos + x * nSin;\n\n\t\tx = iX;\n\t\ty = iY;\n\t}\n\n}", "public enum ArrowType {\n\tRIGHT,\n\tLEFT\n}" ]
import java.util.ArrayList; import java.util.List; import com.sapos_aplastados.game.clash_of_balls.R; import com.sapos_aplastados.game.clash_of_balls.Texture; import com.sapos_aplastados.game.clash_of_balls.TextureManager; import com.sapos_aplastados.game.clash_of_balls.VertexBufferFloat; import com.sapos_aplastados.game.clash_of_balls.game.RenderHelper; import com.sapos_aplastados.game.clash_of_balls.game.Vector; import com.sapos_aplastados.game.clash_of_balls.menu.MenuItemArrow.ArrowType;
/* * Copyright (C) 2012-2013 Hans Hardmeier <hanshardmeier@gmail.com> * Copyright (C) 2012-2013 Andrin Jenal * Copyright (C) 2012-2013 Beat Küng <beat-kueng@gmx.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ package com.sapos_aplastados.game.clash_of_balls.menu; /** * this list can hold multiple MenuItem's in a list * scrolling through the list is done through 2 buttons * * Note: the added MenuItems must have the same width as the list! * the position will be set by this class * */ public class MenuItemList extends MenuItem { private static final String LOG_TAG = "MenuItemList"; private float m_view_height; //=m_size.y - (next or prev buttons height) private final float m_item_spacing; //vertical spacing between 2 items private List<MenuItem> m_items = new ArrayList<MenuItem>(); private int m_sel_item=-1; private int m_first_drawn_item = 0; private int m_last_drawn_item = 0; //page selection MenuItemArrow m_left_arrow; boolean m_left_arrow_visible = true; MenuItemArrow m_right_arrow; boolean m_right_arrow_visible = true; private Texture m_background_texture;
public MenuItemList(Vector position, Vector size, Vector arrow_button_size
3