repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/util/android/ImageContainer.java
// Path: src/main/java/net/ilexiconn/magister/util/AndroidUtil.java // public class AndroidUtil { // private static boolean runningOnAndroid = false; // private static boolean androidSupportCache = false; // // /** // * Check if the API is running on Android. // */ // public static void checkAndroid() { // try { // Class.forName("android.view.View"); // runningOnAndroid = true; // isCacheAvailableOnAndroid(); // } catch (ClassNotFoundException e) { // runningOnAndroid = false; // } // } // // /** // * Check if the API is running on Android, and if it can use the Android caching utilities. // * // * @return true if the API is running on Android and can use the Android caching utilities. // */ // public static boolean isCacheAvailableOnAndroid() { // try { // Class<?> cache = Class.forName("android.net.http.HttpResponseCache"); // cache.getMethod("getInstalled").invoke(null); // androidSupportCache = true; // } catch (ClassNotFoundException e) { // LogUtil.printError("Could not find Class: android.net.http.HttpResponseCache", e.getCause()); // androidSupportCache = false; // } catch (NoSuchMethodException e) { // LogUtil.printError("Could not find Method: getInstalled", e.getCause()); // androidSupportCache = false; // } catch (IllegalAccessException e) { // LogUtil.printError("Could not access Method: getInstalled", e.getCause()); // androidSupportCache = false; // } catch (InvocationTargetException e) { // LogUtil.printError("Failed to invoke Method: getInstalled", e.getCause()); // androidSupportCache = false; // } // return androidSupportCache; // } // // public static boolean getRunningOnAndroid() { // return runningOnAndroid; // } // // public static boolean getAndroidSupportCache() { // return androidSupportCache; // } // } // // Path: src/main/java/net/ilexiconn/magister/util/LogUtil.java // public class LogUtil { // private static String TAG = "MAGISTER.JAVA"; // // /** // * Print an error to the system error stream. Will use the Log class if running on Android. // * // * @param description the error's description. // * @param throwable the throwable. // */ // public static void printError(String description, Throwable throwable) { // String details = toPrettyString("Operating System", System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ")") + toPrettyString("Java Version", System.getProperty("java.version")); // String report = "---- Error Report ----\n" + description + "\n\n-- Crash Log --\n" + getStackTrace(throwable) + "\n-- System Details --\n" + details; // if (AndroidUtil.getRunningOnAndroid()) { // try { // Class<?> logClass = Class.forName("android.util.Log"); // logClass.getMethod("e", String.class, String.class, Throwable.class).invoke(null, TAG, description, throwable); // return; // } catch (Exception e) { // System.err.println(report); // } // } // System.err.println(report); // } // // private static String toPrettyString(String key, String value) { // return key + "\n\t" + value + "\n"; // } // // private static String getStackTrace(Throwable throwable) { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // throwable.printStackTrace(printWriter); // String s = stringWriter.toString(); // // try { // stringWriter.close(); // printWriter.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // return s; // } // // /** // * Set a custom Android logging tag. // * // * @param tag the new tag. // */ // public static void setAndroidTag(String tag) { // TAG = tag; // } // }
import net.ilexiconn.magister.util.AndroidUtil; import net.ilexiconn.magister.util.LogUtil; import java.io.InputStream; import java.lang.reflect.Method;
/* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.util.android; public class ImageContainer { private Class classT; private Class classImage; private Class classBitmap; private Object image; public ImageContainer(InputStream stream) throws ClassNotFoundException { Class c; if (AndroidUtil.getRunningOnAndroid()) { c = Class.forName("android.graphics.Bitmap"); } else { c = Class.forName("java.awt.image.BufferedImage"); } if (c == null) { throw new NullPointerException(); } this.classT = c; try { classBitmap = Class.forName("android.graphics.Bitmap"); if (!classT.equals(classBitmap)) { throw new Exception(); } Method m = Class.forName("android.graphics.BitmapFactory").getMethod("decodeStream", InputStream.class); image = classT.cast(m.invoke(null, stream)); return; } catch (Exception e) { if (!(e instanceof ClassNotFoundException)) {
// Path: src/main/java/net/ilexiconn/magister/util/AndroidUtil.java // public class AndroidUtil { // private static boolean runningOnAndroid = false; // private static boolean androidSupportCache = false; // // /** // * Check if the API is running on Android. // */ // public static void checkAndroid() { // try { // Class.forName("android.view.View"); // runningOnAndroid = true; // isCacheAvailableOnAndroid(); // } catch (ClassNotFoundException e) { // runningOnAndroid = false; // } // } // // /** // * Check if the API is running on Android, and if it can use the Android caching utilities. // * // * @return true if the API is running on Android and can use the Android caching utilities. // */ // public static boolean isCacheAvailableOnAndroid() { // try { // Class<?> cache = Class.forName("android.net.http.HttpResponseCache"); // cache.getMethod("getInstalled").invoke(null); // androidSupportCache = true; // } catch (ClassNotFoundException e) { // LogUtil.printError("Could not find Class: android.net.http.HttpResponseCache", e.getCause()); // androidSupportCache = false; // } catch (NoSuchMethodException e) { // LogUtil.printError("Could not find Method: getInstalled", e.getCause()); // androidSupportCache = false; // } catch (IllegalAccessException e) { // LogUtil.printError("Could not access Method: getInstalled", e.getCause()); // androidSupportCache = false; // } catch (InvocationTargetException e) { // LogUtil.printError("Failed to invoke Method: getInstalled", e.getCause()); // androidSupportCache = false; // } // return androidSupportCache; // } // // public static boolean getRunningOnAndroid() { // return runningOnAndroid; // } // // public static boolean getAndroidSupportCache() { // return androidSupportCache; // } // } // // Path: src/main/java/net/ilexiconn/magister/util/LogUtil.java // public class LogUtil { // private static String TAG = "MAGISTER.JAVA"; // // /** // * Print an error to the system error stream. Will use the Log class if running on Android. // * // * @param description the error's description. // * @param throwable the throwable. // */ // public static void printError(String description, Throwable throwable) { // String details = toPrettyString("Operating System", System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ")") + toPrettyString("Java Version", System.getProperty("java.version")); // String report = "---- Error Report ----\n" + description + "\n\n-- Crash Log --\n" + getStackTrace(throwable) + "\n-- System Details --\n" + details; // if (AndroidUtil.getRunningOnAndroid()) { // try { // Class<?> logClass = Class.forName("android.util.Log"); // logClass.getMethod("e", String.class, String.class, Throwable.class).invoke(null, TAG, description, throwable); // return; // } catch (Exception e) { // System.err.println(report); // } // } // System.err.println(report); // } // // private static String toPrettyString(String key, String value) { // return key + "\n\t" + value + "\n"; // } // // private static String getStackTrace(Throwable throwable) { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // throwable.printStackTrace(printWriter); // String s = stringWriter.toString(); // // try { // stringWriter.close(); // printWriter.close(); // } catch (IOException e) { // e.printStackTrace(); // } // // return s; // } // // /** // * Set a custom Android logging tag. // * // * @param tag the new tag. // */ // public static void setAndroidTag(String tag) { // TAG = tag; // } // } // Path: src/main/java/net/ilexiconn/magister/util/android/ImageContainer.java import net.ilexiconn.magister.util.AndroidUtil; import net.ilexiconn.magister.util.LogUtil; import java.io.InputStream; import java.lang.reflect.Method; /* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.util.android; public class ImageContainer { private Class classT; private Class classImage; private Class classBitmap; private Object image; public ImageContainer(InputStream stream) throws ClassNotFoundException { Class c; if (AndroidUtil.getRunningOnAndroid()) { c = Class.forName("android.graphics.Bitmap"); } else { c = Class.forName("java.awt.image.BufferedImage"); } if (c == null) { throw new NullPointerException(); } this.classT = c; try { classBitmap = Class.forName("android.graphics.Bitmap"); if (!classT.equals(classBitmap)) { throw new Exception(); } Method m = Class.forName("android.graphics.BitmapFactory").getMethod("decodeStream", InputStream.class); image = classT.cast(m.invoke(null, stream)); return; } catch (Exception e) { if (!(e instanceof ClassNotFoundException)) {
LogUtil.printError(e.getMessage(), e.getCause());
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/container/SingleStudyGuide.java
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // }
import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable;
/* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class SingleStudyGuide implements Serializable { @SerializedName("Id") public int id; @SerializedName("Links")
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // } // Path: src/main/java/net/ilexiconn/magister/container/SingleStudyGuide.java import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable; /* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class SingleStudyGuide implements Serializable { @SerializedName("Id") public int id; @SerializedName("Links")
public Link[] links;
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/container/MessageFolder.java
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // }
import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable;
/* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class MessageFolder implements Serializable { @SerializedName("Naam") public String title; @SerializedName("OngelezenBerichten") public int unreadMessages; @SerializedName("Id") public int id; @SerializedName("ParentId") public int parentId; // TODO: Seems always to be NULL // @SerializedName("BerichtenUri") // public int id; @SerializedName("Links")
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // } // Path: src/main/java/net/ilexiconn/magister/container/MessageFolder.java import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable; /* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class MessageFolder implements Serializable { @SerializedName("Naam") public String title; @SerializedName("OngelezenBerichten") public int unreadMessages; @SerializedName("Id") public int id; @SerializedName("ParentId") public int parentId; // TODO: Seems always to be NULL // @SerializedName("BerichtenUri") // public int id; @SerializedName("Links")
public Link[] links;
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/adapter/SingleStudyGuideAdapter.java
// Path: src/main/java/net/ilexiconn/magister/container/SingleStudyGuide.java // public class SingleStudyGuide implements Serializable { // @SerializedName("Id") // public int id; // // @SerializedName("Links") // public Link[] links; // // @SerializedName("Van") // public String from; // // @SerializedName("TotEnMet") // public String to; // // @SerializedName("Titel") // public String title; // // @SerializedName("IsZichtbaar") // public boolean isVisible; // // @SerializedName("InLeerlingArchief") // public boolean isArchived; // // @SerializedName("VakCodes") // public String[] courses; // // public StudyGuideItem[] items; // } // // Path: src/main/java/net/ilexiconn/magister/container/StudyGuideItem.java // public class StudyGuideItem implements Serializable { // // Bronnen // // @SerializedName("Id") // public int id; // // @SerializedName("Links") // public Link[] links; // // @SerializedName("Van") // public String from; // // @SerializedName("TotEnMet") // public String to; // // @SerializedName("Titel") // public String title; // // @SerializedName("Omschrijving") // public String description; // // @SerializedName("IsZichtbaar") // public boolean isVisible; // // @SerializedName("Kleur") // public int color; // // @SerializedName("Volgnummer") // public int followId; // } // // Path: src/main/java/net/ilexiconn/magister/util/GsonUtil.java // public class GsonUtil { // private static Gson gson = new Gson(); // private static JsonParser parser = new JsonParser(); // // public static Gson getGson() { // return gson; // } // // public static JsonElement getFromJson(String json, String key) { // return parser.parse(json).getAsJsonObject().get(key); // } // // public static Gson getGsonWithAdapter(Class<?> type, TypeAdapter<?> adapter) { // Map<Class<?>, TypeAdapter<?>> map = new HashMap<Class<?>, TypeAdapter<?>>(); // map.put(type, adapter); // return getGsonWithAdapters(map); // } // // public static Gson getGsonWithAdapters(Map<Class<?>, TypeAdapter<?>> map) { // GsonBuilder builder = new GsonBuilder(); // for (Map.Entry<Class<?>, TypeAdapter<?>> entry : map.entrySet()) { // builder.registerTypeAdapter(entry.getKey(), entry.getValue()); // } // return builder.create(); // } // }
import net.ilexiconn.magister.util.GsonUtil; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.gson.*; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import net.ilexiconn.magister.container.SingleStudyGuide; import net.ilexiconn.magister.container.StudyGuideItem;
/* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.adapter; public class SingleStudyGuideAdapter extends TypeAdapter<SingleStudyGuide> { public Gson gson = GsonUtil.getGson(); @Override public void write(JsonWriter out, SingleStudyGuide value) throws IOException { throw new UnsupportedOperationException("Not implemented"); } @Override public SingleStudyGuide read(JsonReader in) throws IOException { JsonObject object = gson.getAdapter(JsonElement.class).read(in).getAsJsonObject(); SingleStudyGuide studyGuide = gson.fromJson(object, SingleStudyGuide.class); JsonArray array = object.get("Onderdelen").getAsJsonObject().get("Items").getAsJsonArray();
// Path: src/main/java/net/ilexiconn/magister/container/SingleStudyGuide.java // public class SingleStudyGuide implements Serializable { // @SerializedName("Id") // public int id; // // @SerializedName("Links") // public Link[] links; // // @SerializedName("Van") // public String from; // // @SerializedName("TotEnMet") // public String to; // // @SerializedName("Titel") // public String title; // // @SerializedName("IsZichtbaar") // public boolean isVisible; // // @SerializedName("InLeerlingArchief") // public boolean isArchived; // // @SerializedName("VakCodes") // public String[] courses; // // public StudyGuideItem[] items; // } // // Path: src/main/java/net/ilexiconn/magister/container/StudyGuideItem.java // public class StudyGuideItem implements Serializable { // // Bronnen // // @SerializedName("Id") // public int id; // // @SerializedName("Links") // public Link[] links; // // @SerializedName("Van") // public String from; // // @SerializedName("TotEnMet") // public String to; // // @SerializedName("Titel") // public String title; // // @SerializedName("Omschrijving") // public String description; // // @SerializedName("IsZichtbaar") // public boolean isVisible; // // @SerializedName("Kleur") // public int color; // // @SerializedName("Volgnummer") // public int followId; // } // // Path: src/main/java/net/ilexiconn/magister/util/GsonUtil.java // public class GsonUtil { // private static Gson gson = new Gson(); // private static JsonParser parser = new JsonParser(); // // public static Gson getGson() { // return gson; // } // // public static JsonElement getFromJson(String json, String key) { // return parser.parse(json).getAsJsonObject().get(key); // } // // public static Gson getGsonWithAdapter(Class<?> type, TypeAdapter<?> adapter) { // Map<Class<?>, TypeAdapter<?>> map = new HashMap<Class<?>, TypeAdapter<?>>(); // map.put(type, adapter); // return getGsonWithAdapters(map); // } // // public static Gson getGsonWithAdapters(Map<Class<?>, TypeAdapter<?>> map) { // GsonBuilder builder = new GsonBuilder(); // for (Map.Entry<Class<?>, TypeAdapter<?>> entry : map.entrySet()) { // builder.registerTypeAdapter(entry.getKey(), entry.getValue()); // } // return builder.create(); // } // } // Path: src/main/java/net/ilexiconn/magister/adapter/SingleStudyGuideAdapter.java import net.ilexiconn.magister.util.GsonUtil; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.gson.*; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import net.ilexiconn.magister.container.SingleStudyGuide; import net.ilexiconn.magister.container.StudyGuideItem; /* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.adapter; public class SingleStudyGuideAdapter extends TypeAdapter<SingleStudyGuide> { public Gson gson = GsonUtil.getGson(); @Override public void write(JsonWriter out, SingleStudyGuide value) throws IOException { throw new UnsupportedOperationException("Not implemented"); } @Override public SingleStudyGuide read(JsonReader in) throws IOException { JsonObject object = gson.getAdapter(JsonElement.class).read(in).getAsJsonObject(); SingleStudyGuide studyGuide = gson.fromJson(object, SingleStudyGuide.class); JsonArray array = object.get("Onderdelen").getAsJsonObject().get("Items").getAsJsonArray();
List<StudyGuideItem> studyGuideItemList = new ArrayList<StudyGuideItem>();
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/container/StudyGuideItem.java
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // }
import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable;
/* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class StudyGuideItem implements Serializable { // Bronnen @SerializedName("Id") public int id; @SerializedName("Links")
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // } // Path: src/main/java/net/ilexiconn/magister/container/StudyGuideItem.java import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable; /* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class StudyGuideItem implements Serializable { // Bronnen @SerializedName("Id") public int id; @SerializedName("Links")
public Link[] links;
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/container/StudyGuide.java
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // }
import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable;
/* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class StudyGuide implements Serializable { @SerializedName("Id") public int id; @SerializedName("Links")
// Path: src/main/java/net/ilexiconn/magister/container/sub/Link.java // public class Link implements Serializable { // @SerializedName(value = "href", alternate = "Href") // public String href; // // @SerializedName(value = "rel", alternate = "Rel") // public String rel; // } // Path: src/main/java/net/ilexiconn/magister/container/StudyGuide.java import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.sub.Link; import java.io.Serializable; /* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class StudyGuide implements Serializable { @SerializedName("Id") public int id; @SerializedName("Links")
public Link[] links;
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/container/PersonalAppointment.java
// Path: src/main/java/net/ilexiconn/magister/container/type/AppointmentType.java // public enum AppointmentType implements Serializable { // PERSONAL(1), // GENERAL(2), // SCHOOLWIDE(3), // INTERNSHIP(4), // INTAKE(4), // SHEDULE_FREE(5), // KWT(6), // STANDBY(7), // BLOCK(8), // MISCELLANEOUS(9), // LOCAL_BLOCK(10), // CLASS_BLOCK(11), // //12? // LESSON(13), // SHEDULE_FREE_STUDY(14), // //15? // PLANNING(16), // ACTIONS(101), // PRESENCES(102), // EXAM_SHUDULE(103); // // private int id; // // AppointmentType(int i) { // id = i; // } // // public static AppointmentType getTypeById(int i) { // for (AppointmentType type : values()) { // if (type.getID() == i) { // return type; // } // } // return null; // } // // public int getID() { // return id; // } // } // // Path: src/main/java/net/ilexiconn/magister/util/DateUtil.java // public class DateUtil { // /** // * Parse a String date into a Date object. // * // * @param date the String date. // * @return the new Date instance. // * @throws ParseException if the date String can't be parsed. // */ // public static Date stringToDate(String date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.parse(date); // } // // /** // * Parse a Date object into a String. // * // * @param date the Date instance. // * @return the date as String. // * @throws ParseException if the Date object can't be parsed. // */ // public static String dateToString(Date date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.format(date) + "Z"; // } // }
import java.text.ParseException; import java.util.Date; import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.type.AppointmentType; import net.ilexiconn.magister.util.DateUtil; import java.io.Serializable; import java.security.InvalidParameterException;
/* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class PersonalAppointment implements Serializable { @SerializedName("Id") public int id = 0; @SerializedName("Start") public String startDate; @SerializedName("Einde") public String endDate; @SerializedName("DuurtHeleDag") public boolean takesAllDay = false; @SerializedName("Lokatie") public String location; @SerializedName("InfoType") public int infoType = 1; @SerializedName("WeergaveType") public int displayType = 1; @SerializedName("Type") public int appointmentType = 1; @SerializedName("Afgerond") public boolean finished = false; @SerializedName("Inhoud") public String content; @SerializedName("Omschrijving") public String description; @SerializedName("Status") public int classState = 2; @SerializedName("OpdrachtId") public int asignmentId = 0;
// Path: src/main/java/net/ilexiconn/magister/container/type/AppointmentType.java // public enum AppointmentType implements Serializable { // PERSONAL(1), // GENERAL(2), // SCHOOLWIDE(3), // INTERNSHIP(4), // INTAKE(4), // SHEDULE_FREE(5), // KWT(6), // STANDBY(7), // BLOCK(8), // MISCELLANEOUS(9), // LOCAL_BLOCK(10), // CLASS_BLOCK(11), // //12? // LESSON(13), // SHEDULE_FREE_STUDY(14), // //15? // PLANNING(16), // ACTIONS(101), // PRESENCES(102), // EXAM_SHUDULE(103); // // private int id; // // AppointmentType(int i) { // id = i; // } // // public static AppointmentType getTypeById(int i) { // for (AppointmentType type : values()) { // if (type.getID() == i) { // return type; // } // } // return null; // } // // public int getID() { // return id; // } // } // // Path: src/main/java/net/ilexiconn/magister/util/DateUtil.java // public class DateUtil { // /** // * Parse a String date into a Date object. // * // * @param date the String date. // * @return the new Date instance. // * @throws ParseException if the date String can't be parsed. // */ // public static Date stringToDate(String date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.parse(date); // } // // /** // * Parse a Date object into a String. // * // * @param date the Date instance. // * @return the date as String. // * @throws ParseException if the Date object can't be parsed. // */ // public static String dateToString(Date date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.format(date) + "Z"; // } // } // Path: src/main/java/net/ilexiconn/magister/container/PersonalAppointment.java import java.text.ParseException; import java.util.Date; import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.type.AppointmentType; import net.ilexiconn.magister.util.DateUtil; import java.io.Serializable; import java.security.InvalidParameterException; /* * Copyright (c) 2015 iLexiconn * * 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 net.ilexiconn.magister.container; public class PersonalAppointment implements Serializable { @SerializedName("Id") public int id = 0; @SerializedName("Start") public String startDate; @SerializedName("Einde") public String endDate; @SerializedName("DuurtHeleDag") public boolean takesAllDay = false; @SerializedName("Lokatie") public String location; @SerializedName("InfoType") public int infoType = 1; @SerializedName("WeergaveType") public int displayType = 1; @SerializedName("Type") public int appointmentType = 1; @SerializedName("Afgerond") public boolean finished = false; @SerializedName("Inhoud") public String content; @SerializedName("Omschrijving") public String description; @SerializedName("Status") public int classState = 2; @SerializedName("OpdrachtId") public int asignmentId = 0;
public PersonalAppointment(String title, String content, String location, AppointmentType type, Date start, Date end) throws ParseException {
iLexiconn/Magister.java
src/main/java/net/ilexiconn/magister/container/PersonalAppointment.java
// Path: src/main/java/net/ilexiconn/magister/container/type/AppointmentType.java // public enum AppointmentType implements Serializable { // PERSONAL(1), // GENERAL(2), // SCHOOLWIDE(3), // INTERNSHIP(4), // INTAKE(4), // SHEDULE_FREE(5), // KWT(6), // STANDBY(7), // BLOCK(8), // MISCELLANEOUS(9), // LOCAL_BLOCK(10), // CLASS_BLOCK(11), // //12? // LESSON(13), // SHEDULE_FREE_STUDY(14), // //15? // PLANNING(16), // ACTIONS(101), // PRESENCES(102), // EXAM_SHUDULE(103); // // private int id; // // AppointmentType(int i) { // id = i; // } // // public static AppointmentType getTypeById(int i) { // for (AppointmentType type : values()) { // if (type.getID() == i) { // return type; // } // } // return null; // } // // public int getID() { // return id; // } // } // // Path: src/main/java/net/ilexiconn/magister/util/DateUtil.java // public class DateUtil { // /** // * Parse a String date into a Date object. // * // * @param date the String date. // * @return the new Date instance. // * @throws ParseException if the date String can't be parsed. // */ // public static Date stringToDate(String date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.parse(date); // } // // /** // * Parse a Date object into a String. // * // * @param date the Date instance. // * @return the date as String. // * @throws ParseException if the Date object can't be parsed. // */ // public static String dateToString(Date date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.format(date) + "Z"; // } // }
import java.text.ParseException; import java.util.Date; import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.type.AppointmentType; import net.ilexiconn.magister.util.DateUtil; import java.io.Serializable; import java.security.InvalidParameterException;
public int displayType = 1; @SerializedName("Type") public int appointmentType = 1; @SerializedName("Afgerond") public boolean finished = false; @SerializedName("Inhoud") public String content; @SerializedName("Omschrijving") public String description; @SerializedName("Status") public int classState = 2; @SerializedName("OpdrachtId") public int asignmentId = 0; public PersonalAppointment(String title, String content, String location, AppointmentType type, Date start, Date end) throws ParseException { this.location = location; this.content = content; if (title == null || "".equals(title)) { throw new InvalidParameterException("The appointment's title must be set!"); } description = title; if (start.after(end) || start.equals(end)) { throw new InvalidParameterException("The appointment's start date must be before and not equal to the end date!"); }
// Path: src/main/java/net/ilexiconn/magister/container/type/AppointmentType.java // public enum AppointmentType implements Serializable { // PERSONAL(1), // GENERAL(2), // SCHOOLWIDE(3), // INTERNSHIP(4), // INTAKE(4), // SHEDULE_FREE(5), // KWT(6), // STANDBY(7), // BLOCK(8), // MISCELLANEOUS(9), // LOCAL_BLOCK(10), // CLASS_BLOCK(11), // //12? // LESSON(13), // SHEDULE_FREE_STUDY(14), // //15? // PLANNING(16), // ACTIONS(101), // PRESENCES(102), // EXAM_SHUDULE(103); // // private int id; // // AppointmentType(int i) { // id = i; // } // // public static AppointmentType getTypeById(int i) { // for (AppointmentType type : values()) { // if (type.getID() == i) { // return type; // } // } // return null; // } // // public int getID() { // return id; // } // } // // Path: src/main/java/net/ilexiconn/magister/util/DateUtil.java // public class DateUtil { // /** // * Parse a String date into a Date object. // * // * @param date the String date. // * @return the new Date instance. // * @throws ParseException if the date String can't be parsed. // */ // public static Date stringToDate(String date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.parse(date); // } // // /** // * Parse a Date object into a String. // * // * @param date the Date instance. // * @return the date as String. // * @throws ParseException if the Date object can't be parsed. // */ // public static String dateToString(Date date) throws ParseException { // if (date == null) { // return null; // } // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS"); // format.setTimeZone(TimeZone.getTimeZone("GMT-0")); // return format.format(date) + "Z"; // } // } // Path: src/main/java/net/ilexiconn/magister/container/PersonalAppointment.java import java.text.ParseException; import java.util.Date; import com.google.gson.annotations.SerializedName; import net.ilexiconn.magister.container.type.AppointmentType; import net.ilexiconn.magister.util.DateUtil; import java.io.Serializable; import java.security.InvalidParameterException; public int displayType = 1; @SerializedName("Type") public int appointmentType = 1; @SerializedName("Afgerond") public boolean finished = false; @SerializedName("Inhoud") public String content; @SerializedName("Omschrijving") public String description; @SerializedName("Status") public int classState = 2; @SerializedName("OpdrachtId") public int asignmentId = 0; public PersonalAppointment(String title, String content, String location, AppointmentType type, Date start, Date end) throws ParseException { this.location = location; this.content = content; if (title == null || "".equals(title)) { throw new InvalidParameterException("The appointment's title must be set!"); } description = title; if (start.after(end) || start.equals(end)) { throw new InvalidParameterException("The appointment's start date must be before and not equal to the end date!"); }
startDate = DateUtil.dateToString(start);
wakaleo/maven-schemaspy-plugin
src/test/java/com/wakaleo/schemaspy/SchemaSpyMojoTest.java
// Path: src/test/java/com/wakaleo/schemaspy/util/DatabaseHelper.java // public class DatabaseHelper { // // private static Boolean databaseSetupDone = false; // // /** // * Create an embedded Derby database using a simple SQL script. The SQL // * commands should each be on a single line. "--" and "//" can be used for // * comments. // * // * @param sqlCreateScript // * Path to a file containing the SQL creation script. // */ // public static final void setupDatabase(String sqlCreateScript) // throws SQLException, FileNotFoundException, IOException, // ClassNotFoundException { // if (!databaseSetupDone) { // synchronized (databaseSetupDone) { // BufferedReader input = null; // try { // Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); // java.sql.Connection connection = java.sql.DriverManager // .getConnection("jdbc:derby:testdb;create=true"); // // input = new BufferedReader(new FileReader(sqlCreateScript)); // String line = null; // // while ((line = input.readLine()) != null) { // if (!isSQLComment(line)) { // Logger.getLogger("global").log(Level.INFO, line); // Statement st = connection.createStatement(); // try { // int i = st.executeUpdate(line); // run the query // if (i == -1) { // Logger.getLogger("global").log( // Level.SEVERE, "SQL Error: " + line); // } // } catch (SQLException e) { // String msg = e.getMessage(); // if (msg.contains("DROP TABLE")) { // continue; // Ignore errors when trying to // // drop tables // } // Logger.getLogger("global").log(Level.SEVERE, // "SQL Error: ", e); // } // st.close(); // } // } // connection.commit(); // connection.close(); // databaseSetupDone = true; // } finally { // try { // if (input != null) { // // flush and close both "input" and its underlying // // FileReader // input.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // } // } // } // // private static boolean isSQLComment(String line) { // return ((line.startsWith("//")) || (line.startsWith("--"))); // } // }
import com.wakaleo.schemaspy.util.DatabaseHelper; import org.apache.maven.plugin.testing.MojoRule; import org.apache.maven.plugin.testing.resources.TestResources; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.util.Locale; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeTrue;
package com.wakaleo.schemaspy; /** * SchemaSpyReport unit tests Test POM files is kept in test/resources/unit * directory. * * @author john */ public class SchemaSpyMojoTest { /** * Test resources. */ @Rule public TestResources resources = new TestResources(); /** * test rule. */ @Rule public MojoRule rule = new MojoRule(); @Before public void setUp() throws Exception {
// Path: src/test/java/com/wakaleo/schemaspy/util/DatabaseHelper.java // public class DatabaseHelper { // // private static Boolean databaseSetupDone = false; // // /** // * Create an embedded Derby database using a simple SQL script. The SQL // * commands should each be on a single line. "--" and "//" can be used for // * comments. // * // * @param sqlCreateScript // * Path to a file containing the SQL creation script. // */ // public static final void setupDatabase(String sqlCreateScript) // throws SQLException, FileNotFoundException, IOException, // ClassNotFoundException { // if (!databaseSetupDone) { // synchronized (databaseSetupDone) { // BufferedReader input = null; // try { // Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); // java.sql.Connection connection = java.sql.DriverManager // .getConnection("jdbc:derby:testdb;create=true"); // // input = new BufferedReader(new FileReader(sqlCreateScript)); // String line = null; // // while ((line = input.readLine()) != null) { // if (!isSQLComment(line)) { // Logger.getLogger("global").log(Level.INFO, line); // Statement st = connection.createStatement(); // try { // int i = st.executeUpdate(line); // run the query // if (i == -1) { // Logger.getLogger("global").log( // Level.SEVERE, "SQL Error: " + line); // } // } catch (SQLException e) { // String msg = e.getMessage(); // if (msg.contains("DROP TABLE")) { // continue; // Ignore errors when trying to // // drop tables // } // Logger.getLogger("global").log(Level.SEVERE, // "SQL Error: ", e); // } // st.close(); // } // } // connection.commit(); // connection.close(); // databaseSetupDone = true; // } finally { // try { // if (input != null) { // // flush and close both "input" and its underlying // // FileReader // input.close(); // } // } catch (IOException ex) { // ex.printStackTrace(); // } // } // } // } // } // // private static boolean isSQLComment(String line) { // return ((line.startsWith("//")) || (line.startsWith("--"))); // } // } // Path: src/test/java/com/wakaleo/schemaspy/SchemaSpyMojoTest.java import com.wakaleo.schemaspy.util.DatabaseHelper; import org.apache.maven.plugin.testing.MojoRule; import org.apache.maven.plugin.testing.resources.TestResources; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.util.Locale; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeTrue; package com.wakaleo.schemaspy; /** * SchemaSpyReport unit tests Test POM files is kept in test/resources/unit * directory. * * @author john */ public class SchemaSpyMojoTest { /** * Test resources. */ @Rule public TestResources resources = new TestResources(); /** * test rule. */ @Rule public MojoRule rule = new MojoRule(); @Before public void setUp() throws Exception {
DatabaseHelper.setupDatabase("src/test/resources/sql/testdb.sql");
OlliV/angr
workspace/Angr/src/fi/hbp/angr/hud/HudGameStateDisplay.java
// Path: workspace/Angr/src/fi/hbp/angr/logic/GameState.java // public class GameState { // /** // * Grenade counter. // */ // public class Grenades { // /** // * Amount of grenades at the beginning. // */ // public final int originalCount; // /** // * Current count. // */ // private int count; // // /** // * Constructor for Grenades class. // * @param amount Amount of grenades available. // */ // public Grenades(int amount) { // this.originalCount = amount; // this.count = amount; // } // // /** // * Decrement amount of grenades by one. // */ // public void decrement() { // if (count > 0) // count--; // } // // /** // * Returns current grenade count. // * @return current grenade count. // */ // public int getCount() { // return count; // } // } // // /** // * Game score. // */ // private int score = 0; // /** // * Badge scaling. // */ // private int badgeScale = 1; // /** // * Enemies left in this map. // */ // private int enemyCount = 0; // /** // * Grenade counter. // */ // private Grenades grenades = new Grenades(0); // /** // * All game stats calculated true/false. // */ // private boolean gameFinalized = false; // // /** // * Initialize game state object. // * @param badgeScale points needed to achieve one badge. // * @param enemies enemy count on the current level at the beginning of the game. // * @param grenades amount of grenades available to clear the current level. // */ // public void init(int badgeScale, int enemies, int grenades) { // if (gameFinalized == true) // return; // // this.badgeScale = (badgeScale > 0) ? badgeScale : 1; // this.enemyCount = enemies; // this.grenades = new Grenades(grenades); // } // // /** // * Add points achieved by the player. // * @param value point added. // * @param enemyDestroyed was enemy destroyed when points were achieved? // */ // public void addPoints(int value, boolean enemyDestroyed) { // if (gameFinalized) // return; // // score += value; // if (enemyDestroyed) // enemyCount--; // } // // /** // * Get current score status. // * @return score counter value. // */ // public int getScore() { // return score; // } // // public Grenades getGrenades() { // return this.grenades; // } // // /** // * Get number of achieved badges. // * @return number of badges between 0..3, // */ // public int getBadges() { // if (enemyCount == 0) // return MathUtils.clamp(score / badgeScale, 0, 3); // return 0; // } // // /** // * Update statuses. // * @return true if game continues, false if game is end. // */ // public boolean update() { // if (gameFinalized) // return false; // // if (enemyCount <= 0) // return false; // // if (grenades.getCount() == 0) // return false; // // return true; // } // // /** // * Count final score and return level cleared status. // * @return true if player cleared the level. // */ // public boolean countFinalScore() { // if (gameFinalized == false) { // gameFinalized = true; // // score += grenades.getCount() * 150; // } // // return enemyCount == 0; // } // // @Override // public String toString() { // return "Score: " + score; // } // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import fi.hbp.angr.logic.GameState;
package fi.hbp.angr.hud; /** * HudScoreCounter used to show current game score status. */ public class HudGameStateDisplay implements Hud.HudActor { private BitmapFont font;
// Path: workspace/Angr/src/fi/hbp/angr/logic/GameState.java // public class GameState { // /** // * Grenade counter. // */ // public class Grenades { // /** // * Amount of grenades at the beginning. // */ // public final int originalCount; // /** // * Current count. // */ // private int count; // // /** // * Constructor for Grenades class. // * @param amount Amount of grenades available. // */ // public Grenades(int amount) { // this.originalCount = amount; // this.count = amount; // } // // /** // * Decrement amount of grenades by one. // */ // public void decrement() { // if (count > 0) // count--; // } // // /** // * Returns current grenade count. // * @return current grenade count. // */ // public int getCount() { // return count; // } // } // // /** // * Game score. // */ // private int score = 0; // /** // * Badge scaling. // */ // private int badgeScale = 1; // /** // * Enemies left in this map. // */ // private int enemyCount = 0; // /** // * Grenade counter. // */ // private Grenades grenades = new Grenades(0); // /** // * All game stats calculated true/false. // */ // private boolean gameFinalized = false; // // /** // * Initialize game state object. // * @param badgeScale points needed to achieve one badge. // * @param enemies enemy count on the current level at the beginning of the game. // * @param grenades amount of grenades available to clear the current level. // */ // public void init(int badgeScale, int enemies, int grenades) { // if (gameFinalized == true) // return; // // this.badgeScale = (badgeScale > 0) ? badgeScale : 1; // this.enemyCount = enemies; // this.grenades = new Grenades(grenades); // } // // /** // * Add points achieved by the player. // * @param value point added. // * @param enemyDestroyed was enemy destroyed when points were achieved? // */ // public void addPoints(int value, boolean enemyDestroyed) { // if (gameFinalized) // return; // // score += value; // if (enemyDestroyed) // enemyCount--; // } // // /** // * Get current score status. // * @return score counter value. // */ // public int getScore() { // return score; // } // // public Grenades getGrenades() { // return this.grenades; // } // // /** // * Get number of achieved badges. // * @return number of badges between 0..3, // */ // public int getBadges() { // if (enemyCount == 0) // return MathUtils.clamp(score / badgeScale, 0, 3); // return 0; // } // // /** // * Update statuses. // * @return true if game continues, false if game is end. // */ // public boolean update() { // if (gameFinalized) // return false; // // if (enemyCount <= 0) // return false; // // if (grenades.getCount() == 0) // return false; // // return true; // } // // /** // * Count final score and return level cleared status. // * @return true if player cleared the level. // */ // public boolean countFinalScore() { // if (gameFinalized == false) { // gameFinalized = true; // // score += grenades.getCount() * 150; // } // // return enemyCount == 0; // } // // @Override // public String toString() { // return "Score: " + score; // } // } // Path: workspace/Angr/src/fi/hbp/angr/hud/HudGameStateDisplay.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import fi.hbp.angr.logic.GameState; package fi.hbp.angr.hud; /** * HudScoreCounter used to show current game score status. */ public class HudGameStateDisplay implements Hud.HudActor { private BitmapFont font;
private final GameState gameState;
OlliV/angr
workspace/Angr-desktop/test/fi/hbp/angr/BodyFactoryTest.java
// Path: workspace/Angr/src/fi/hbp/angr/BodyFactory.java // public class BodyFactory { // private final GameStage stage; // private final InputMultiplexer inputMultiplexer; // private final BodyEditorLoader bel; // protected AssetContainer asGrenade = new AssetContainer(); // protected AssetContainer asBox = new AssetContainer(); // protected Hans.HansAssetContainer hac = new Hans.HansAssetContainer(); // // private static boolean preloaded = false; // // /** // * Add assets of this class to a preload list. // */ // public static void preload() { // if (!preloaded) { // Grenade.preload(); // Box.preload(); // Hans.preload(); // // preloaded = true; // } // } // // /* TODO Should the map/level tell what assets it will need? */ // // /* TODO Add a function to unload unneeded assets? */ // // /** // * Constructor for body factory. // * @param stage the game stage. // * @param inputMultiplexer input multiplexer for adding new input processor. // */ // public BodyFactory(GameStage stage, InputMultiplexer inputMultiplexer) { // this.stage = stage; // this.inputMultiplexer = inputMultiplexer; // // bel = new BodyEditorLoader(Gdx.files.internal("models.json")); // // /* Initialize assets */ // Grenade.initAssets(asGrenade, bel); // Box.initAssets(asBox, bel); // Hans.initAssets(hac, bel); // } // // /** // * Get world used by body factory and game stage // * @return Box2D world. // */ // public World getWorld() { // return stage.getWorld(); // } // // /** // * Spawns a new grenade to the game stage // * @param x position on x axis. // * @param y position on y axis. // * @param angle body angle. // * @return actor of the new game object. // */ // public Actor spawnGrenade(float x, float y, float angle) { // Grenade actor = new Grenade(stage, bel, asGrenade, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // ((GameStage)stage).setCameraFollow(((Grenade)actor).getBody()); // return actor; // } // // /** // * Spawns a new box t othe game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnBox(float x, float y, float angle) { // Box actor = new Box(stage, bel, asBox, x, y, angle); // stage.addActor(actor); // return actor; // } // // /** // * Spawns a new Hans player model to the game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnHans(float x, float y, float angle) { // Hans actor = new Hans(stage, bel, hac, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // return actor; // } // } // // Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.badlogic.gdx.InputMultiplexer; import fi.hbp.angr.BodyFactory; import fi.hbp.angr.G;
/** * */ package fi.hbp.angr; /** * @author hbp * */ public class BodyFactoryTest { static InputMultiplexer inputMultiplexer;
// Path: workspace/Angr/src/fi/hbp/angr/BodyFactory.java // public class BodyFactory { // private final GameStage stage; // private final InputMultiplexer inputMultiplexer; // private final BodyEditorLoader bel; // protected AssetContainer asGrenade = new AssetContainer(); // protected AssetContainer asBox = new AssetContainer(); // protected Hans.HansAssetContainer hac = new Hans.HansAssetContainer(); // // private static boolean preloaded = false; // // /** // * Add assets of this class to a preload list. // */ // public static void preload() { // if (!preloaded) { // Grenade.preload(); // Box.preload(); // Hans.preload(); // // preloaded = true; // } // } // // /* TODO Should the map/level tell what assets it will need? */ // // /* TODO Add a function to unload unneeded assets? */ // // /** // * Constructor for body factory. // * @param stage the game stage. // * @param inputMultiplexer input multiplexer for adding new input processor. // */ // public BodyFactory(GameStage stage, InputMultiplexer inputMultiplexer) { // this.stage = stage; // this.inputMultiplexer = inputMultiplexer; // // bel = new BodyEditorLoader(Gdx.files.internal("models.json")); // // /* Initialize assets */ // Grenade.initAssets(asGrenade, bel); // Box.initAssets(asBox, bel); // Hans.initAssets(hac, bel); // } // // /** // * Get world used by body factory and game stage // * @return Box2D world. // */ // public World getWorld() { // return stage.getWorld(); // } // // /** // * Spawns a new grenade to the game stage // * @param x position on x axis. // * @param y position on y axis. // * @param angle body angle. // * @return actor of the new game object. // */ // public Actor spawnGrenade(float x, float y, float angle) { // Grenade actor = new Grenade(stage, bel, asGrenade, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // ((GameStage)stage).setCameraFollow(((Grenade)actor).getBody()); // return actor; // } // // /** // * Spawns a new box t othe game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnBox(float x, float y, float angle) { // Box actor = new Box(stage, bel, asBox, x, y, angle); // stage.addActor(actor); // return actor; // } // // /** // * Spawns a new Hans player model to the game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnHans(float x, float y, float angle) { // Hans actor = new Hans(stage, bel, hac, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // return actor; // } // } // // Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // Path: workspace/Angr-desktop/test/fi/hbp/angr/BodyFactoryTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.badlogic.gdx.InputMultiplexer; import fi.hbp.angr.BodyFactory; import fi.hbp.angr.G; /** * */ package fi.hbp.angr; /** * @author hbp * */ public class BodyFactoryTest { static InputMultiplexer inputMultiplexer;
BodyFactory bf;
OlliV/angr
workspace/Angr-desktop/test/fi/hbp/angr/BodyFactoryTest.java
// Path: workspace/Angr/src/fi/hbp/angr/BodyFactory.java // public class BodyFactory { // private final GameStage stage; // private final InputMultiplexer inputMultiplexer; // private final BodyEditorLoader bel; // protected AssetContainer asGrenade = new AssetContainer(); // protected AssetContainer asBox = new AssetContainer(); // protected Hans.HansAssetContainer hac = new Hans.HansAssetContainer(); // // private static boolean preloaded = false; // // /** // * Add assets of this class to a preload list. // */ // public static void preload() { // if (!preloaded) { // Grenade.preload(); // Box.preload(); // Hans.preload(); // // preloaded = true; // } // } // // /* TODO Should the map/level tell what assets it will need? */ // // /* TODO Add a function to unload unneeded assets? */ // // /** // * Constructor for body factory. // * @param stage the game stage. // * @param inputMultiplexer input multiplexer for adding new input processor. // */ // public BodyFactory(GameStage stage, InputMultiplexer inputMultiplexer) { // this.stage = stage; // this.inputMultiplexer = inputMultiplexer; // // bel = new BodyEditorLoader(Gdx.files.internal("models.json")); // // /* Initialize assets */ // Grenade.initAssets(asGrenade, bel); // Box.initAssets(asBox, bel); // Hans.initAssets(hac, bel); // } // // /** // * Get world used by body factory and game stage // * @return Box2D world. // */ // public World getWorld() { // return stage.getWorld(); // } // // /** // * Spawns a new grenade to the game stage // * @param x position on x axis. // * @param y position on y axis. // * @param angle body angle. // * @return actor of the new game object. // */ // public Actor spawnGrenade(float x, float y, float angle) { // Grenade actor = new Grenade(stage, bel, asGrenade, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // ((GameStage)stage).setCameraFollow(((Grenade)actor).getBody()); // return actor; // } // // /** // * Spawns a new box t othe game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnBox(float x, float y, float angle) { // Box actor = new Box(stage, bel, asBox, x, y, angle); // stage.addActor(actor); // return actor; // } // // /** // * Spawns a new Hans player model to the game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnHans(float x, float y, float angle) { // Hans actor = new Hans(stage, bel, hac, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // return actor; // } // } // // Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.badlogic.gdx.InputMultiplexer; import fi.hbp.angr.BodyFactory; import fi.hbp.angr.G;
/** * */ package fi.hbp.angr; /** * @author hbp * */ public class BodyFactoryTest { static InputMultiplexer inputMultiplexer; BodyFactory bf; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { inputMultiplexer = new InputMultiplexer(); BodyFactory.preload(); } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception {
// Path: workspace/Angr/src/fi/hbp/angr/BodyFactory.java // public class BodyFactory { // private final GameStage stage; // private final InputMultiplexer inputMultiplexer; // private final BodyEditorLoader bel; // protected AssetContainer asGrenade = new AssetContainer(); // protected AssetContainer asBox = new AssetContainer(); // protected Hans.HansAssetContainer hac = new Hans.HansAssetContainer(); // // private static boolean preloaded = false; // // /** // * Add assets of this class to a preload list. // */ // public static void preload() { // if (!preloaded) { // Grenade.preload(); // Box.preload(); // Hans.preload(); // // preloaded = true; // } // } // // /* TODO Should the map/level tell what assets it will need? */ // // /* TODO Add a function to unload unneeded assets? */ // // /** // * Constructor for body factory. // * @param stage the game stage. // * @param inputMultiplexer input multiplexer for adding new input processor. // */ // public BodyFactory(GameStage stage, InputMultiplexer inputMultiplexer) { // this.stage = stage; // this.inputMultiplexer = inputMultiplexer; // // bel = new BodyEditorLoader(Gdx.files.internal("models.json")); // // /* Initialize assets */ // Grenade.initAssets(asGrenade, bel); // Box.initAssets(asBox, bel); // Hans.initAssets(hac, bel); // } // // /** // * Get world used by body factory and game stage // * @return Box2D world. // */ // public World getWorld() { // return stage.getWorld(); // } // // /** // * Spawns a new grenade to the game stage // * @param x position on x axis. // * @param y position on y axis. // * @param angle body angle. // * @return actor of the new game object. // */ // public Actor spawnGrenade(float x, float y, float angle) { // Grenade actor = new Grenade(stage, bel, asGrenade, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // ((GameStage)stage).setCameraFollow(((Grenade)actor).getBody()); // return actor; // } // // /** // * Spawns a new box t othe game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnBox(float x, float y, float angle) { // Box actor = new Box(stage, bel, asBox, x, y, angle); // stage.addActor(actor); // return actor; // } // // /** // * Spawns a new Hans player model to the game stage // * @param x Position on x axis. // * @param y Position on y axis. // * @param angle Body angle. // * @return Actor of the new game object. // */ // public Actor spawnHans(float x, float y, float angle) { // Hans actor = new Hans(stage, bel, hac, x, y, angle); // inputMultiplexer.addProcessor(actor); // stage.addActor(actor); // return actor; // } // } // // Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // Path: workspace/Angr-desktop/test/fi/hbp/angr/BodyFactoryTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.badlogic.gdx.InputMultiplexer; import fi.hbp.angr.BodyFactory; import fi.hbp.angr.G; /** * */ package fi.hbp.angr; /** * @author hbp * */ public class BodyFactoryTest { static InputMultiplexer inputMultiplexer; BodyFactory bf; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { inputMultiplexer = new InputMultiplexer(); BodyFactory.preload(); } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception {
G.getAssetManager().clear();
OlliV/angr
workspace/Angr-desktop/test/fi/hbp/angr/logic/ModelContactListenerTest.java
// Path: workspace/Angr/src/fi/hbp/angr/models/Destructible.java // public interface Destructible { // /** // * Get damage model of this object // * @return Damage model // */ // DamageModel getDatamageModel(); // // /** // * Set body as destroyed // * // * This information can be used for sprite rendering. // */ // void setDestroyed(); // // /** // * Get destroyed status // */ // boolean isDestroyed(); // // /** // * Get Box2D body // * // * This is used to remove body from the world // * @return Body. // */ // Body getBody(); // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.fail; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; 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 com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.GdxNativesLoader; import fi.hbp.angr.models.Destructible;
package fi.hbp.angr.logic; public class ModelContactListenerTest { World world; GameState gameState; ModelContactListener listener;
// Path: workspace/Angr/src/fi/hbp/angr/models/Destructible.java // public interface Destructible { // /** // * Get damage model of this object // * @return Damage model // */ // DamageModel getDatamageModel(); // // /** // * Set body as destroyed // * // * This information can be used for sprite rendering. // */ // void setDestroyed(); // // /** // * Get destroyed status // */ // boolean isDestroyed(); // // /** // * Get Box2D body // * // * This is used to remove body from the world // * @return Body. // */ // Body getBody(); // } // Path: workspace/Angr-desktop/test/fi/hbp/angr/logic/ModelContactListenerTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.fail; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; 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 com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.utils.GdxNativesLoader; import fi.hbp.angr.models.Destructible; package fi.hbp.angr.logic; public class ModelContactListenerTest { World world; GameState gameState; ModelContactListener listener;
protected class TestActor extends Actor implements Destructible {
OlliV/angr
workspace/Angr/src/fi/hbp/angr/screens/ScreenLoader.java
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/Preloadable.java // public interface Preloadable { // /** // * Start preloading assets. // * // * This method should only contain asynchronous loading calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Loading_Assets // */ // public void preload(); // // public void create(); // // /** // * Unload assets. // * // * This method should mainly contain dispose/unload method calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Disposing_Assets // */ // public void unload(); // }
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import fi.hbp.angr.G; import fi.hbp.angr.Preloadable;
package fi.hbp.angr.screens; /** * Preload a given Screen. * * Creates an instance of a screen of given type and loads its assets. This * is useful and works only if constructor of the new screen class loads all * assets needed. */ public class ScreenLoader { /** * Game. */ private final Game game; /** * Screen that will be preloaded and then switched to. */ private final Screen screen; /** * Reentrant lock. */ private final Lock l = new ReentrantLock(); /** * Loading status. * true if preloading has been started. * This doesn't actually tell whether preloading is ready or not. */ private boolean loaded = false; /** * Constructor for ScreenLoader. * @param game main game object. * @param screen screen to be loaded. */ public ScreenLoader(Game game, Screen screen) { this.game = game; this.screen = screen; } /** * Fills preload queue. */ public void start() { l.lock(); try {
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/Preloadable.java // public interface Preloadable { // /** // * Start preloading assets. // * // * This method should only contain asynchronous loading calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Loading_Assets // */ // public void preload(); // // public void create(); // // /** // * Unload assets. // * // * This method should mainly contain dispose/unload method calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Disposing_Assets // */ // public void unload(); // } // Path: workspace/Angr/src/fi/hbp/angr/screens/ScreenLoader.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import fi.hbp.angr.G; import fi.hbp.angr.Preloadable; package fi.hbp.angr.screens; /** * Preload a given Screen. * * Creates an instance of a screen of given type and loads its assets. This * is useful and works only if constructor of the new screen class loads all * assets needed. */ public class ScreenLoader { /** * Game. */ private final Game game; /** * Screen that will be preloaded and then switched to. */ private final Screen screen; /** * Reentrant lock. */ private final Lock l = new ReentrantLock(); /** * Loading status. * true if preloading has been started. * This doesn't actually tell whether preloading is ready or not. */ private boolean loaded = false; /** * Constructor for ScreenLoader. * @param game main game object. * @param screen screen to be loaded. */ public ScreenLoader(Game game, Screen screen) { this.game = game; this.screen = screen; } /** * Fills preload queue. */ public void start() { l.lock(); try {
if (Preloadable.class.isInstance(screen)) {
OlliV/angr
workspace/Angr/src/fi/hbp/angr/screens/ScreenLoader.java
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/Preloadable.java // public interface Preloadable { // /** // * Start preloading assets. // * // * This method should only contain asynchronous loading calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Loading_Assets // */ // public void preload(); // // public void create(); // // /** // * Unload assets. // * // * This method should mainly contain dispose/unload method calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Disposing_Assets // */ // public void unload(); // }
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import fi.hbp.angr.G; import fi.hbp.angr.Preloadable;
package fi.hbp.angr.screens; /** * Preload a given Screen. * * Creates an instance of a screen of given type and loads its assets. This * is useful and works only if constructor of the new screen class loads all * assets needed. */ public class ScreenLoader { /** * Game. */ private final Game game; /** * Screen that will be preloaded and then switched to. */ private final Screen screen; /** * Reentrant lock. */ private final Lock l = new ReentrantLock(); /** * Loading status. * true if preloading has been started. * This doesn't actually tell whether preloading is ready or not. */ private boolean loaded = false; /** * Constructor for ScreenLoader. * @param game main game object. * @param screen screen to be loaded. */ public ScreenLoader(Game game, Screen screen) { this.game = game; this.screen = screen; } /** * Fills preload queue. */ public void start() { l.lock(); try { if (Preloadable.class.isInstance(screen)) { ((Preloadable)screen).preload(); } loaded = true; } finally { l.unlock(); } } /** * Updates the AssetManager, keeping it loading any assets in the preload queue. * @return true if all loading is finished. */ public boolean update() {
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/Preloadable.java // public interface Preloadable { // /** // * Start preloading assets. // * // * This method should only contain asynchronous loading calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Loading_Assets // */ // public void preload(); // // public void create(); // // /** // * Unload assets. // * // * This method should mainly contain dispose/unload method calls described in: // * http://code.google.com/p/libgdx/wiki/AssetManager#Disposing_Assets // */ // public void unload(); // } // Path: workspace/Angr/src/fi/hbp/angr/screens/ScreenLoader.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import fi.hbp.angr.G; import fi.hbp.angr.Preloadable; package fi.hbp.angr.screens; /** * Preload a given Screen. * * Creates an instance of a screen of given type and loads its assets. This * is useful and works only if constructor of the new screen class loads all * assets needed. */ public class ScreenLoader { /** * Game. */ private final Game game; /** * Screen that will be preloaded and then switched to. */ private final Screen screen; /** * Reentrant lock. */ private final Lock l = new ReentrantLock(); /** * Loading status. * true if preloading has been started. * This doesn't actually tell whether preloading is ready or not. */ private boolean loaded = false; /** * Constructor for ScreenLoader. * @param game main game object. * @param screen screen to be loaded. */ public ScreenLoader(Game game, Screen screen) { this.game = game; this.screen = screen; } /** * Fills preload queue. */ public void start() { l.lock(); try { if (Preloadable.class.isInstance(screen)) { ((Preloadable)screen).preload(); } loaded = true; } finally { l.unlock(); } } /** * Updates the AssetManager, keeping it loading any assets in the preload queue. * @return true if all loading is finished. */ public boolean update() {
return G.getAssetManager().update();
OlliV/angr
workspace/Angr/src/fi/hbp/angr/models/levels/TestLevel.java
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/models/CollisionFilterMasks.java // public class CollisionFilterMasks { // public static final short GROUND = 0x01; // public static final short HANS_BODY = 0x02; // public static final short HANS_HAND = 0x04; // public static final short GRENADE = 0x08; // /** // * Other than listed here. // */ // public static final short OTHER = 0x16; // /** // * All bodies. // */ // public static final short ALL = 0xff; // }
import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.physics.box2d.FixtureDef; import fi.hbp.angr.G; import fi.hbp.angr.models.CollisionFilterMasks;
package fi.hbp.angr.models.levels; /** * Test map/level. */ public class TestLevel extends Level { /** * Music file path. */ private static final String MUSIC_PATH = "data/march.mp3"; /** * Game music. */ private Music music; /** * Constructor for this level. */ public TestLevel() { super("mappi", 5); } @Override public void doOnPreload() {
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/models/CollisionFilterMasks.java // public class CollisionFilterMasks { // public static final short GROUND = 0x01; // public static final short HANS_BODY = 0x02; // public static final short HANS_HAND = 0x04; // public static final short GRENADE = 0x08; // /** // * Other than listed here. // */ // public static final short OTHER = 0x16; // /** // * All bodies. // */ // public static final short ALL = 0xff; // } // Path: workspace/Angr/src/fi/hbp/angr/models/levels/TestLevel.java import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.physics.box2d.FixtureDef; import fi.hbp.angr.G; import fi.hbp.angr.models.CollisionFilterMasks; package fi.hbp.angr.models.levels; /** * Test map/level. */ public class TestLevel extends Level { /** * Music file path. */ private static final String MUSIC_PATH = "data/march.mp3"; /** * Game music. */ private Music music; /** * Constructor for this level. */ public TestLevel() { super("mappi", 5); } @Override public void doOnPreload() {
G.getAssetManager().load(MUSIC_PATH, Music.class);
OlliV/angr
workspace/Angr/src/fi/hbp/angr/models/levels/TestLevel.java
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/models/CollisionFilterMasks.java // public class CollisionFilterMasks { // public static final short GROUND = 0x01; // public static final short HANS_BODY = 0x02; // public static final short HANS_HAND = 0x04; // public static final short GRENADE = 0x08; // /** // * Other than listed here. // */ // public static final short OTHER = 0x16; // /** // * All bodies. // */ // public static final short ALL = 0xff; // }
import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.physics.box2d.FixtureDef; import fi.hbp.angr.G; import fi.hbp.angr.models.CollisionFilterMasks;
package fi.hbp.angr.models.levels; /** * Test map/level. */ public class TestLevel extends Level { /** * Music file path. */ private static final String MUSIC_PATH = "data/march.mp3"; /** * Game music. */ private Music music; /** * Constructor for this level. */ public TestLevel() { super("mappi", 5); } @Override public void doOnPreload() { G.getAssetManager().load(MUSIC_PATH, Music.class); } @Override public void doOnUnload() { music.stop(); G.getAssetManager().unload(MUSIC_PATH); } @Override public void doOnCreate() { /* Initialize game state */ gs.init(550, /* Badge scaling */ 10, /* Enemy count */ 10); /* Grenade count */ /* Create terrain fixture definition */ FixtureDef fd = new FixtureDef(); fd.density = 0.6f; fd.friction = 0.7f; fd.restitution = 0.3f;
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // // Path: workspace/Angr/src/fi/hbp/angr/models/CollisionFilterMasks.java // public class CollisionFilterMasks { // public static final short GROUND = 0x01; // public static final short HANS_BODY = 0x02; // public static final short HANS_HAND = 0x04; // public static final short GRENADE = 0x08; // /** // * Other than listed here. // */ // public static final short OTHER = 0x16; // /** // * All bodies. // */ // public static final short ALL = 0xff; // } // Path: workspace/Angr/src/fi/hbp/angr/models/levels/TestLevel.java import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.physics.box2d.FixtureDef; import fi.hbp.angr.G; import fi.hbp.angr.models.CollisionFilterMasks; package fi.hbp.angr.models.levels; /** * Test map/level. */ public class TestLevel extends Level { /** * Music file path. */ private static final String MUSIC_PATH = "data/march.mp3"; /** * Game music. */ private Music music; /** * Constructor for this level. */ public TestLevel() { super("mappi", 5); } @Override public void doOnPreload() { G.getAssetManager().load(MUSIC_PATH, Music.class); } @Override public void doOnUnload() { music.stop(); G.getAssetManager().unload(MUSIC_PATH); } @Override public void doOnCreate() { /* Initialize game state */ gs.init(550, /* Badge scaling */ 10, /* Enemy count */ 10); /* Grenade count */ /* Create terrain fixture definition */ FixtureDef fd = new FixtureDef(); fd.density = 0.6f; fd.friction = 0.7f; fd.restitution = 0.3f;
fd.filter.categoryBits = CollisionFilterMasks.GROUND;
OlliV/angr
workspace/Angr/src/fi/hbp/angr/hud/Hud.java
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // }
import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import fi.hbp.angr.G;
package fi.hbp.angr.hud; /** * Drawable HUD. */ public class Hud { /** * Font for drawing HUD. */ private BitmapFont font = new BitmapFont(); /** * Batch for drawing this HUD. */ private SpriteBatch hudBatch; /** * List of actors in this HUD. */ private ArrayList<HudActor> actors = new ArrayList<HudActor>(); /** * HudActor that can be drawn by a Hud object. */ public interface HudActor { /** * Draw this HudActor now. * @param batch sprite batch to be used for drawing. */ public void draw(SpriteBatch batch); } /** * Constructor for Hud. */ public Hud() { hudBatch = new SpriteBatch(); font.setColor(Color.RED); font.setScale(1.0f); } /** * Adds the specified HudActor to the list of actors that will * be drawn on the screen. * @param actor element that is added to the list. */ public void addActor(HudActor actor) { actors.add(actor); } /** * Removes all of the elements from the HUD actor list. * The list will be empty after this call returns. */ public void clear() { actors.clear(); } /** * Draw this HUD. */ public void draw() { hudBatch.begin();
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // Path: workspace/Angr/src/fi/hbp/angr/hud/Hud.java import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import fi.hbp.angr.G; package fi.hbp.angr.hud; /** * Drawable HUD. */ public class Hud { /** * Font for drawing HUD. */ private BitmapFont font = new BitmapFont(); /** * Batch for drawing this HUD. */ private SpriteBatch hudBatch; /** * List of actors in this HUD. */ private ArrayList<HudActor> actors = new ArrayList<HudActor>(); /** * HudActor that can be drawn by a Hud object. */ public interface HudActor { /** * Draw this HudActor now. * @param batch sprite batch to be used for drawing. */ public void draw(SpriteBatch batch); } /** * Constructor for Hud. */ public Hud() { hudBatch = new SpriteBatch(); font.setColor(Color.RED); font.setScale(1.0f); } /** * Adds the specified HudActor to the list of actors that will * be drawn on the screen. * @param actor element that is added to the list. */ public void addActor(HudActor actor) { actors.add(actor); } /** * Removes all of the elements from the HUD actor list. * The list will be empty after this call returns. */ public void clear() { actors.clear(); } /** * Draw this HUD. */ public void draw() { hudBatch.begin();
if (G.DEBUG)
OlliV/angr
workspace/Angr/src/fi/hbp/angr/models/SlingshotActor.java
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // }
import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; 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.Fixture; import com.badlogic.gdx.physics.box2d.QueryCallback; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import fi.hbp.angr.G;
* to which we can connect the mouse joint */ BodyDef bodyDef = new BodyDef(); groundBody = world.createBody(bodyDef); } QueryCallback callback = new QueryCallback() { @Override public boolean reportFixture (Fixture fixture) { /* If the hit point is inside the fixture of the body /* we report it */ Vector2 v = fixture.getBody().getPosition(); if (fixture.testPoint(testPoint.x, testPoint.y) || v.dst(testPoint.x, testPoint.y) < touchDst) { hitBody = fixture.getBody(); if (hitBody.equals(body)) { return false; } } return true; /* Keep going until all bodies in the area are checked. */ } }; @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { if (slingshotEnabled == false) return false; /* Translate the mouse coordinates to world coordinates */ stage.getCamera().unproject(testPoint.set(screenX, screenY, 0));
// Path: workspace/Angr/src/fi/hbp/angr/G.java // public class G { // /** // * Debug mode // * // * If this is set to true game will output some additional data and // * enables debug camera functionality. Debug camera is enabled by // * pressing d while in the game stage. // */ // public static final boolean DEBUG = false; // // /** // * Global static assets manager // * // * @note As there is no universal support for threaded access to the // * OpenGL context from multiple threads and as its exclusively prohibited // * in gdx a global asset manager is needed. This asset manager makes it // * easier to load new assets asynchronously without blocking rendering. // */ // private static AssetManager assetManager = new AssetManager(); // // /** // * Conversion from Box2D to the sprite relative/pixel coordinates // */ // public static final float BOX_TO_WORLD = 100.0f; // // /** // * Conversion from sprite relative/pixel coordinates to Box2D coordinates // */ // public static final float WORLD_TO_BOX = 1.0f / BOX_TO_WORLD; // // /** // * Get global static assets manager // * @return Global asset manager. // */ // public static AssetManager getAssetManager() { // return assetManager; // } // // /** // * Game scoreboard // */ // public static Scoreboard scoreboard = null; // // /** // * Game pause button // */ // public static int pauseButton = Keys.P; // public static int pauseButton1 = Keys.BACK; // } // Path: workspace/Angr/src/fi/hbp/angr/models/SlingshotActor.java import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; 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.Fixture; import com.badlogic.gdx.physics.box2d.QueryCallback; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import fi.hbp.angr.G; * to which we can connect the mouse joint */ BodyDef bodyDef = new BodyDef(); groundBody = world.createBody(bodyDef); } QueryCallback callback = new QueryCallback() { @Override public boolean reportFixture (Fixture fixture) { /* If the hit point is inside the fixture of the body /* we report it */ Vector2 v = fixture.getBody().getPosition(); if (fixture.testPoint(testPoint.x, testPoint.y) || v.dst(testPoint.x, testPoint.y) < touchDst) { hitBody = fixture.getBody(); if (hitBody.equals(body)) { return false; } } return true; /* Keep going until all bodies in the area are checked. */ } }; @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { if (slingshotEnabled == false) return false; /* Translate the mouse coordinates to world coordinates */ stage.getCamera().unproject(testPoint.set(screenX, screenY, 0));
testPoint.x *= G.WORLD_TO_BOX;
OlliV/angr
workspace/Angr/src/fi/hbp/angr/logic/ModelContactListener.java
// Path: workspace/Angr/src/fi/hbp/angr/models/Destructible.java // public interface Destructible { // /** // * Get damage model of this object // * @return Damage model // */ // DamageModel getDatamageModel(); // // /** // * Set body as destroyed // * // * This information can be used for sprite rendering. // */ // void setDestroyed(); // // /** // * Get destroyed status // */ // boolean isDestroyed(); // // /** // * Get Box2D body // * // * This is used to remove body from the world // * @return Body. // */ // Body getBody(); // }
import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import fi.hbp.angr.models.Destructible;
package fi.hbp.angr.logic; /** * Model contact listener for damage modeling. */ public class ModelContactListener implements ContactListener { protected final GameState gameState; /** * Contructor for ModelContactListerner. * @param gameState game state object. */ public ModelContactListener(GameState gameState) {; this.gameState = gameState; } @Override public void beginContact(Contact arg0) { } @Override public void endContact(Contact arg0) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { if(impulse.getNormalImpulses()[0] > 0.01) { /* If body A was hit */ if(contact.getFixtureA() != null) { if (Actor.class.isInstance(contact.getFixtureA().getBody().getUserData())) { Actor a = (Actor) contact.getFixtureA().getBody().getUserData(); evalDamage(a, impulse); } } /* If body B was hit */ if(contact.getFixtureB() != null) { if (Actor.class.isInstance(contact.getFixtureB().getBody().getUserData())) { Actor b = (Actor) contact.getFixtureB().getBody().getUserData(); evalDamage(b, impulse); } } } } /** * Evaluate damage and score, and check if actor needs to be destroyed * @param actor Current actor * @param impulse Impulse */ private void evalDamage(Actor actor, ContactImpulse impulse) {
// Path: workspace/Angr/src/fi/hbp/angr/models/Destructible.java // public interface Destructible { // /** // * Get damage model of this object // * @return Damage model // */ // DamageModel getDatamageModel(); // // /** // * Set body as destroyed // * // * This information can be used for sprite rendering. // */ // void setDestroyed(); // // /** // * Get destroyed status // */ // boolean isDestroyed(); // // /** // * Get Box2D body // * // * This is used to remove body from the world // * @return Body. // */ // Body getBody(); // } // Path: workspace/Angr/src/fi/hbp/angr/logic/ModelContactListener.java import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Manifold; import com.badlogic.gdx.scenes.scene2d.Actor; import fi.hbp.angr.models.Destructible; package fi.hbp.angr.logic; /** * Model contact listener for damage modeling. */ public class ModelContactListener implements ContactListener { protected final GameState gameState; /** * Contructor for ModelContactListerner. * @param gameState game state object. */ public ModelContactListener(GameState gameState) {; this.gameState = gameState; } @Override public void beginContact(Contact arg0) { } @Override public void endContact(Contact arg0) { } @Override public void postSolve(Contact contact, ContactImpulse impulse) { if(impulse.getNormalImpulses()[0] > 0.01) { /* If body A was hit */ if(contact.getFixtureA() != null) { if (Actor.class.isInstance(contact.getFixtureA().getBody().getUserData())) { Actor a = (Actor) contact.getFixtureA().getBody().getUserData(); evalDamage(a, impulse); } } /* If body B was hit */ if(contact.getFixtureB() != null) { if (Actor.class.isInstance(contact.getFixtureB().getBody().getUserData())) { Actor b = (Actor) contact.getFixtureB().getBody().getUserData(); evalDamage(b, impulse); } } } } /** * Evaluate damage and score, and check if actor needs to be destroyed * @param actor Current actor * @param impulse Impulse */ private void evalDamage(Actor actor, ContactImpulse impulse) {
if (Destructible.class.isInstance(actor)) {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle;
package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id";
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle; package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id";
public static final BaseFragment createMainFragment(DataType type) {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle;
package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id";
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle; package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id";
public static final BaseFragment createMainFragment(DataType type) {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle;
package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id"; public static final BaseFragment createMainFragment(DataType type) { BaseFragment fragment = null; switch (type) { case NET_EASY:
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle; package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id"; public static final BaseFragment createMainFragment(DataType type) { BaseFragment fragment = null; switch (type) { case NET_EASY:
fragment = new NetEasyVideoFragment();
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle;
package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id"; public static final BaseFragment createMainFragment(DataType type) { BaseFragment fragment = null; switch (type) { case NET_EASY: fragment = new NetEasyVideoFragment(); break; case TTKB:
// Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/BaseFragment.java // public abstract class BaseFragment<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>> // extends MvpLceFragment<CV, M, V, P> implements NameFragment { // // protected Context mContext; // private boolean mIsInited = false; // // @Override // public void onAttach(Context context) { // // super.onAttach(context); // mContext = context; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // // ViewGroup view = (ViewGroup) inflater.inflate(R.layout.base_fragment_layout, container, false); // // view.addView(getContentView(inflater, savedInstanceState)); // // return view; // } // // @Override // public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { // // super.onViewCreated(view, savedInstanceState); // showLoading(false); // if(isInitRefreshEnable() && isDelayRefreshEnable() == false) { // loadData(false); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // // super.setUserVisibleHint(isVisibleToUser); // if(isVisibleToUser && isInitRefreshEnable() == false && isDelayRefreshEnable() && mIsInited == false) { // mIsInited = true; // refreshData(false); // } // } // // private void refreshData(final boolean pullToRefresh) { // // if(presenter != null) { // loadData(pullToRefresh); // } else { // Observable.timer(50, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long aLong) { // refreshData(pullToRefresh); // } // }); // } // } // // /** // * Fragment数据视图 // * @param inflater // * @param savedInstanceState // * @return // */ // public abstract View getContentView(LayoutInflater inflater, @Nullable Bundle savedInstanceState); // // public boolean isInitRefreshEnable() { // // return true; // } // // public boolean isDelayRefreshEnable() { // // return false; // } // // @Override // protected String getErrorMessage(Throwable e, boolean pullToRefresh) { // // return getActivity().getString(R.string.load_failed); // } // // @Override // public void showLoading(boolean pullToRefresh) { // // super.showLoading(pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).start(); // } // } // // @Override // public void showContent() { // // super.showContent(); // ((LoadingView)loadingView).stop(); // } // // @Override // public void showError(Throwable e, boolean pullToRefresh) { // // super.showError(e, pullToRefresh); // if(!pullToRefresh) { // ((LoadingView)loadingView).stop(); // } // } // // @Override // public void onDestroyView() { // // super.onDestroyView(); // presenter = null; // mIsInited = false; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java // public class NetEasyVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new NetEasyVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.net_easy_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java // public class TtKbVideoFragment extends VideoFragment { // // @Override // public VideoPresenter createPresenter() { // // return new TtKbVideoPresenter(); // } // // @Override // public int getName() { // // return R.string.ttkb_video; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/FragmentFactory.java import cn.ittiger.video.fragment.BaseFragment; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.fragment.IFengTabFragment; import cn.ittiger.video.fragment.IFengVideoFragment; import cn.ittiger.video.fragment.NetEasyVideoFragment; import cn.ittiger.video.fragment.TtKbVideoFragment; import cn.ittiger.video.http.DataType; import android.os.Bundle; package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class FragmentFactory { public static final String KEY_BUNDLE_TAB_ID = "tab_id"; public static final BaseFragment createMainFragment(DataType type) { BaseFragment fragment = null; switch (type) { case NET_EASY: fragment = new NetEasyVideoFragment(); break; case TTKB:
fragment = new TtKbVideoFragment();
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java // public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> // implements TypePresenter { // // private int mCurPage = 1; // // public void refreshData(boolean pullToRefresh) { // // mCurPage = 1; // request(false, pullToRefresh); // } // // public void loadMoreData() { // // request(true, false); // } // // @Override // public void detachView(boolean retainInstance) { // // super.detachView(retainInstance); // mCurPage = 1; // } // // public abstract Observable<String> getHttpCallObservable(int curPage); // // void request(final boolean loadMore, final boolean pullToRefresh) { // // getHttpCallObservable(mCurPage) // .subscribeOn(Schedulers.io()) // .map(new Func1<String, List<VideoData>>() { // // @Override // public List<VideoData> call(String s) { // // return ResultParseFactory.parse(s, getType()); // } // }) // .flatMap(new Func1<List<VideoData>, Observable<List<VideoData>>>() { // @Override // public Observable<List<VideoData>> call(List<VideoData> videos) { // // if(videos == null || videos.size() == 0) { // return Observable.error(new NullPointerException("not load video data")); // } // return Observable.just(videos); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Subscriber<List<VideoData>>() { // @Override // public void onCompleted() { // // getView().showContent(); // mCurPage ++; // } // // @Override // public void onError(Throwable e) { // // if(loadMore == false) { // getView().showError(e, pullToRefresh); // } else { // getView().showLoadMoreErrorView(); // } // } // // @Override // public void onNext(List<VideoData> videos) { // // if(isViewAttached()) { // if(loadMore == false) { // getView().setData(videos); // } else { // getView().setLoadMoreData(videos); // } // } // } // }); // } // }
import cn.ittiger.video.R; import cn.ittiger.video.presenter.NetEasyVideoPresenter; import cn.ittiger.video.presenter.VideoPresenter;
package cn.ittiger.video.fragment; /** * @author laohu * @site http://ittiger.cn */ public class NetEasyVideoFragment extends VideoFragment { @Override
// Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java // public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> // implements TypePresenter { // // private int mCurPage = 1; // // public void refreshData(boolean pullToRefresh) { // // mCurPage = 1; // request(false, pullToRefresh); // } // // public void loadMoreData() { // // request(true, false); // } // // @Override // public void detachView(boolean retainInstance) { // // super.detachView(retainInstance); // mCurPage = 1; // } // // public abstract Observable<String> getHttpCallObservable(int curPage); // // void request(final boolean loadMore, final boolean pullToRefresh) { // // getHttpCallObservable(mCurPage) // .subscribeOn(Schedulers.io()) // .map(new Func1<String, List<VideoData>>() { // // @Override // public List<VideoData> call(String s) { // // return ResultParseFactory.parse(s, getType()); // } // }) // .flatMap(new Func1<List<VideoData>, Observable<List<VideoData>>>() { // @Override // public Observable<List<VideoData>> call(List<VideoData> videos) { // // if(videos == null || videos.size() == 0) { // return Observable.error(new NullPointerException("not load video data")); // } // return Observable.just(videos); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Subscriber<List<VideoData>>() { // @Override // public void onCompleted() { // // getView().showContent(); // mCurPage ++; // } // // @Override // public void onError(Throwable e) { // // if(loadMore == false) { // getView().showError(e, pullToRefresh); // } else { // getView().showLoadMoreErrorView(); // } // } // // @Override // public void onNext(List<VideoData> videos) { // // if(isViewAttached()) { // if(loadMore == false) { // getView().setData(videos); // } else { // getView().setLoadMoreData(videos); // } // } // } // }); // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/NetEasyVideoFragment.java import cn.ittiger.video.R; import cn.ittiger.video.presenter.NetEasyVideoPresenter; import cn.ittiger.video.presenter.VideoPresenter; package cn.ittiger.video.fragment; /** * @author laohu * @site http://ittiger.cn */ public class NetEasyVideoFragment extends VideoFragment { @Override
public VideoPresenter createPresenter() {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/http/parse/TtKbResultParse.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.bean.TtKb; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class TtKbResultParse implements ResultParse { private static final String KEY_VIDEO_LIST = "data"; private static final String KEY_COUNT = "count"; private static final String KEY_END_KEY = "endkey"; private static final String KEY_NEW_KEY = "newkey"; private static final String KEY_ID = "id"; private static final String KEY_TITLE = "topic"; private static final String KEY_VIDEO_URL = "video_link"; private static final String KEY_DURATION = "videoalltime"; private static final String KEY_IMAGE_ITEM = "lbimg"; private static final String KEY_IMAGE = "src"; @Override
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/http/parse/TtKbResultParse.java import cn.ittiger.video.bean.TtKb; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class TtKbResultParse implements ResultParse { private static final String KEY_VIDEO_LIST = "data"; private static final String KEY_COUNT = "count"; private static final String KEY_END_KEY = "endkey"; private static final String KEY_NEW_KEY = "newkey"; private static final String KEY_ID = "id"; private static final String KEY_TITLE = "topic"; private static final String KEY_VIDEO_URL = "video_link"; private static final String KEY_DURATION = "videoalltime"; private static final String KEY_IMAGE_ITEM = "lbimg"; private static final String KEY_IMAGE = "src"; @Override
public List<VideoData> parse(JSONObject json) throws JSONException {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/http/parse/TtKbResultParse.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.bean.TtKb; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class TtKbResultParse implements ResultParse { private static final String KEY_VIDEO_LIST = "data"; private static final String KEY_COUNT = "count"; private static final String KEY_END_KEY = "endkey"; private static final String KEY_NEW_KEY = "newkey"; private static final String KEY_ID = "id"; private static final String KEY_TITLE = "topic"; private static final String KEY_VIDEO_URL = "video_link"; private static final String KEY_DURATION = "videoalltime"; private static final String KEY_IMAGE_ITEM = "lbimg"; private static final String KEY_IMAGE = "src"; @Override public List<VideoData> parse(JSONObject json) throws JSONException { List<VideoData> list = new ArrayList<>(); int count = json.optInt(KEY_COUNT); String newkey = json.optString(KEY_NEW_KEY); String endkey = json.optString(KEY_END_KEY); TtKb.save(newkey, endkey, count == 10 ? 1 : 0); JSONArray videos = json.getJSONArray(KEY_VIDEO_LIST); JSONObject item; for(int i = 0; i < videos.length(); i++) { item = videos.getJSONObject(i); VideoData videoData = new VideoData();
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/http/parse/TtKbResultParse.java import cn.ittiger.video.bean.TtKb; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class TtKbResultParse implements ResultParse { private static final String KEY_VIDEO_LIST = "data"; private static final String KEY_COUNT = "count"; private static final String KEY_END_KEY = "endkey"; private static final String KEY_NEW_KEY = "newkey"; private static final String KEY_ID = "id"; private static final String KEY_TITLE = "topic"; private static final String KEY_VIDEO_URL = "video_link"; private static final String KEY_DURATION = "videoalltime"; private static final String KEY_IMAGE_ITEM = "lbimg"; private static final String KEY_IMAGE = "src"; @Override public List<VideoData> parse(JSONObject json) throws JSONException { List<VideoData> list = new ArrayList<>(); int count = json.optInt(KEY_COUNT); String newkey = json.optString(KEY_NEW_KEY); String endkey = json.optString(KEY_END_KEY); TtKb.save(newkey, endkey, count == 10 ? 1 : 0); JSONArray videos = json.getJSONArray(KEY_VIDEO_LIST); JSONObject item; for(int i = 0; i < videos.length(); i++) { item = videos.getJSONObject(i); VideoData videoData = new VideoData();
videoData.setDataType(DataType.TTKB.value());
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java // public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> // implements TypePresenter { // // private int mCurPage = 1; // // public void refreshData(boolean pullToRefresh) { // // mCurPage = 1; // request(false, pullToRefresh); // } // // public void loadMoreData() { // // request(true, false); // } // // @Override // public void detachView(boolean retainInstance) { // // super.detachView(retainInstance); // mCurPage = 1; // } // // public abstract Observable<String> getHttpCallObservable(int curPage); // // void request(final boolean loadMore, final boolean pullToRefresh) { // // getHttpCallObservable(mCurPage) // .subscribeOn(Schedulers.io()) // .map(new Func1<String, List<VideoData>>() { // // @Override // public List<VideoData> call(String s) { // // return ResultParseFactory.parse(s, getType()); // } // }) // .flatMap(new Func1<List<VideoData>, Observable<List<VideoData>>>() { // @Override // public Observable<List<VideoData>> call(List<VideoData> videos) { // // if(videos == null || videos.size() == 0) { // return Observable.error(new NullPointerException("not load video data")); // } // return Observable.just(videos); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Subscriber<List<VideoData>>() { // @Override // public void onCompleted() { // // getView().showContent(); // mCurPage ++; // } // // @Override // public void onError(Throwable e) { // // if(loadMore == false) { // getView().showError(e, pullToRefresh); // } else { // getView().showLoadMoreErrorView(); // } // } // // @Override // public void onNext(List<VideoData> videos) { // // if(isViewAttached()) { // if(loadMore == false) { // getView().setData(videos); // } else { // getView().setLoadMoreData(videos); // } // } // } // }); // } // }
import cn.ittiger.video.R; import cn.ittiger.video.presenter.TtKbVideoPresenter; import cn.ittiger.video.presenter.VideoPresenter;
package cn.ittiger.video.fragment; /** * @author laohu * @site http://ittiger.cn */ public class TtKbVideoFragment extends VideoFragment { @Override
// Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java // public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> // implements TypePresenter { // // private int mCurPage = 1; // // public void refreshData(boolean pullToRefresh) { // // mCurPage = 1; // request(false, pullToRefresh); // } // // public void loadMoreData() { // // request(true, false); // } // // @Override // public void detachView(boolean retainInstance) { // // super.detachView(retainInstance); // mCurPage = 1; // } // // public abstract Observable<String> getHttpCallObservable(int curPage); // // void request(final boolean loadMore, final boolean pullToRefresh) { // // getHttpCallObservable(mCurPage) // .subscribeOn(Schedulers.io()) // .map(new Func1<String, List<VideoData>>() { // // @Override // public List<VideoData> call(String s) { // // return ResultParseFactory.parse(s, getType()); // } // }) // .flatMap(new Func1<List<VideoData>, Observable<List<VideoData>>>() { // @Override // public Observable<List<VideoData>> call(List<VideoData> videos) { // // if(videos == null || videos.size() == 0) { // return Observable.error(new NullPointerException("not load video data")); // } // return Observable.just(videos); // } // }) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(new Subscriber<List<VideoData>>() { // @Override // public void onCompleted() { // // getView().showContent(); // mCurPage ++; // } // // @Override // public void onError(Throwable e) { // // if(loadMore == false) { // getView().showError(e, pullToRefresh); // } else { // getView().showLoadMoreErrorView(); // } // } // // @Override // public void onNext(List<VideoData> videos) { // // if(isViewAttached()) { // if(loadMore == false) { // getView().setData(videos); // } else { // getView().setLoadMoreData(videos); // } // } // } // }); // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/fragment/TtKbVideoFragment.java import cn.ittiger.video.R; import cn.ittiger.video.presenter.TtKbVideoPresenter; import cn.ittiger.video.presenter.VideoPresenter; package cn.ittiger.video.fragment; /** * @author laohu * @site http://ittiger.cn */ public class TtKbVideoFragment extends VideoFragment { @Override
public VideoPresenter createPresenter() {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/http/parse/IFengTabResultParse.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.bean.IFengInfo; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.DataKeeper; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class IFengTabResultParse implements ResultParse { private static final String KEY_TAB_LIST = "channelInfo"; private static final String KEY_TAB_ID = "channelId"; private static final String KEY_TAB_NAME = "channelName"; private static final String MEMBER_TYPE = "video"; private static final String KEY_DATA_LIST = "bodyList"; private static final String KEY_DATA_ITEMID = "itemId"; private static final String KEY_DATA_ID = "infoId"; private static final String KEY_DATA_TITLE = "title"; private static final String KEY_DATA_TYPE = "memberType"; private static final String KEY_DATA_VIDEO_ITEM = "memberItem"; private static final String KEY_DATA_VIDEO_DURATION = "duration"; private static final String KEY_DATA_VIDEO_IMAGE = "image"; private static final String KEY_DATA_VIDEO_DATA_LIST = "videoFiles"; private static final String KEY_DATA_VIDEO_URL = "mediaUrl"; @Override
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/http/parse/IFengTabResultParse.java import cn.ittiger.video.bean.IFengInfo; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.DataKeeper; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class IFengTabResultParse implements ResultParse { private static final String KEY_TAB_LIST = "channelInfo"; private static final String KEY_TAB_ID = "channelId"; private static final String KEY_TAB_NAME = "channelName"; private static final String MEMBER_TYPE = "video"; private static final String KEY_DATA_LIST = "bodyList"; private static final String KEY_DATA_ITEMID = "itemId"; private static final String KEY_DATA_ID = "infoId"; private static final String KEY_DATA_TITLE = "title"; private static final String KEY_DATA_TYPE = "memberType"; private static final String KEY_DATA_VIDEO_ITEM = "memberItem"; private static final String KEY_DATA_VIDEO_DURATION = "duration"; private static final String KEY_DATA_VIDEO_IMAGE = "image"; private static final String KEY_DATA_VIDEO_DATA_LIST = "videoFiles"; private static final String KEY_DATA_VIDEO_URL = "mediaUrl"; @Override
public List<VideoData> parse(JSONObject json) throws JSONException {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/http/parse/IFengTabResultParse.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // }
import cn.ittiger.video.bean.IFengInfo; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.DataKeeper; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List;
package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class IFengTabResultParse implements ResultParse { private static final String KEY_TAB_LIST = "channelInfo"; private static final String KEY_TAB_ID = "channelId"; private static final String KEY_TAB_NAME = "channelName"; private static final String MEMBER_TYPE = "video"; private static final String KEY_DATA_LIST = "bodyList"; private static final String KEY_DATA_ITEMID = "itemId"; private static final String KEY_DATA_ID = "infoId"; private static final String KEY_DATA_TITLE = "title"; private static final String KEY_DATA_TYPE = "memberType"; private static final String KEY_DATA_VIDEO_ITEM = "memberItem"; private static final String KEY_DATA_VIDEO_DURATION = "duration"; private static final String KEY_DATA_VIDEO_IMAGE = "image"; private static final String KEY_DATA_VIDEO_DATA_LIST = "videoFiles"; private static final String KEY_DATA_VIDEO_URL = "mediaUrl"; @Override public List<VideoData> parse(JSONObject json) throws JSONException { List<VideoData> list = new ArrayList<>(); JSONArray array = json.getJSONArray(KEY_DATA_LIST); JSONObject item; for(int i = 0; i < array.length(); i++) { item = array.getJSONObject(i); String type = item.optString(KEY_DATA_TYPE); if(!MEMBER_TYPE.equals(type)) { continue; } VideoData videoData = new VideoData();
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/DataType.java // public enum DataType { // // NET_EASY(1), // WU5LI(2), // TTKB(3), // IFENG(4); // // int mValue; // // DataType(int value) { // // mValue = value; // } // // public int value() { // // return mValue; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/http/parse/IFengTabResultParse.java import cn.ittiger.video.bean.IFengInfo; import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.http.DataType; import cn.ittiger.video.util.DataKeeper; import cn.ittiger.video.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; package cn.ittiger.video.http.parse; /** * @author laohu * @site http://ittiger.cn */ public class IFengTabResultParse implements ResultParse { private static final String KEY_TAB_LIST = "channelInfo"; private static final String KEY_TAB_ID = "channelId"; private static final String KEY_TAB_NAME = "channelName"; private static final String MEMBER_TYPE = "video"; private static final String KEY_DATA_LIST = "bodyList"; private static final String KEY_DATA_ITEMID = "itemId"; private static final String KEY_DATA_ID = "infoId"; private static final String KEY_DATA_TITLE = "title"; private static final String KEY_DATA_TYPE = "memberType"; private static final String KEY_DATA_VIDEO_ITEM = "memberItem"; private static final String KEY_DATA_VIDEO_DURATION = "duration"; private static final String KEY_DATA_VIDEO_IMAGE = "image"; private static final String KEY_DATA_VIDEO_DATA_LIST = "videoFiles"; private static final String KEY_DATA_VIDEO_URL = "mediaUrl"; @Override public List<VideoData> parse(JSONObject json) throws JSONException { List<VideoData> list = new ArrayList<>(); JSONArray array = json.getJSONArray(KEY_DATA_LIST); JSONObject item; for(int i = 0; i < array.length(); i++) { item = array.getJSONObject(i); String type = item.optString(KEY_DATA_TYPE); if(!MEMBER_TYPE.equals(type)) { continue; } VideoData videoData = new VideoData();
videoData.setDataType(DataType.IFENG.value());
huyongli/TigerVideo
TigerVideoPlayer/src/main/java/cn/ittiger/player/media/AbsSimplePlayer.java
// Path: TigerVideoPlayer/src/main/java/cn/ittiger/player/state/PlayState.java // public final class PlayState { // public static final int STATE_NORMAL = 0; // public static final int STATE_LOADING = 1; // public static final int STATE_PLAYING = 2; // public static final int STATE_PLAYING_BUFFERING_START = 3; // public static final int STATE_PAUSE = 4; // public static final int STATE_AUTO_COMPLETE = 5; // public static final int STATE_ERROR = 6; // }
import android.graphics.SurfaceTexture; import android.view.TextureView; import cn.ittiger.player.state.PlayState;
package cn.ittiger.player.media; /** * @author: laohu on 2017/9/10 * @site: http://ittiger.cn */ public abstract class AbsSimplePlayer implements IPlayer, TextureView.SurfaceTextureListener { protected TextureView mTextureView; protected SurfaceTexture mSurfaceTexture; protected PlayCallback mPlayCallback; /** * 此函数中给播放器设置数据源开始loading视频数据 * * 此时TextureView已经初始化完成 */ protected abstract void prepare(); @Override public void setPlayCallback(PlayCallback playCallback) { mPlayCallback = playCallback; } @Override public void setTextureView(TextureView textureView) { if(mTextureView != null) { mTextureView.setSurfaceTextureListener(null); } mSurfaceTexture = null; mTextureView = textureView; if(textureView != null) { mTextureView.setSurfaceTextureListener(this); } } @Override public boolean isPlaying() {
// Path: TigerVideoPlayer/src/main/java/cn/ittiger/player/state/PlayState.java // public final class PlayState { // public static final int STATE_NORMAL = 0; // public static final int STATE_LOADING = 1; // public static final int STATE_PLAYING = 2; // public static final int STATE_PLAYING_BUFFERING_START = 3; // public static final int STATE_PAUSE = 4; // public static final int STATE_AUTO_COMPLETE = 5; // public static final int STATE_ERROR = 6; // } // Path: TigerVideoPlayer/src/main/java/cn/ittiger/player/media/AbsSimplePlayer.java import android.graphics.SurfaceTexture; import android.view.TextureView; import cn.ittiger.player.state.PlayState; package cn.ittiger.player.media; /** * @author: laohu on 2017/9/10 * @site: http://ittiger.cn */ public abstract class AbsSimplePlayer implements IPlayer, TextureView.SurfaceTextureListener { protected TextureView mTextureView; protected SurfaceTexture mSurfaceTexture; protected PlayCallback mPlayCallback; /** * 此函数中给播放器设置数据源开始loading视频数据 * * 此时TextureView已经初始化完成 */ protected abstract void prepare(); @Override public void setPlayCallback(PlayCallback playCallback) { mPlayCallback = playCallback; } @Override public void setTextureView(TextureView textureView) { if(mTextureView != null) { mTextureView.setSurfaceTextureListener(null); } mSurfaceTexture = null; mTextureView = textureView; if(textureView != null) { mTextureView.setSurfaceTextureListener(this); } } @Override public boolean isPlaying() {
return (getState() == PlayState.STATE_PLAYING ||
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/factory/RetrofitFactory.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/NetEasyApi.java // public interface NetEasyApi { // // @GET("recommend/getChanListNews?channel=T1457068979049&fn=3&passport=h3o88AuDhdH7tlyrE3hlILX2WMCoMqapk08GhEzPqX4%3D&devId=DWT861zlolJo7mHnyynnGA%3D%3D&version=15.0&net=wifi&ts=1474185450&sign=JmMhXTnPo%2BqgTgwyxKstDgS9lmS5Pv%2BUCP5tZ%2FrWevV48ErR02zJ6%2FKXOnxX046I&encryption=1") // Observable<String> getVideos(@Query("size") int size, @Query("offset") int offset); // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/TtKbApi.java // public interface TtKbApi { // // @Headers({/*"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",*/ // "Accept-Encoding: gzip", // "User-Agent: okhttp/3.2.0"}) // @FormUrlEncoded // @POST("app_video/getvideos") // Observable<String> getVideos(@FieldMap Map<String, String> fieldMap); // }
import cn.ittiger.video.http.service.IFengApi; import cn.ittiger.video.http.service.NetEasyApi; import cn.ittiger.video.http.service.TtKbApi; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; import java.util.concurrent.TimeUnit;
package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class RetrofitFactory { private static final int TIME_OUT = 12;//超时时间 private static final String NETEASY_BASE_URL = "http://c.m.163.com/"; private static final String TTKB_BASE_URL = "http://video.toutiaokuaibao.com/"; private static final String IFENG_BASE_URL = "http://vcis.ifeng.com/";
// Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/NetEasyApi.java // public interface NetEasyApi { // // @GET("recommend/getChanListNews?channel=T1457068979049&fn=3&passport=h3o88AuDhdH7tlyrE3hlILX2WMCoMqapk08GhEzPqX4%3D&devId=DWT861zlolJo7mHnyynnGA%3D%3D&version=15.0&net=wifi&ts=1474185450&sign=JmMhXTnPo%2BqgTgwyxKstDgS9lmS5Pv%2BUCP5tZ%2FrWevV48ErR02zJ6%2FKXOnxX046I&encryption=1") // Observable<String> getVideos(@Query("size") int size, @Query("offset") int offset); // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/TtKbApi.java // public interface TtKbApi { // // @Headers({/*"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",*/ // "Accept-Encoding: gzip", // "User-Agent: okhttp/3.2.0"}) // @FormUrlEncoded // @POST("app_video/getvideos") // Observable<String> getVideos(@FieldMap Map<String, String> fieldMap); // } // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/RetrofitFactory.java import cn.ittiger.video.http.service.IFengApi; import cn.ittiger.video.http.service.NetEasyApi; import cn.ittiger.video.http.service.TtKbApi; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; import java.util.concurrent.TimeUnit; package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class RetrofitFactory { private static final int TIME_OUT = 12;//超时时间 private static final String NETEASY_BASE_URL = "http://c.m.163.com/"; private static final String TTKB_BASE_URL = "http://video.toutiaokuaibao.com/"; private static final String IFENG_BASE_URL = "http://vcis.ifeng.com/";
private static volatile NetEasyApi sNetEasyService;
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/factory/RetrofitFactory.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/NetEasyApi.java // public interface NetEasyApi { // // @GET("recommend/getChanListNews?channel=T1457068979049&fn=3&passport=h3o88AuDhdH7tlyrE3hlILX2WMCoMqapk08GhEzPqX4%3D&devId=DWT861zlolJo7mHnyynnGA%3D%3D&version=15.0&net=wifi&ts=1474185450&sign=JmMhXTnPo%2BqgTgwyxKstDgS9lmS5Pv%2BUCP5tZ%2FrWevV48ErR02zJ6%2FKXOnxX046I&encryption=1") // Observable<String> getVideos(@Query("size") int size, @Query("offset") int offset); // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/TtKbApi.java // public interface TtKbApi { // // @Headers({/*"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",*/ // "Accept-Encoding: gzip", // "User-Agent: okhttp/3.2.0"}) // @FormUrlEncoded // @POST("app_video/getvideos") // Observable<String> getVideos(@FieldMap Map<String, String> fieldMap); // }
import cn.ittiger.video.http.service.IFengApi; import cn.ittiger.video.http.service.NetEasyApi; import cn.ittiger.video.http.service.TtKbApi; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; import java.util.concurrent.TimeUnit;
package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class RetrofitFactory { private static final int TIME_OUT = 12;//超时时间 private static final String NETEASY_BASE_URL = "http://c.m.163.com/"; private static final String TTKB_BASE_URL = "http://video.toutiaokuaibao.com/"; private static final String IFENG_BASE_URL = "http://vcis.ifeng.com/"; private static volatile NetEasyApi sNetEasyService;
// Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/NetEasyApi.java // public interface NetEasyApi { // // @GET("recommend/getChanListNews?channel=T1457068979049&fn=3&passport=h3o88AuDhdH7tlyrE3hlILX2WMCoMqapk08GhEzPqX4%3D&devId=DWT861zlolJo7mHnyynnGA%3D%3D&version=15.0&net=wifi&ts=1474185450&sign=JmMhXTnPo%2BqgTgwyxKstDgS9lmS5Pv%2BUCP5tZ%2FrWevV48ErR02zJ6%2FKXOnxX046I&encryption=1") // Observable<String> getVideos(@Query("size") int size, @Query("offset") int offset); // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/http/service/TtKbApi.java // public interface TtKbApi { // // @Headers({/*"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",*/ // "Accept-Encoding: gzip", // "User-Agent: okhttp/3.2.0"}) // @FormUrlEncoded // @POST("app_video/getvideos") // Observable<String> getVideos(@FieldMap Map<String, String> fieldMap); // } // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/RetrofitFactory.java import cn.ittiger.video.http.service.IFengApi; import cn.ittiger.video.http.service.NetEasyApi; import cn.ittiger.video.http.service.TtKbApi; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; import java.util.concurrent.TimeUnit; package cn.ittiger.video.factory; /** * @author laohu * @site http://ittiger.cn */ public class RetrofitFactory { private static final int TIME_OUT = 12;//超时时间 private static final String NETEASY_BASE_URL = "http://c.m.163.com/"; private static final String TTKB_BASE_URL = "http://video.toutiaokuaibao.com/"; private static final String IFENG_BASE_URL = "http://vcis.ifeng.com/"; private static volatile NetEasyApi sNetEasyService;
private static volatile TtKbApi sTtKbService;
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // }
import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoMvpView; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List;
package cn.ittiger.video.presenter; /** * @author laohu * @site http://ittiger.cn */ public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> implements TypePresenter { private int mCurPage = 1; public void refreshData(boolean pullToRefresh) { mCurPage = 1; request(false, pullToRefresh); } public void loadMoreData() { request(true, false); } @Override public void detachView(boolean retainInstance) { super.detachView(retainInstance); mCurPage = 1; } public abstract Observable<String> getHttpCallObservable(int curPage); void request(final boolean loadMore, final boolean pullToRefresh) { getHttpCallObservable(mCurPage) .subscribeOn(Schedulers.io())
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoMvpView; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List; package cn.ittiger.video.presenter; /** * @author laohu * @site http://ittiger.cn */ public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> implements TypePresenter { private int mCurPage = 1; public void refreshData(boolean pullToRefresh) { mCurPage = 1; request(false, pullToRefresh); } public void loadMoreData() { request(true, false); } @Override public void detachView(boolean retainInstance) { super.detachView(retainInstance); mCurPage = 1; } public abstract Observable<String> getHttpCallObservable(int curPage); void request(final boolean loadMore, final boolean pullToRefresh) { getHttpCallObservable(mCurPage) .subscribeOn(Schedulers.io())
.map(new Func1<String, List<VideoData>>() {
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // }
import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoMvpView; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List;
package cn.ittiger.video.presenter; /** * @author laohu * @site http://ittiger.cn */ public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> implements TypePresenter { private int mCurPage = 1; public void refreshData(boolean pullToRefresh) { mCurPage = 1; request(false, pullToRefresh); } public void loadMoreData() { request(true, false); } @Override public void detachView(boolean retainInstance) { super.detachView(retainInstance); mCurPage = 1; } public abstract Observable<String> getHttpCallObservable(int curPage); void request(final boolean loadMore, final boolean pullToRefresh) { getHttpCallObservable(mCurPage) .subscribeOn(Schedulers.io()) .map(new Func1<String, List<VideoData>>() { @Override public List<VideoData> call(String s) {
// Path: TigerVideo/src/main/java/cn/ittiger/video/bean/VideoData.java // @Table(name = "VideoTable") // public class VideoData { // // // private String id;//视频id // private String duration;//视频时长 // private String title;//视频标题 // private String imageUrl;//视频预览图地址 // private String videoUrl;//视频播放地址 // private int mDataType;//视频数据类型 // // public String getId() { // // return id; // } // // public void setId(String id) { // // this.id = id; // } // // public String getDuration() { // // return duration; // } // // public void setDuration(String duration) { // // this.duration = duration; // } // // public String getTitle() { // // return title; // } // // public void setTitle(String title) { // // this.title = title; // } // // public String getImageUrl() { // // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // // this.imageUrl = imageUrl; // } // // public String getVideoUrl() { // // return videoUrl; // } // // public void setVideoUrl(String videoUrl) { // // this.videoUrl = videoUrl; // } // // public int getDataType() { // // return mDataType; // } // // public void setDataType(int dataType) { // // mDataType = dataType; // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoPresenter.java import cn.ittiger.video.bean.VideoData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoMvpView; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List; package cn.ittiger.video.presenter; /** * @author laohu * @site http://ittiger.cn */ public abstract class VideoPresenter extends MvpBasePresenter<VideoMvpView> implements TypePresenter { private int mCurPage = 1; public void refreshData(boolean pullToRefresh) { mCurPage = 1; request(false, pullToRefresh); } public void loadMoreData() { request(true, false); } @Override public void detachView(boolean retainInstance) { super.detachView(retainInstance); mCurPage = 1; } public abstract Observable<String> getHttpCallObservable(int curPage); void request(final boolean loadMore, final boolean pullToRefresh) { getHttpCallObservable(mCurPage) .subscribeOn(Schedulers.io()) .map(new Func1<String, List<VideoData>>() { @Override public List<VideoData> call(String s) {
return ResultParseFactory.parse(s, getType());
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoTabPresenter.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/util/DBManager.java // public class DBManager { // /** // * 管理器单例 // */ // private static DBManager sDBInstance; // /** // * 数据库配置上下文 // */ // private IDbApplication mDbApplication; // /** // * 全局数据库 // */ // private SQLiteDB mDB; // // // private DBManager() { // // mDbApplication = ApplicationHelper.getInstance().getDbApplication(); // } // // public static DBManager getInstance() { // // if(sDBInstance == null) { // synchronized (DBManager.class) { // if(sDBInstance == null) { // sDBInstance = new DBManager(); // } // } // } // return sDBInstance; // } // // /** // * 获取全局数据库操作对象 // * @return // */ // public SQLiteDB getSQLiteDB() { // // if(mDB == null) { // synchronized (this) { // if(mDB == null) { // SQLiteDBConfig config = mDbApplication.getGlobalDbConfig(); // mDB = SQLiteDBFactory.createSQLiteDB(config); // } // } // } // return mDB; // } // // /** // * 关闭数据库 // */ // public void closeSQLiteDB() { // if(this.mDB != null) { // this.mDB.close(); // } // this.mDB = null; // } // }
import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoTabMvpView; import cn.ittiger.video.util.DBManager; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List;
package cn.ittiger.video.presenter; /** * @author: laohu on 2016/10/8 * @site: http://ittiger.cn */ public abstract class VideoTabPresenter extends MvpBasePresenter<VideoTabMvpView> implements TypePresenter { public void queryVideoTab(final boolean pullToRefresh) { Observable.just(getType().value()) .subscribeOn(Schedulers.io()) .map(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { String[] whereArgs = {String.valueOf(integer.intValue())};
// Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/util/DBManager.java // public class DBManager { // /** // * 管理器单例 // */ // private static DBManager sDBInstance; // /** // * 数据库配置上下文 // */ // private IDbApplication mDbApplication; // /** // * 全局数据库 // */ // private SQLiteDB mDB; // // // private DBManager() { // // mDbApplication = ApplicationHelper.getInstance().getDbApplication(); // } // // public static DBManager getInstance() { // // if(sDBInstance == null) { // synchronized (DBManager.class) { // if(sDBInstance == null) { // sDBInstance = new DBManager(); // } // } // } // return sDBInstance; // } // // /** // * 获取全局数据库操作对象 // * @return // */ // public SQLiteDB getSQLiteDB() { // // if(mDB == null) { // synchronized (this) { // if(mDB == null) { // SQLiteDBConfig config = mDbApplication.getGlobalDbConfig(); // mDB = SQLiteDBFactory.createSQLiteDB(config); // } // } // } // return mDB; // } // // /** // * 关闭数据库 // */ // public void closeSQLiteDB() { // if(this.mDB != null) { // this.mDB.close(); // } // this.mDB = null; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoTabPresenter.java import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoTabMvpView; import cn.ittiger.video.util.DBManager; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List; package cn.ittiger.video.presenter; /** * @author: laohu on 2016/10/8 * @site: http://ittiger.cn */ public abstract class VideoTabPresenter extends MvpBasePresenter<VideoTabMvpView> implements TypePresenter { public void queryVideoTab(final boolean pullToRefresh) { Observable.just(getType().value()) .subscribeOn(Schedulers.io()) .map(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { String[] whereArgs = {String.valueOf(integer.intValue())};
return DBManager.getInstance().getSQLiteDB().queryIfExist(VideoTabData.class, "type=?", whereArgs);
huyongli/TigerVideo
TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoTabPresenter.java
// Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/util/DBManager.java // public class DBManager { // /** // * 管理器单例 // */ // private static DBManager sDBInstance; // /** // * 数据库配置上下文 // */ // private IDbApplication mDbApplication; // /** // * 全局数据库 // */ // private SQLiteDB mDB; // // // private DBManager() { // // mDbApplication = ApplicationHelper.getInstance().getDbApplication(); // } // // public static DBManager getInstance() { // // if(sDBInstance == null) { // synchronized (DBManager.class) { // if(sDBInstance == null) { // sDBInstance = new DBManager(); // } // } // } // return sDBInstance; // } // // /** // * 获取全局数据库操作对象 // * @return // */ // public SQLiteDB getSQLiteDB() { // // if(mDB == null) { // synchronized (this) { // if(mDB == null) { // SQLiteDBConfig config = mDbApplication.getGlobalDbConfig(); // mDB = SQLiteDBFactory.createSQLiteDB(config); // } // } // } // return mDB; // } // // /** // * 关闭数据库 // */ // public void closeSQLiteDB() { // if(this.mDB != null) { // this.mDB.close(); // } // this.mDB = null; // } // }
import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoTabMvpView; import cn.ittiger.video.util.DBManager; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List;
package cn.ittiger.video.presenter; /** * @author: laohu on 2016/10/8 * @site: http://ittiger.cn */ public abstract class VideoTabPresenter extends MvpBasePresenter<VideoTabMvpView> implements TypePresenter { public void queryVideoTab(final boolean pullToRefresh) { Observable.just(getType().value()) .subscribeOn(Schedulers.io()) .map(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { String[] whereArgs = {String.valueOf(integer.intValue())}; return DBManager.getInstance().getSQLiteDB().queryIfExist(VideoTabData.class, "type=?", whereArgs); } }) .flatMap(new Func1<Boolean, Observable<List<VideoTabData>>>() { @Override public Observable<List<VideoTabData>> call(Boolean aBoolean) { if(aBoolean.booleanValue()) { String[] whereArgs = {String.valueOf(getType().value())}; List<VideoTabData> tabs = DBManager.getInstance().getSQLiteDB().query(VideoTabData.class, "type=?", whereArgs); return Observable.just(tabs); } return getHttpCallObservable() .flatMap(new Func1<String, Observable<List<VideoTabData>>>() { @Override public Observable<List<VideoTabData>> call(String s) {
// Path: TigerVideo/src/main/java/cn/ittiger/video/factory/ResultParseFactory.java // public class ResultParseFactory { // // public static ResultParse create(DataType type) { // // ResultParse parse = null; // switch (type) { // case NET_EASY: // parse = new NetEasyResultParse(); // break; // case TTKB: // parse = new TtKbResultParse(); // break; // case IFENG: // parse = new IFengTabResultParse(); // break; // } // return parse; // } // // public static List<VideoData> parse(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parse(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // // public static List<VideoTabData> parseTab(String value, DataType type) { // // try { // JSONObject json = new JSONObject(value); // ResultParse parse = create(type); // return parse.parseTab(json); // } catch(Exception e) { // return new ArrayList<>(0); // } // } // } // // Path: TigerVideo/src/main/java/cn/ittiger/video/util/DBManager.java // public class DBManager { // /** // * 管理器单例 // */ // private static DBManager sDBInstance; // /** // * 数据库配置上下文 // */ // private IDbApplication mDbApplication; // /** // * 全局数据库 // */ // private SQLiteDB mDB; // // // private DBManager() { // // mDbApplication = ApplicationHelper.getInstance().getDbApplication(); // } // // public static DBManager getInstance() { // // if(sDBInstance == null) { // synchronized (DBManager.class) { // if(sDBInstance == null) { // sDBInstance = new DBManager(); // } // } // } // return sDBInstance; // } // // /** // * 获取全局数据库操作对象 // * @return // */ // public SQLiteDB getSQLiteDB() { // // if(mDB == null) { // synchronized (this) { // if(mDB == null) { // SQLiteDBConfig config = mDbApplication.getGlobalDbConfig(); // mDB = SQLiteDBFactory.createSQLiteDB(config); // } // } // } // return mDB; // } // // /** // * 关闭数据库 // */ // public void closeSQLiteDB() { // if(this.mDB != null) { // this.mDB.close(); // } // this.mDB = null; // } // } // Path: TigerVideo/src/main/java/cn/ittiger/video/presenter/VideoTabPresenter.java import cn.ittiger.video.bean.VideoTabData; import cn.ittiger.video.factory.ResultParseFactory; import cn.ittiger.video.mvpview.VideoTabMvpView; import cn.ittiger.video.util.DBManager; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import com.hannesdorfmann.mosby.mvp.MvpBasePresenter; import java.util.List; package cn.ittiger.video.presenter; /** * @author: laohu on 2016/10/8 * @site: http://ittiger.cn */ public abstract class VideoTabPresenter extends MvpBasePresenter<VideoTabMvpView> implements TypePresenter { public void queryVideoTab(final boolean pullToRefresh) { Observable.just(getType().value()) .subscribeOn(Schedulers.io()) .map(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer integer) { String[] whereArgs = {String.valueOf(integer.intValue())}; return DBManager.getInstance().getSQLiteDB().queryIfExist(VideoTabData.class, "type=?", whereArgs); } }) .flatMap(new Func1<Boolean, Observable<List<VideoTabData>>>() { @Override public Observable<List<VideoTabData>> call(Boolean aBoolean) { if(aBoolean.booleanValue()) { String[] whereArgs = {String.valueOf(getType().value())}; List<VideoTabData> tabs = DBManager.getInstance().getSQLiteDB().query(VideoTabData.class, "type=?", whereArgs); return Observable.just(tabs); } return getHttpCallObservable() .flatMap(new Func1<String, Observable<List<VideoTabData>>>() { @Override public Observable<List<VideoTabData>> call(String s) {
List<VideoTabData> tabs = ResultParseFactory.parseTab(s, getType());
karask/bitcoinpos
app/src/main/java/gr/cryptocurrencies/bitcoinpos/ItemRecyclerViewAdapter.java
// Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/ItemFragment.java // public interface OnFragmentInteractionListener { // void onListItemClickFragmentInteraction(Item item); // } // // Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/database/Item.java // public class Item implements Parcelable { // // private Integer itemId; // private String name; // private String description; // private String color; // private Date createdAt; // private int displayOrder; // private double amount; // private boolean isAvailable; // // // public Item(Integer itemId, String name, String description, double amount, int order, String color, boolean isAvailable, Date createdAt) { // // if(name == null) // throw new IllegalArgumentException("Name or amount are invalid!"); // // this.itemId = itemId; // this.name = name; // this.description = description; // this.color = color; // this.displayOrder = order; // this.amount = amount; // this.isAvailable = isAvailable; // this.createdAt = createdAt; // } // // public Integer getItemId() { // return itemId; // } // // public void setItemId(Integer itemId) { // this.itemId = itemId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getColor() { // return color; // } // // public void setColor(String color) { // this.color = color; // } // // public Date getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // public int getDisplayOrder() { // return displayOrder; // } // // public void setDisplayOrder(int displayOrder) { // this.displayOrder = displayOrder; // } // // public double getAmount() { // return amount; // } // // public void setAmount(double amount) { // this.amount = amount; // } // // public boolean isAvailable() { // return isAvailable; // } // // public void setAvailable(boolean available) { // isAvailable = available; // } // // // protected Item(Parcel in) { // itemId = in.readByte() == 0x00 ? null : in.readInt(); // name = in.readString(); // description = in.readString(); // color = in.readString(); // long tmpCreatedAt = in.readLong(); // createdAt = tmpCreatedAt != -1 ? new Date(tmpCreatedAt) : null; // displayOrder = in.readInt(); // amount = in.readDouble(); // isAvailable = in.readByte() != 0x00; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (itemId == null) { // dest.writeByte((byte) (0x00)); // } else { // dest.writeByte((byte) (0x01)); // dest.writeInt(itemId); // } // dest.writeString(name); // dest.writeString(description); // dest.writeString(color); // dest.writeLong(createdAt != null ? createdAt.getTime() : -1L); // dest.writeInt(displayOrder); // dest.writeDouble(amount); // dest.writeByte((byte) (isAvailable ? 0x01 : 0x00)); // } // // @SuppressWarnings("unused") // public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() { // @Override // public Item createFromParcel(Parcel in) { // return new Item(in); // } // // @Override // public Item[] newArray(int size) { // return new Item[size]; // } // }; // // // currently only keeps item's name and amount // // TODO: put separator in a GenericUtils class ? // public String toString() { // return name + "[-|-]" + amount; // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import gr.cryptocurrencies.bitcoinpos.ItemFragment.OnFragmentInteractionListener; import gr.cryptocurrencies.bitcoinpos.database.Item; import java.util.List;
package gr.cryptocurrencies.bitcoinpos; /** * {@link RecyclerView.Adapter} that can display a {@link Item} and makes a call to the * specified {@link OnFragmentInteractionListener}. * TODO: Replace the implementation with code for your data type. */ public class ItemRecyclerViewAdapter extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ViewHolder> { private final List<Item> mValues;
// Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/ItemFragment.java // public interface OnFragmentInteractionListener { // void onListItemClickFragmentInteraction(Item item); // } // // Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/database/Item.java // public class Item implements Parcelable { // // private Integer itemId; // private String name; // private String description; // private String color; // private Date createdAt; // private int displayOrder; // private double amount; // private boolean isAvailable; // // // public Item(Integer itemId, String name, String description, double amount, int order, String color, boolean isAvailable, Date createdAt) { // // if(name == null) // throw new IllegalArgumentException("Name or amount are invalid!"); // // this.itemId = itemId; // this.name = name; // this.description = description; // this.color = color; // this.displayOrder = order; // this.amount = amount; // this.isAvailable = isAvailable; // this.createdAt = createdAt; // } // // public Integer getItemId() { // return itemId; // } // // public void setItemId(Integer itemId) { // this.itemId = itemId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getColor() { // return color; // } // // public void setColor(String color) { // this.color = color; // } // // public Date getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // public int getDisplayOrder() { // return displayOrder; // } // // public void setDisplayOrder(int displayOrder) { // this.displayOrder = displayOrder; // } // // public double getAmount() { // return amount; // } // // public void setAmount(double amount) { // this.amount = amount; // } // // public boolean isAvailable() { // return isAvailable; // } // // public void setAvailable(boolean available) { // isAvailable = available; // } // // // protected Item(Parcel in) { // itemId = in.readByte() == 0x00 ? null : in.readInt(); // name = in.readString(); // description = in.readString(); // color = in.readString(); // long tmpCreatedAt = in.readLong(); // createdAt = tmpCreatedAt != -1 ? new Date(tmpCreatedAt) : null; // displayOrder = in.readInt(); // amount = in.readDouble(); // isAvailable = in.readByte() != 0x00; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // if (itemId == null) { // dest.writeByte((byte) (0x00)); // } else { // dest.writeByte((byte) (0x01)); // dest.writeInt(itemId); // } // dest.writeString(name); // dest.writeString(description); // dest.writeString(color); // dest.writeLong(createdAt != null ? createdAt.getTime() : -1L); // dest.writeInt(displayOrder); // dest.writeDouble(amount); // dest.writeByte((byte) (isAvailable ? 0x01 : 0x00)); // } // // @SuppressWarnings("unused") // public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() { // @Override // public Item createFromParcel(Parcel in) { // return new Item(in); // } // // @Override // public Item[] newArray(int size) { // return new Item[size]; // } // }; // // // currently only keeps item's name and amount // // TODO: put separator in a GenericUtils class ? // public String toString() { // return name + "[-|-]" + amount; // } // } // Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/ItemRecyclerViewAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import gr.cryptocurrencies.bitcoinpos.ItemFragment.OnFragmentInteractionListener; import gr.cryptocurrencies.bitcoinpos.database.Item; import java.util.List; package gr.cryptocurrencies.bitcoinpos; /** * {@link RecyclerView.Adapter} that can display a {@link Item} and makes a call to the * specified {@link OnFragmentInteractionListener}. * TODO: Replace the implementation with code for your data type. */ public class ItemRecyclerViewAdapter extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ViewHolder> { private final List<Item> mValues;
private final OnFragmentInteractionListener mListener;
karask/bitcoinpos
app/src/main/java/gr/cryptocurrencies/bitcoinpos/database/UpdateDbHelper.java
// Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/network/BlockchainInfoHelper.java // public static final String CUSTOM_BROADCAST_ACTION = "gr.cryptocurrencies.bitcoinpos.CUSTOM_BROADCAST";
import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import static gr.cryptocurrencies.bitcoinpos.network.BlockchainInfoHelper.CUSTOM_BROADCAST_ACTION;
package gr.cryptocurrencies.bitcoinpos.database; public class UpdateDbHelper { private static PointOfSaleDb mDbHelper; private static Context context; public UpdateDbHelper(Context context){ this.context=context; } //send broadcast to refresh view in HistoryFragment and in PaymentRequestFragment public static void sendBroadcast(){
// Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/network/BlockchainInfoHelper.java // public static final String CUSTOM_BROADCAST_ACTION = "gr.cryptocurrencies.bitcoinpos.CUSTOM_BROADCAST"; // Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/database/UpdateDbHelper.java import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import static gr.cryptocurrencies.bitcoinpos.network.BlockchainInfoHelper.CUSTOM_BROADCAST_ACTION; package gr.cryptocurrencies.bitcoinpos.database; public class UpdateDbHelper { private static PointOfSaleDb mDbHelper; private static Context context; public UpdateDbHelper(Context context){ this.context=context; } //send broadcast to refresh view in HistoryFragment and in PaymentRequestFragment public static void sendBroadcast(){
Intent intent = new Intent(CUSTOM_BROADCAST_ACTION);
karask/bitcoinpos
app/src/main/java/gr/cryptocurrencies/bitcoinpos/database/ItemHelper.java
// Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/utilities/DateUtilities.java // public class DateUtilities { // // public final static String DATABASE_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // public final static String UTC = "UTC"; // // public final static String USER_INTERFACE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // public static String getRelativeTimeString(String date) { // // // previously DB wasn't unix timestamp because of previous block explorer service didn't use it // //DateFormat dbDf = new SimpleDateFormat(DateUtilities.DATABASE_DATE_FORMAT); // //dbDf.setTimeZone(TimeZone.getTimeZone(DateUtilities.UTC)); // DateFormat uiDf = new SimpleDateFormat(DateUtilities.USER_INTERFACE_DATE_FORMAT); // uiDf.setTimeZone(Calendar.getInstance().getTimeZone()); // // long dbTimeInMillis = Long.parseLong(date); // long currentTimeInMillis = System.currentTimeMillis(); // // Date dbDate = null; // dbDate = new Date((long) dbTimeInMillis*1000); // // // convert to friendly relative time string onl if difference less than 23 hours // String relativeTimeString; // if(currentTimeInMillis - dbTimeInMillis < 23*60*60 * 1000) { // // only get friendly relative string if we have a translation for that language // // Currently only Locale.ENGLISH // if(Locale.getDefault().getLanguage().equals( Locale.ENGLISH.toString() ) || // Locale.getDefault().getLanguage().equals( "el" )) { // relativeTimeString = DateUtils.getRelativeTimeSpanString(dbTimeInMillis, currentTimeInMillis, DateUtils.MINUTE_IN_MILLIS).toString(); // } else { // relativeTimeString = dbDate != null ? uiDf.format(dbDate) : " -- "; // } // } else { // relativeTimeString = dbDate != null ? uiDf.format(dbDate) : " -- "; // } // // return relativeTimeString; // } // // public static String getDateAsString(Date date) { // DateFormat dbDf = new SimpleDateFormat(DateUtilities.DATABASE_DATE_FORMAT); // dbDf.setTimeZone(TimeZone.getTimeZone(DateUtilities.UTC)); // // return dbDf.format(date); // } // // public static Date getStringAsDate(String date) { // DateFormat dbDf = new SimpleDateFormat(DateUtilities.DATABASE_DATE_FORMAT); // dbDf.setTimeZone(TimeZone.getTimeZone(DateUtilities.UTC)); // // Date dbDate = null; // try { // dbDate = dbDf.parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // // return dbDate; // } // // // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import gr.cryptocurrencies.bitcoinpos.utilities.DateUtilities;
package gr.cryptocurrencies.bitcoinpos.database; public class ItemHelper { private static ItemHelper ourInstance = new ItemHelper(); private static PointOfSaleDb mDbHelper; private static SQLiteDatabase mDb; public static ItemHelper getInstance(Context context) { if(mDbHelper == null) { mDbHelper = PointOfSaleDb.getInstance(context); } if(mDb == null) { mDb = mDbHelper.getWritableDatabase(); } return ourInstance; } private ItemHelper() { } public int insert(Item item) { ContentValues values = new ContentValues(); values.put(PointOfSaleDb.ITEMS_COLUMN_NAME, item.getName()); values.put(PointOfSaleDb.ITEMS_COLUMN_AMOUNT, item.getAmount()); values.put(PointOfSaleDb.ITEMS_COLUMN_IS_AVAILABLE, item.isAvailable()); values.put(PointOfSaleDb.ITEMS_COLUMN_COLOR, item.getColor()); values.put(PointOfSaleDb.ITEMS_COLUMN_DESCRIPTION, item.getDescription()); values.put(PointOfSaleDb.ITEMS_COLUMN_DISPLAY_ORDER, item.getDisplayOrder());
// Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/utilities/DateUtilities.java // public class DateUtilities { // // public final static String DATABASE_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // public final static String UTC = "UTC"; // // public final static String USER_INTERFACE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // public static String getRelativeTimeString(String date) { // // // previously DB wasn't unix timestamp because of previous block explorer service didn't use it // //DateFormat dbDf = new SimpleDateFormat(DateUtilities.DATABASE_DATE_FORMAT); // //dbDf.setTimeZone(TimeZone.getTimeZone(DateUtilities.UTC)); // DateFormat uiDf = new SimpleDateFormat(DateUtilities.USER_INTERFACE_DATE_FORMAT); // uiDf.setTimeZone(Calendar.getInstance().getTimeZone()); // // long dbTimeInMillis = Long.parseLong(date); // long currentTimeInMillis = System.currentTimeMillis(); // // Date dbDate = null; // dbDate = new Date((long) dbTimeInMillis*1000); // // // convert to friendly relative time string onl if difference less than 23 hours // String relativeTimeString; // if(currentTimeInMillis - dbTimeInMillis < 23*60*60 * 1000) { // // only get friendly relative string if we have a translation for that language // // Currently only Locale.ENGLISH // if(Locale.getDefault().getLanguage().equals( Locale.ENGLISH.toString() ) || // Locale.getDefault().getLanguage().equals( "el" )) { // relativeTimeString = DateUtils.getRelativeTimeSpanString(dbTimeInMillis, currentTimeInMillis, DateUtils.MINUTE_IN_MILLIS).toString(); // } else { // relativeTimeString = dbDate != null ? uiDf.format(dbDate) : " -- "; // } // } else { // relativeTimeString = dbDate != null ? uiDf.format(dbDate) : " -- "; // } // // return relativeTimeString; // } // // public static String getDateAsString(Date date) { // DateFormat dbDf = new SimpleDateFormat(DateUtilities.DATABASE_DATE_FORMAT); // dbDf.setTimeZone(TimeZone.getTimeZone(DateUtilities.UTC)); // // return dbDf.format(date); // } // // public static Date getStringAsDate(String date) { // DateFormat dbDf = new SimpleDateFormat(DateUtilities.DATABASE_DATE_FORMAT); // dbDf.setTimeZone(TimeZone.getTimeZone(DateUtilities.UTC)); // // Date dbDate = null; // try { // dbDate = dbDf.parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // // return dbDate; // } // // // } // Path: app/src/main/java/gr/cryptocurrencies/bitcoinpos/database/ItemHelper.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import gr.cryptocurrencies.bitcoinpos.utilities.DateUtilities; package gr.cryptocurrencies.bitcoinpos.database; public class ItemHelper { private static ItemHelper ourInstance = new ItemHelper(); private static PointOfSaleDb mDbHelper; private static SQLiteDatabase mDb; public static ItemHelper getInstance(Context context) { if(mDbHelper == null) { mDbHelper = PointOfSaleDb.getInstance(context); } if(mDb == null) { mDb = mDbHelper.getWritableDatabase(); } return ourInstance; } private ItemHelper() { } public int insert(Item item) { ContentValues values = new ContentValues(); values.put(PointOfSaleDb.ITEMS_COLUMN_NAME, item.getName()); values.put(PointOfSaleDb.ITEMS_COLUMN_AMOUNT, item.getAmount()); values.put(PointOfSaleDb.ITEMS_COLUMN_IS_AVAILABLE, item.isAvailable()); values.put(PointOfSaleDb.ITEMS_COLUMN_COLOR, item.getColor()); values.put(PointOfSaleDb.ITEMS_COLUMN_DESCRIPTION, item.getDescription()); values.put(PointOfSaleDb.ITEMS_COLUMN_DISPLAY_ORDER, item.getDisplayOrder());
values.put(PointOfSaleDb.ITEMS_COLUMN_CREATED_AT, DateUtilities.getDateAsString(item.getCreatedAt()));
asyncj/core
api/src/test/java/com/asyncj/core/api/examples/fork/Actor1Impl.java
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // }
import com.asyncj.core.api.ActorManager;
/** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.fork; class Actor1Impl implements ForkExample.Actor1 { private final int workLoad; int n; int count = 0; final long startTime; public Actor1Impl(int n) { this.n = n; workLoad = this.n / Runtime.getRuntime().availableProcessors(); startTime = System.currentTimeMillis(); } public void pong(ForkExample.Actor2 actor2, String s) { count++; if (count < n - Runtime.getRuntime().availableProcessors()) { if (count % 100000 == 0) System.out.println(count + " pings from - " + s); actor2.ping(this, count); } else { long endTime = System.currentTimeMillis(); System.out.println("super mega total count = " + count + ". In " + (endTime - startTime)/1000 + " seconds"); } } @Override
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // } // Path: api/src/test/java/com/asyncj/core/api/examples/fork/Actor1Impl.java import com.asyncj.core.api.ActorManager; /** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.fork; class Actor1Impl implements ForkExample.Actor1 { private final int workLoad; int n; int count = 0; final long startTime; public Actor1Impl(int n) { this.n = n; workLoad = this.n / Runtime.getRuntime().availableProcessors(); startTime = System.currentTimeMillis(); } public void pong(ForkExample.Actor2 actor2, String s) { count++; if (count < n - Runtime.getRuntime().availableProcessors()) { if (count % 100000 == 0) System.out.println(count + " pings from - " + s); actor2.ping(this, count); } else { long endTime = System.currentTimeMillis(); System.out.println("super mega total count = " + count + ". In " + (endTime - startTime)/1000 + " seconds"); } } @Override
public void startPings(ActorManager actorManager, int m) {
asyncj/core
api/src/test/java/com/asyncj/core/api/examples/pingpong/PingPongExample.java
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // }
import com.asyncj.core.api.ActorManager; import org.junit.Test; import java.util.Collection; import java.util.List;
/** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.pingpong; /** * User: APOPOV * Date: 05.10.13 */ public class PingPongExample { @Test public void testPingPong() {
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // } // Path: api/src/test/java/com/asyncj/core/api/examples/pingpong/PingPongExample.java import com.asyncj.core.api.ActorManager; import org.junit.Test; import java.util.Collection; import java.util.List; /** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.pingpong; /** * User: APOPOV * Date: 05.10.13 */ public class PingPongExample { @Test public void testPingPong() {
ActorManager actorManager = new ActorManager();
asyncj/core
api/src/test/java/com/asyncj/core/api/examples/forkjoin/ForkJoinExample.java
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // }
import com.asyncj.core.api.ActorManager; import org.junit.Test;
/** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.forkjoin; /** * User: APOPOV * Date: 05.10.13 */ public class ForkJoinExample { @Test public void testPingPong() {
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // } // Path: api/src/test/java/com/asyncj/core/api/examples/forkjoin/ForkJoinExample.java import com.asyncj.core.api.ActorManager; import org.junit.Test; /** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.forkjoin; /** * User: APOPOV * Date: 05.10.13 */ public class ForkJoinExample { @Test public void testPingPong() {
ActorManager actorManager = new ActorManager();
asyncj/core
api/src/test/java/com/asyncj/core/api/examples/fork/ForkExample.java
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // }
import com.asyncj.core.api.ActorManager; import org.junit.Test;
/** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.fork; /** * User: APOPOV * Date: 05.10.13 */ public class ForkExample { @Test public void testPingPong() {
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // } // Path: api/src/test/java/com/asyncj/core/api/examples/fork/ForkExample.java import com.asyncj.core.api.ActorManager; import org.junit.Test; /** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.fork; /** * User: APOPOV * Date: 05.10.13 */ public class ForkExample { @Test public void testPingPong() {
ActorManager actorManager = new ActorManager();
asyncj/core
api/src/test/java/com/asyncj/core/api/examples/forkjoin/Actor1Impl.java
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // }
import com.asyncj.core.api.ActorManager;
this.workLoad = workLoad; } public void pong(ForkJoinExample.Actor2 actor2, String s) { count++; if (count < n) { if (count % 100000 == 0) System.out.println(count + " pings from - " + s); actor2.ping(this, count); } else { System.out.println("final count = " + count); if (parentActor1 != null) { parentActor1.incCount(count); } } } @Override public void incCount(int count) { incTimes++; this.count += count; System.out.println("sub count = " + this.count); if (incTimes >= 5 && parentActor1 != null) { parentActor1.incCount(this.count); } } @Override
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // } // Path: api/src/test/java/com/asyncj/core/api/examples/forkjoin/Actor1Impl.java import com.asyncj.core.api.ActorManager; this.workLoad = workLoad; } public void pong(ForkJoinExample.Actor2 actor2, String s) { count++; if (count < n) { if (count % 100000 == 0) System.out.println(count + " pings from - " + s); actor2.ping(this, count); } else { System.out.println("final count = " + count); if (parentActor1 != null) { parentActor1.incCount(count); } } } @Override public void incCount(int count) { incTimes++; this.count += count; System.out.println("sub count = " + this.count); if (incTimes >= 5 && parentActor1 != null) { parentActor1.incCount(this.count); } } @Override
public void startPings(ActorManager actorManager, int m) {
asyncj/core
api/src/test/java/com/asyncj/core/api/examples/pingpong/Actor1Impl.java
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // }
import com.asyncj.core.api.ActorManager;
/** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.pingpong; class Actor1Impl implements PingPongExample.Actor1 { int n;
// Path: api/src/main/java/com/asyncj/core/api/ActorManager.java // public class ActorManager { // // // private BlockingQueue<ActorMessage> queue = new LinkedBlockingQueue<ActorMessage>(); // // private Map<Object, Proxy> actorToProxy = (new LinkedHashMap<Object, Proxy>()); // // public ActorManager() { // // int availableProcessors = Runtime.getRuntime().availableProcessors() * 20; // // ActorManagerThread actorManagerThread = new ActorManagerThread(queue); // for (int i = 0; i < availableProcessors; i++) { // actorManagerThread.addNewActorThread(); // } // // actorManagerThread.start(); // } // // // @SuppressWarnings("unchecked") // public synchronized <T> T createActor(Object obj) { // MethodHandler h = new MethodHandler(obj); // T t = (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), h); // actorToProxy.put(obj, (Proxy) t); // return t; // } // // public synchronized <T> List<T> createActors(Object obj, int count) { // List<T> ts = new ArrayList<T>(); // for (int i = 0; i < count; i++) { // ts.add(this.<T>createActor(obj)); // } // return ts; // } // // @SuppressWarnings("unchecked") // public <T> T getReference(T actor1) { // return (T) actorToProxy.get(actor1); // } // // public void unblockResult(Object actor1) { // Proxy proxy = (Proxy) getReference(actor1); // ((MethodHandler) Proxy.getInvocationHandler(proxy)).unblockResult(); // } // // class MethodHandler implements InvocationHandler { // // private Object obj; // // private final Object lock = new Object(); // // public MethodHandler(Object obj) { // this.obj = obj; // } // // @Override // public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // // if ("hashCode".equals(method.getName()) ) { // return obj.hashCode(); // } // // if ("equals".equals(method.getName()) ) { // return obj.equals(args); // } // // if ("toString".equals(method.getName()) ) { // return obj.toString(); // } // // a method invocation will send the message to a blocking queue // int i=0; // if (args != null) { // for (Object arg : args) { // Proxy proxy1 = actorToProxy.get(arg); // if (proxy1 != null) { // args[i] = proxy1; // } // i++; // } // } // // Class<?> returnType = method.getReturnType(); // if ("void".equals(returnType.getName())) { // queue.put(new ActorMessage(ActorMessage.METHOD_CALL, obj, method, args)); // return null; // } // else { // // //if the return class is an actor interface then return a new instance of the proxy // //to the user and associate it with the current proxy/actor. // //the proxy should send all messages inside with a type METHOD_RESULT // // and when the actor thread will execute the // // method which will return the result of the actual actor, then the actor thread will send // // a message to the Actor Manager Thread. The AMT will start sending messages to the new actor... // //when the actor will be instantiated later it should receive all messages // //that has been sent to it before // // //block the current thread and wait for the value from a future object // synchronized (lock) { // lock.wait(); // return method.invoke(obj, args); // } // } // } // // public void unblockResult() { // synchronized (lock) { // lock.notify(); // } // } // // } // } // Path: api/src/test/java/com/asyncj/core/api/examples/pingpong/Actor1Impl.java import com.asyncj.core.api.ActorManager; /** Copyright 2013 Aliaksei Papou 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.asyncj.core.api.examples.pingpong; class Actor1Impl implements PingPongExample.Actor1 { int n;
private ActorManager actorManager;
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ConfigurableTestServer.java
// Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/SSLTestServerSocketFactory.java // public class SSLTestServerSocketFactory // { // private static final String KEYSTORE_PASSWORD = "keypassword"; // private static final String KEY_PASSWORD = "keypassword"; // // public SSLServerSocket create() // throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException // { // String trustStorePath = SSLSocketBuilder.class.getClassLoader().getResource("truststore.jks").getFile(); // System.getProperties().setProperty("javax.net.ssl.trustStore", trustStorePath); // // String keyStorePath = SSLSocketBuilder.class.getClassLoader().getResource("keystore.jks").getFile(); // // InputStream keystoreStream = null; // try { // KeyStore keystore = KeyStore.getInstance("JKS"); // keystoreStream = new FileInputStream(new File(keyStorePath)); // // keystore.load(keystoreStream, KEYSTORE_PASSWORD.toCharArray()); // KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // // keyManagerFactory.init(keystore, KEY_PASSWORD.toCharArray()); // // SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); // sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); // // SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); // serverSocket.setEnabledCipherSuites(serverSocket.getSupportedCipherSuites()); // serverSocket.bind(new InetSocketAddress(0)); // // return serverSocket; // } // finally { // if (keystoreStream != null) { // keystoreStream.close(); // } // } // } // }
import org.komamitsu.fluency.fluentd.ingester.sender.SSLTestServerSocketFactory; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd; public class ConfigurableTestServer { private final boolean sslEnabled; public ConfigurableTestServer(boolean sslEnabled) { this.sslEnabled = sslEnabled; } Exception run(final WithClientSocket withClientSocket, final WithServerPort withServerPort, long timeoutMilli) throws Throwable { ExecutorService executorService = Executors.newCachedThreadPool(); final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>(); try { if (sslEnabled) {
// Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/SSLTestServerSocketFactory.java // public class SSLTestServerSocketFactory // { // private static final String KEYSTORE_PASSWORD = "keypassword"; // private static final String KEY_PASSWORD = "keypassword"; // // public SSLServerSocket create() // throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException // { // String trustStorePath = SSLSocketBuilder.class.getClassLoader().getResource("truststore.jks").getFile(); // System.getProperties().setProperty("javax.net.ssl.trustStore", trustStorePath); // // String keyStorePath = SSLSocketBuilder.class.getClassLoader().getResource("keystore.jks").getFile(); // // InputStream keystoreStream = null; // try { // KeyStore keystore = KeyStore.getInstance("JKS"); // keystoreStream = new FileInputStream(new File(keyStorePath)); // // keystore.load(keystoreStream, KEYSTORE_PASSWORD.toCharArray()); // KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // // keyManagerFactory.init(keystore, KEY_PASSWORD.toCharArray()); // // SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); // sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); // // SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); // serverSocket.setEnabledCipherSuites(serverSocket.getSupportedCipherSuites()); // serverSocket.bind(new InetSocketAddress(0)); // // return serverSocket; // } // finally { // if (keystoreStream != null) { // keystoreStream.close(); // } // } // } // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ConfigurableTestServer.java import org.komamitsu.fluency.fluentd.ingester.sender.SSLTestServerSocketFactory; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd; public class ConfigurableTestServer { private final boolean sslEnabled; public ConfigurableTestServer(boolean sslEnabled) { this.sslEnabled = sslEnabled; } Exception run(final WithClientSocket withClientSocket, final WithServerPort withServerPort, long timeoutMilli) throws Throwable { ExecutorService executorService = Executors.newCachedThreadPool(); final AtomicReference<ServerSocket> serverSocket = new AtomicReference<ServerSocket>(); try { if (sslEnabled) {
serverSocket.set(new SSLTestServerSocketFactory().create());
komamitsu/fluency
fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.buffer; class BufferTest { private static final Logger LOG = LoggerFactory.getLogger(BufferTest.class);
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // } // Path: fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.buffer; class BufferTest { private static final Logger LOG = LoggerFactory.getLogger(BufferTest.class);
private Ingester ingester;
komamitsu/fluency
fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.buffer; class BufferTest { private static final Logger LOG = LoggerFactory.getLogger(BufferTest.class); private Ingester ingester;
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // } // Path: fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.buffer; class BufferTest { private static final Logger LOG = LoggerFactory.getLogger(BufferTest.class); private Ingester ingester;
private RecordFormatter recordFormatter;
komamitsu/fluency
fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.buffer; class BufferTest { private static final Logger LOG = LoggerFactory.getLogger(BufferTest.class); private Ingester ingester; private RecordFormatter recordFormatter; private Buffer.Config bufferConfig; @BeforeEach void setUp() {
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // } // Path: fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.buffer; class BufferTest { private static final Logger LOG = LoggerFactory.getLogger(BufferTest.class); private Ingester ingester; private RecordFormatter recordFormatter; private Buffer.Config bufferConfig; @BeforeEach void setUp() {
recordFormatter = new JsonRecordFormatter();
komamitsu/fluency
fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
@Test void testFileBackup() throws IOException { bufferConfig.setFileBackupDir(System.getProperty("java.io.tmpdir")); bufferConfig.setFileBackupPrefix("FileBackupTest"); // Just for cleaning backup files try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { buffer.clearBackupFiles(); } try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { assertEquals(0, buffer.getBufferedDataSize()); } long currentTime = System.currentTimeMillis() / 1000; Map<String, Object> event0 = ImmutableMap.of("name", "a", "age", 42); Map<String, Object> event1 = ImmutableMap.of("name", "b", "age", 99); try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { buffer.append("foo", currentTime, event0); buffer.append("bar", currentTime, event1); } Ingester ingester = mock(Ingester.class); try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { buffer.flushInternal(ingester, true); } ObjectMapper objectMapper = new ObjectMapper();
// Path: fluency-core/src/test/java/org/komamitsu/fluency/JsonRecordFormatter.java // public class JsonRecordFormatter // extends AbstractRecordFormatter // { // private ObjectMapper objectMapper = new ObjectMapper(); // // public JsonRecordFormatter() // { // super(new Config()); // } // // @Override // public byte[] format(String tag, Object timestamp, Map<String, Object> data) // { // try { // return objectMapper.writeValueAsBytes(data); // } // catch (JsonProcessingException e) { // throw new RuntimeException(e); // } // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue) // { // throw new RuntimeException("Shouldn't be called"); // } // // @Override // public String formatName() // { // return "json"; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // } // Path: fluency-core/src/test/java/org/komamitsu/fluency/buffer/BufferTest.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.JsonRecordFormatter; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.komamitsu.fluency.util.Tuple; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.hamcrest.number.OrderingComparison.lessThan; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @Test void testFileBackup() throws IOException { bufferConfig.setFileBackupDir(System.getProperty("java.io.tmpdir")); bufferConfig.setFileBackupPrefix("FileBackupTest"); // Just for cleaning backup files try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { buffer.clearBackupFiles(); } try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { assertEquals(0, buffer.getBufferedDataSize()); } long currentTime = System.currentTimeMillis() / 1000; Map<String, Object> event0 = ImmutableMap.of("name", "a", "age", 42); Map<String, Object> event1 = ImmutableMap.of("name", "b", "age", 99); try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { buffer.append("foo", currentTime, event0); buffer.append("bar", currentTime, event1); } Ingester ingester = mock(Ingester.class); try (Buffer buffer = new Buffer(bufferConfig, recordFormatter)) { buffer.flushInternal(ingester, true); } ObjectMapper objectMapper = new ObjectMapper();
for (Tuple<String, Map<String, Object>> tagAndEvent :
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/ConstantRetryStrategy.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // }
import org.komamitsu.fluency.validation.Validatable; import org.komamitsu.fluency.validation.annotation.Min;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender.retry; public class ConstantRetryStrategy extends RetryStrategy { private final Config config; public ConstantRetryStrategy(Config config) { super(config); config.validateValues(); this.config = config; } @Override public int getNextIntervalMillis(int retryCount) { return config.getRetryIntervalMillis(); } @Override public String toString() { return "ConstantRetryStrategy{" + "config=" + config + "} " + super.toString(); } public static class Config extends RetryStrategy.Config
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/ConstantRetryStrategy.java import org.komamitsu.fluency.validation.Validatable; import org.komamitsu.fluency.validation.annotation.Min; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender.retry; public class ConstantRetryStrategy extends RetryStrategy { private final Config config; public ConstantRetryStrategy(Config config) { super(config); config.validateValues(); this.config = config; } @Override public int getNextIntervalMillis(int retryCount) { return config.getRetryIntervalMillis(); } @Override public String toString() { return "ConstantRetryStrategy{" + "config=" + config + "} " + super.toString(); } public static class Config extends RetryStrategy.Config
implements Validatable
komamitsu/fluency
fluency-aws-s3/src/main/java/org/komamitsu/fluency/aws/s3/ingester/DefaultS3DestinationDecider.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // }
import org.komamitsu.fluency.validation.Validatable; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter;
protected String getKeyBase(Instant time) { return ZonedDateTime.ofInstant(time, getZoneId()).format(FORMATTER); } @Override public S3Destination decide(String tag, Instant time) { String keyPrefix = getKeyPrefix() == null ? "" : getKeyPrefix() + "/"; String keySuffix = getKeySuffix() == null ? "" : getKeySuffix(); return new S3Destination(getBucket(tag), keyPrefix + getKeyBase(time) + keySuffix); } public String getKeyPrefix() { return config.getKeyPrefix(); } public String getKeySuffix() { return config.getKeySuffix(); } public ZoneId getZoneId() { return config.getZoneId(); } public static class Config
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // } // Path: fluency-aws-s3/src/main/java/org/komamitsu/fluency/aws/s3/ingester/DefaultS3DestinationDecider.java import org.komamitsu.fluency.validation.Validatable; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; protected String getKeyBase(Instant time) { return ZonedDateTime.ofInstant(time, getZoneId()).format(FORMATTER); } @Override public S3Destination decide(String tag, Instant time) { String keyPrefix = getKeyPrefix() == null ? "" : getKeyPrefix() + "/"; String keySuffix = getKeySuffix() == null ? "" : getKeySuffix(); return new S3Destination(getBucket(tag), keyPrefix + getKeyBase(time) + keySuffix); } public String getKeyPrefix() { return config.getKeyPrefix(); } public String getKeySuffix() { return config.getKeySuffix(); } public ZoneId getZoneId() { return config.getZoneId(); } public static class Config
implements Validatable
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/ErrorHandler.java // public interface ErrorHandler // { // void handle(Throwable e); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // }
import org.komamitsu.fluency.ingester.sender.ErrorHandler; import org.komamitsu.fluency.ingester.sender.Sender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
} public synchronized void send(List<ByteBuffer> buffers) throws IOException { sendInternalWithRestoreBufferPositions(buffers, null); } public void sendWithAck(List<ByteBuffer> buffers, String ackToken) throws IOException { sendInternalWithRestoreBufferPositions(buffers, ackToken); } private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) throws IOException { List<Integer> positions = new ArrayList<>(buffers.size()); for (ByteBuffer data : buffers) { positions.add(data.position()); } try { sendInternal(buffers, ackToken); } catch (Exception e) { for (int i = 0; i < buffers.size(); i++) { buffers.get(i).position(positions.get(i)); }
// Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/ErrorHandler.java // public interface ErrorHandler // { // void handle(Throwable e); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java import org.komamitsu.fluency.ingester.sender.ErrorHandler; import org.komamitsu.fluency.ingester.sender.Sender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; } public synchronized void send(List<ByteBuffer> buffers) throws IOException { sendInternalWithRestoreBufferPositions(buffers, null); } public void sendWithAck(List<ByteBuffer> buffers, String ackToken) throws IOException { sendInternalWithRestoreBufferPositions(buffers, ackToken); } private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) throws IOException { List<Integer> positions = new ArrayList<>(buffers.size()); for (ByteBuffer data : buffers) { positions.add(data.position()); } try { sendInternal(buffers, ackToken); } catch (Exception e) { for (int i = 0; i < buffers.size(); i++) { buffers.get(i).position(positions.get(i)); }
ErrorHandler errorHandler = config.getErrorHandler();
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngesterTest.java
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // }
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.ingester.Ingester; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.msgpack.core.MessagePack; import org.msgpack.core.MessageUnpacker; import org.msgpack.value.ImmutableArrayValue; import org.msgpack.value.Value; import org.msgpack.value.ValueFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester; class FluentdIngesterTest { private static final String TAG = "foo.bar"; private static final byte[] DATA = "hello, world".getBytes(StandardCharsets.UTF_8); @Captor public ArgumentCaptor<List<ByteBuffer>> byteBuffersArgumentCaptor;
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngesterTest.java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.ingester.Ingester; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.msgpack.core.MessagePack; import org.msgpack.core.MessageUnpacker; import org.msgpack.value.ImmutableArrayValue; import org.msgpack.value.Value; import org.msgpack.value.ValueFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester; class FluentdIngesterTest { private static final String TAG = "foo.bar"; private static final byte[] DATA = "hello, world".getBytes(StandardCharsets.UTF_8); @Captor public ArgumentCaptor<List<ByteBuffer>> byteBuffersArgumentCaptor;
private FluentdSender fluentdSender;
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngesterTest.java
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // }
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.ingester.Ingester; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.msgpack.core.MessagePack; import org.msgpack.core.MessageUnpacker; import org.msgpack.value.ImmutableArrayValue; import org.msgpack.value.Value; import org.msgpack.value.ValueFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester; class FluentdIngesterTest { private static final String TAG = "foo.bar"; private static final byte[] DATA = "hello, world".getBytes(StandardCharsets.UTF_8); @Captor public ArgumentCaptor<List<ByteBuffer>> byteBuffersArgumentCaptor; private FluentdSender fluentdSender; @BeforeEach void setUp() throws Exception { MockitoAnnotations.initMocks(this); fluentdSender = mock(FluentdSender.class); } private byte[] getIngestedData(List<ByteBuffer> byteBuffers) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (ByteBuffer byteBuffer : byteBuffers) { outputStream.write(byteBuffer.array()); } return outputStream.toByteArray(); } @Test void ingestWithoutAck() throws IOException {
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngesterTest.java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.ingester.Ingester; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.msgpack.core.MessagePack; import org.msgpack.core.MessageUnpacker; import org.msgpack.value.ImmutableArrayValue; import org.msgpack.value.Value; import org.msgpack.value.ValueFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester; class FluentdIngesterTest { private static final String TAG = "foo.bar"; private static final byte[] DATA = "hello, world".getBytes(StandardCharsets.UTF_8); @Captor public ArgumentCaptor<List<ByteBuffer>> byteBuffersArgumentCaptor; private FluentdSender fluentdSender; @BeforeEach void setUp() throws Exception { MockitoAnnotations.initMocks(this); fluentdSender = mock(FluentdSender.class); } private byte[] getIngestedData(List<ByteBuffer> byteBuffers) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (ByteBuffer byteBuffer : byteBuffers) { outputStream.write(byteBuffer.array()); } return outputStream.toByteArray(); } @Test void ingestWithoutAck() throws IOException {
Ingester ingester = new FluentdIngester(new FluentdIngester.Config(), fluentdSender);
komamitsu/fluency
fluency-treasuredata/src/test/java/org/komamitsu/fluency/treasuredata/ingester/sender/TreasureDataSenderTest.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/NonRetryableException.java // public class NonRetryableException // extends RuntimeException // { // public NonRetryableException(String message) // { // super(message); // } // // public NonRetryableException(String message, Throwable cause) // { // super(message, cause); // } // }
import com.treasuredata.client.TDClient; import com.treasuredata.client.TDClientHttpConflictException; import com.treasuredata.client.TDClientHttpNotFoundException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.NonRetryableException; import org.mockito.ArgumentCaptor; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPInputStream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
}).when(client).createTable(anyString(), anyString()); sender.send(DB_AND_TABLE, ByteBuffer.wrap(DATA)); ArgumentCaptor<String> uniqueIdArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(client, times(2)).importFile( eq(DB), eq(TABLE), any(File.class), uniqueIdArgumentCaptor.capture()); verify(client, times(1)).createDatabase(eq(DB)); verify(client, times(2)).createTable(eq(DB), eq(TABLE)); UUID.fromString(uniqueIdArgumentCaptor.getValue()); } @Test public void sendWithLackOfPermissionOnDatabase() throws IOException { doThrow(new TDClientHttpNotFoundException("Not Found!!!!")) .when(client).importFile(anyString(), anyString(), any(File.class), anyString()); doThrow(new TDClientHttpNotFoundException("Not Found!!!!")) .when(client).createTable(anyString(), anyString()); doThrow(new TDClientHttpConflictException("Conflict!!!!")) .when(client).createDatabase(anyString()); doReturn(false).when(client).existsDatabase(anyString()); try { sender.send(DB_AND_TABLE, ByteBuffer.wrap(DATA)); fail(); }
// Path: fluency-core/src/main/java/org/komamitsu/fluency/NonRetryableException.java // public class NonRetryableException // extends RuntimeException // { // public NonRetryableException(String message) // { // super(message); // } // // public NonRetryableException(String message, Throwable cause) // { // super(message, cause); // } // } // Path: fluency-treasuredata/src/test/java/org/komamitsu/fluency/treasuredata/ingester/sender/TreasureDataSenderTest.java import com.treasuredata.client.TDClient; import com.treasuredata.client.TDClientHttpConflictException; import com.treasuredata.client.TDClientHttpNotFoundException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.NonRetryableException; import org.mockito.ArgumentCaptor; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPInputStream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; }).when(client).createTable(anyString(), anyString()); sender.send(DB_AND_TABLE, ByteBuffer.wrap(DATA)); ArgumentCaptor<String> uniqueIdArgumentCaptor = ArgumentCaptor.forClass(String.class); verify(client, times(2)).importFile( eq(DB), eq(TABLE), any(File.class), uniqueIdArgumentCaptor.capture()); verify(client, times(1)).createDatabase(eq(DB)); verify(client, times(2)).createTable(eq(DB), eq(TABLE)); UUID.fromString(uniqueIdArgumentCaptor.getValue()); } @Test public void sendWithLackOfPermissionOnDatabase() throws IOException { doThrow(new TDClientHttpNotFoundException("Not Found!!!!")) .when(client).importFile(anyString(), anyString(), any(File.class), anyString()); doThrow(new TDClientHttpNotFoundException("Not Found!!!!")) .when(client).createTable(anyString(), anyString()); doThrow(new TDClientHttpConflictException("Conflict!!!!")) .when(client).createDatabase(anyString()); doReturn(false).when(client).existsDatabase(anyString()); try { sender.send(DB_AND_TABLE, ByteBuffer.wrap(DATA)); fail(); }
catch (NonRetryableException e) {
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/recordformat/FluentdRecordFormatter.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/AbstractRecordFormatter.java // public abstract class AbstractRecordFormatter // implements RecordFormatter // { // private static final Logger LOG = LoggerFactory.getLogger(AbstractRecordFormatter.class); // protected final ObjectMapper objectMapperForMessagePack = new ObjectMapper(new MessagePackFactory()); // protected final Config config; // // public AbstractRecordFormatter(Config config) // { // this.config = config; // registerObjectMapperModules(objectMapperForMessagePack); // } // // public abstract byte[] format(String tag, Object timestamp, Map<String, Object> data); // // public abstract byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // public abstract byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // public abstract String formatName(); // // protected long getEpoch(Object timestamp) // { // if (timestamp instanceof EventTime) { // return ((EventTime) timestamp).getSeconds(); // } // else if (timestamp instanceof Number) { // return ((Number) timestamp).longValue(); // } // else { // LOG.warn("Invalid timestamp. Using current time: timestamp={}", timestamp); // return System.currentTimeMillis() / 1000; // } // } // // protected void registerObjectMapperModules(ObjectMapper objectMapper) // { // List<Module> jacksonModules = config.getJacksonModules(); // for (Module module : jacksonModules) { // objectMapper.registerModule(module); // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // }
import com.fasterxml.jackson.core.JsonProcessingException; import org.komamitsu.fluency.recordformat.AbstractRecordFormatter; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.recordformat; public class FluentdRecordFormatter extends AbstractRecordFormatter
// Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/AbstractRecordFormatter.java // public abstract class AbstractRecordFormatter // implements RecordFormatter // { // private static final Logger LOG = LoggerFactory.getLogger(AbstractRecordFormatter.class); // protected final ObjectMapper objectMapperForMessagePack = new ObjectMapper(new MessagePackFactory()); // protected final Config config; // // public AbstractRecordFormatter(Config config) // { // this.config = config; // registerObjectMapperModules(objectMapperForMessagePack); // } // // public abstract byte[] format(String tag, Object timestamp, Map<String, Object> data); // // public abstract byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // public abstract byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // public abstract String formatName(); // // protected long getEpoch(Object timestamp) // { // if (timestamp instanceof EventTime) { // return ((EventTime) timestamp).getSeconds(); // } // else if (timestamp instanceof Number) { // return ((Number) timestamp).longValue(); // } // else { // LOG.warn("Invalid timestamp. Using current time: timestamp={}", timestamp); // return System.currentTimeMillis() / 1000; // } // } // // protected void registerObjectMapperModules(ObjectMapper objectMapper) // { // List<Module> jacksonModules = config.getJacksonModules(); // for (Module module : jacksonModules) { // objectMapper.registerModule(module); // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/RecordFormatter.java // public interface RecordFormatter // { // byte[] format(String tag, Object timestamp, Map<String, Object> data); // // byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len); // // byte[] formatFromMessagePack(String tag, Object timestamp, ByteBuffer mapValue); // // String formatName(); // // class Config // { // private List<Module> jacksonModules = Collections.emptyList(); // // public List<Module> getJacksonModules() // { // return jacksonModules; // } // // public void setJacksonModules(List<Module> jacksonModules) // { // this.jacksonModules = jacksonModules; // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/recordformat/FluentdRecordFormatter.java import com.fasterxml.jackson.core.JsonProcessingException; import org.komamitsu.fluency.recordformat.AbstractRecordFormatter; import org.komamitsu.fluency.recordformat.RecordFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.recordformat; public class FluentdRecordFormatter extends AbstractRecordFormatter
implements RecordFormatter
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngester.java
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/RequestOption.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class RequestOption // { // private final int size; // private final String chunk; // // public RequestOption( // @JsonProperty("size") int size, // @JsonProperty("chunk") String chunk) // { // this.size = size; // this.chunk = chunk; // } // // @JsonProperty("size") // public int getSize() // { // return size; // } // // @JsonProperty("chunk") // public String getChunk() // { // return chunk; // } // // @Override // public String toString() // { // return "RequestOption{" + // "size=" + size + // ", chunk=" + chunk + // '}'; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // }
import java.util.UUID; import com.fasterxml.jackson.databind.ObjectMapper; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.fluentd.ingester.sender.RequestOption; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.ingester.sender.Sender; import org.msgpack.core.MessagePack; import org.msgpack.core.MessagePacker; import org.msgpack.jackson.dataformat.MessagePackFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester; public class FluentdIngester implements Ingester { private final Config config;
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/RequestOption.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class RequestOption // { // private final int size; // private final String chunk; // // public RequestOption( // @JsonProperty("size") int size, // @JsonProperty("chunk") String chunk) // { // this.size = size; // this.chunk = chunk; // } // // @JsonProperty("size") // public int getSize() // { // return size; // } // // @JsonProperty("chunk") // public String getChunk() // { // return chunk; // } // // @Override // public String toString() // { // return "RequestOption{" + // "size=" + size + // ", chunk=" + chunk + // '}'; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngester.java import java.util.UUID; import com.fasterxml.jackson.databind.ObjectMapper; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.fluentd.ingester.sender.RequestOption; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.ingester.sender.Sender; import org.msgpack.core.MessagePack; import org.msgpack.core.MessagePacker; import org.msgpack.jackson.dataformat.MessagePackFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester; public class FluentdIngester implements Ingester { private final Config config;
private final FluentdSender sender;
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngester.java
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/RequestOption.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class RequestOption // { // private final int size; // private final String chunk; // // public RequestOption( // @JsonProperty("size") int size, // @JsonProperty("chunk") String chunk) // { // this.size = size; // this.chunk = chunk; // } // // @JsonProperty("size") // public int getSize() // { // return size; // } // // @JsonProperty("chunk") // public String getChunk() // { // return chunk; // } // // @Override // public String toString() // { // return "RequestOption{" + // "size=" + size + // ", chunk=" + chunk + // '}'; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // }
import java.util.UUID; import com.fasterxml.jackson.databind.ObjectMapper; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.fluentd.ingester.sender.RequestOption; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.ingester.sender.Sender; import org.msgpack.core.MessagePack; import org.msgpack.core.MessagePacker; import org.msgpack.jackson.dataformat.MessagePackFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List;
messagePacker.packRawStringHeader(dataLength); messagePacker.flush(); ByteBuffer headerBuffer = ByteBuffer.wrap(header.toByteArray()); if (config.isAckResponseMode()) { // The spec (https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#entry) // says to encode a 128 bit value as base64, but fluent-bit currently does something different // and in fluent-bit and fluentd there is no validation. So for now we keep it simple, see // discussion on issue #181. String token = UUID.randomUUID().toString(); ByteBuffer optionBuffer = ByteBuffer.wrap(objectMapper.writeValueAsBytes(new RequestOption(dataLength, token))); List<ByteBuffer> buffers = Arrays.asList(headerBuffer, dataBuffer, optionBuffer); synchronized (sender) { sender.sendWithAck(buffers, token); } } else { ByteBuffer optionBuffer = ByteBuffer.wrap(objectMapper.writeValueAsBytes(new RequestOption(dataLength, null))); List<ByteBuffer> buffers = Arrays.asList(headerBuffer, dataBuffer, optionBuffer); synchronized (sender) { sender.send(buffers); } } } @Override
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/FluentdSender.java // public abstract class FluentdSender // implements Closeable, Sender // { // private static final Logger LOG = LoggerFactory.getLogger(FluentdSender.class); // private final Config config; // // protected FluentdSender(Config config) // { // this.config = config; // } // // protected FluentdSender() // { // this(new FluentdSender.Config()); // } // // public synchronized void send(ByteBuffer buffer) // throws IOException // { // sendInternalWithRestoreBufferPositions(Arrays.asList(buffer), null); // } // // public synchronized void send(List<ByteBuffer> buffers) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, null); // } // // public void sendWithAck(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // sendInternalWithRestoreBufferPositions(buffers, ackToken); // } // // private void sendInternalWithRestoreBufferPositions(List<ByteBuffer> buffers, String ackToken) // throws IOException // { // List<Integer> positions = new ArrayList<>(buffers.size()); // for (ByteBuffer data : buffers) { // positions.add(data.position()); // } // // try { // sendInternal(buffers, ackToken); // } // catch (Exception e) { // for (int i = 0; i < buffers.size(); i++) { // buffers.get(i).position(positions.get(i)); // } // // ErrorHandler errorHandler = config.getErrorHandler(); // if (errorHandler != null) { // try { // errorHandler.handle(e); // } // catch (Exception ex) { // LOG.warn("Failed to handle an error in the error handler {}", errorHandler, ex); // } // } // // if (e instanceof IOException) { // throw (IOException) e; // } // else { // throw new IOException(e); // } // } // } // // public abstract boolean isAvailable(); // // abstract protected void sendInternal(List<ByteBuffer> buffers, String ackToken) // throws IOException; // // public static class Config // extends Sender.Config // { // } // } // // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/RequestOption.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class RequestOption // { // private final int size; // private final String chunk; // // public RequestOption( // @JsonProperty("size") int size, // @JsonProperty("chunk") String chunk) // { // this.size = size; // this.chunk = chunk; // } // // @JsonProperty("size") // public int getSize() // { // return size; // } // // @JsonProperty("chunk") // public String getChunk() // { // return chunk; // } // // @Override // public String toString() // { // return "RequestOption{" + // "size=" + size + // ", chunk=" + chunk + // '}'; // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java // public interface Ingester // extends Closeable // { // void ingest(String tag, ByteBuffer dataBuffer) // throws IOException; // // Sender getSender(); // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/FluentdIngester.java import java.util.UUID; import com.fasterxml.jackson.databind.ObjectMapper; import org.komamitsu.fluency.fluentd.ingester.sender.FluentdSender; import org.komamitsu.fluency.fluentd.ingester.sender.RequestOption; import org.komamitsu.fluency.ingester.Ingester; import org.komamitsu.fluency.ingester.sender.Sender; import org.msgpack.core.MessagePack; import org.msgpack.core.MessagePacker; import org.msgpack.jackson.dataformat.MessagePackFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; messagePacker.packRawStringHeader(dataLength); messagePacker.flush(); ByteBuffer headerBuffer = ByteBuffer.wrap(header.toByteArray()); if (config.isAckResponseMode()) { // The spec (https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#entry) // says to encode a 128 bit value as base64, but fluent-bit currently does something different // and in fluent-bit and fluentd there is no validation. So for now we keep it simple, see // discussion on issue #181. String token = UUID.randomUUID().toString(); ByteBuffer optionBuffer = ByteBuffer.wrap(objectMapper.writeValueAsBytes(new RequestOption(dataLength, token))); List<ByteBuffer> buffers = Arrays.asList(headerBuffer, dataBuffer, optionBuffer); synchronized (sender) { sender.sendWithAck(buffers, token); } } else { ByteBuffer optionBuffer = ByteBuffer.wrap(objectMapper.writeValueAsBytes(new RequestOption(dataLength, null))); List<ByteBuffer> buffers = Arrays.asList(headerBuffer, dataBuffer, optionBuffer); synchronized (sender) { sender.send(buffers); } } } @Override
public Sender getSender()
komamitsu/fluency
fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // }
import org.komamitsu.fluency.ingester.sender.Sender; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.ingester; public interface Ingester extends Closeable { void ingest(String tag, ByteBuffer dataBuffer) throws IOException;
// Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/sender/Sender.java // public interface Sender // { // class Config // { // private ErrorHandler errorHandler; // // public ErrorHandler getErrorHandler() // { // return errorHandler; // } // // public void setErrorHandler(ErrorHandler errorHandler) // { // this.errorHandler = errorHandler; // } // // @Override // public String toString() // { // return "Config{" + // "senderErrorHandler=" + errorHandler + // '}'; // } // } // } // Path: fluency-core/src/main/java/org/komamitsu/fluency/ingester/Ingester.java import org.komamitsu.fluency.ingester.sender.Sender; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.ingester; public interface Ingester extends Closeable { void ingest(String tag, ByteBuffer dataBuffer) throws IOException;
Sender getSender();
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/MockTCPServerWithMetrics.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // }
import org.komamitsu.fluency.util.Tuple; import java.net.Socket; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd; public class MockTCPServerWithMetrics extends MockTCPServer {
// Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple.java // public class Tuple<F, S> // { // private final F first; // private final S second; // // public Tuple(F first, S second) // { // this.first = first; // this.second = second; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/MockTCPServerWithMetrics.java import org.komamitsu.fluency.util.Tuple; import java.net.Socket; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd; public class MockTCPServerWithMetrics extends MockTCPServer {
private final List<Tuple<Type, Integer>> events = new CopyOnWriteArrayList<Tuple<Type, Integer>>();
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/RetryableSender.java
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/RetryStrategy.java // public abstract class RetryStrategy // { // private final Config config; // // protected RetryStrategy(Config config) // { // this.config = config; // } // // public abstract int getNextIntervalMillis(int retryCount); // // public boolean isRetriedOver(int retryCount) // { // return retryCount > config.getMaxRetryCount(); // } // // public int getMaxRetryCount() // { // return config.getMaxRetryCount(); // } // // @Override // public String toString() // { // return "RetryStrategy{" + // "config=" + config + // '}'; // } // // public static class Config // { // @Min(0) // private int maxRetryCount = 7; // // public int getMaxRetryCount() // { // return maxRetryCount; // } // // public void setMaxRetryCount(int maxRetryCount) // { // this.maxRetryCount = maxRetryCount; // } // // @Override // public String toString() // { // return "Config{" + // "maxRetryCount=" + maxRetryCount + // '}'; // } // } // }
import org.komamitsu.fluency.fluentd.ingester.sender.retry.RetryStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender; public class RetryableSender extends FluentdSender { private static final Logger LOG = LoggerFactory.getLogger(RetryableSender.class); private final FluentdSender baseSender; private final AtomicBoolean isClosed = new AtomicBoolean();
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/RetryStrategy.java // public abstract class RetryStrategy // { // private final Config config; // // protected RetryStrategy(Config config) // { // this.config = config; // } // // public abstract int getNextIntervalMillis(int retryCount); // // public boolean isRetriedOver(int retryCount) // { // return retryCount > config.getMaxRetryCount(); // } // // public int getMaxRetryCount() // { // return config.getMaxRetryCount(); // } // // @Override // public String toString() // { // return "RetryStrategy{" + // "config=" + config + // '}'; // } // // public static class Config // { // @Min(0) // private int maxRetryCount = 7; // // public int getMaxRetryCount() // { // return maxRetryCount; // } // // public void setMaxRetryCount(int maxRetryCount) // { // this.maxRetryCount = maxRetryCount; // } // // @Override // public String toString() // { // return "Config{" + // "maxRetryCount=" + maxRetryCount + // '}'; // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/RetryableSender.java import org.komamitsu.fluency.fluentd.ingester.sender.retry.RetryStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender; public class RetryableSender extends FluentdSender { private static final Logger LOG = LoggerFactory.getLogger(RetryableSender.class); private final FluentdSender baseSender; private final AtomicBoolean isClosed = new AtomicBoolean();
private RetryStrategy retryStrategy;
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/failuredetect/PhiAccrualFailureDetectStrategy.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // }
import org.komamitsu.failuredetector.PhiAccuralFailureDetector; import org.komamitsu.fluency.validation.Validatable; import org.komamitsu.fluency.validation.annotation.DecimalMin; import org.komamitsu.fluency.validation.annotation.Min;
{ failureDetector.heartbeat(now); } @Override public boolean isAvailable() { return failureDetector.isAvailable(); } public double getPhiThreshold() { return config.getPhiThreshold(); } public int getArrivalWindowSize() { return config.getArrivalWindowSize(); } @Override public String toString() { return "PhiAccrualFailureDetectStrategy{" + "failureDetector=" + failureDetector + "} " + super.toString(); } public static class Config extends FailureDetectStrategy.Config
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/failuredetect/PhiAccrualFailureDetectStrategy.java import org.komamitsu.failuredetector.PhiAccuralFailureDetector; import org.komamitsu.fluency.validation.Validatable; import org.komamitsu.fluency.validation.annotation.DecimalMin; import org.komamitsu.fluency.validation.annotation.Min; { failureDetector.heartbeat(now); } @Override public boolean isAvailable() { return failureDetector.isAvailable(); } public double getPhiThreshold() { return config.getPhiThreshold(); } public int getArrivalWindowSize() { return config.getArrivalWindowSize(); } @Override public String toString() { return "PhiAccrualFailureDetectStrategy{" + "failureDetector=" + failureDetector + "} " + super.toString(); } public static class Config extends FailureDetectStrategy.Config
implements Validatable
komamitsu/fluency
fluency-core/src/main/java/org/komamitsu/fluency/recordformat/MessagePackRecordFormatter.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MapRecordAccessor.java // public class MapRecordAccessor // implements RecordAccessor // { // private Map<String, Object> map; // // public MapRecordAccessor(Map<String, Object> map) // { // this.map = new HashMap<>(map); // } // // @Override // public String getAsString(String key) // { // Object value = map.get(key); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // map.putIfAbsent("time", timestamp); // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // try { // return objectMapperForMessagePack.writeValueAsBytes(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to MessagePack format", e); // } // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // try { // return objectMapperForJson.writeValueAsString(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to JSON format", e); // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MessagePackRecordAccessor.java // public class MessagePackRecordAccessor // implements RecordAccessor // { // private static final StringValue KEY_TIME = ValueFactory.newString("time"); // private MapValueBytes mapValueBytes; // // private static class MapValueBytes { // private final byte[] byteArray; // private final Map<Value, Value> map; // // MapValueBytes(ByteBuffer byteBuffer) // { // byte[] mapValueBytes = new byte[byteBuffer.remaining()]; // byteBuffer.get(mapValueBytes); // try (MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(mapValueBytes)) { // this.map = unpacker.unpackValue().asMapValue().map(); // this.byteArray = mapValueBytes; // } // catch (IOException e) { // throw new IllegalArgumentException("Invalid MessagePack ByteBuffer", e); // } // } // // byte[] byteArray() // { // return byteArray; // } // // Map<Value, Value> map() // { // return map; // } // } // // public MessagePackRecordAccessor(ByteBuffer byteBuffer) // { // mapValueBytes = new MapValueBytes(byteBuffer); // } // // @Override // public String getAsString(String key) // { // Value value = mapValueBytes.map().get(ValueFactory.newString(key)); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // int mapSize = mapValueBytes.map().size(); // try (ByteArrayOutputStream output = new ByteArrayOutputStream(mapValueBytes.byteArray().length + 16)) { // try (MessagePacker packer = MessagePack.newDefaultPacker(output)) { // if (mapValueBytes.map().containsKey(KEY_TIME)) { // packer.packMapHeader(mapSize); // } // else { // packer.packMapHeader(mapSize + 1); // KEY_TIME.writeTo(packer); // packer.packLong(timestamp); // } // // for (Map.Entry<Value, Value> entry : mapValueBytes.map().entrySet()) { // packer.packValue(entry.getKey()); // packer.packValue(entry.getValue()); // } // } // mapValueBytes = new MapValueBytes(ByteBuffer.wrap(output.toByteArray())); // } // catch (IOException e) { // throw new IllegalStateException("Failed to upsert `time` field", e); // } // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // return mapValueBytes.byteArray(); // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // return ValueFactory.newMap(mapValueBytes.map()).toJson(); // } // }
import org.komamitsu.fluency.recordformat.recordaccessor.MapRecordAccessor; import org.komamitsu.fluency.recordformat.recordaccessor.MessagePackRecordAccessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Map;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.recordformat; public class MessagePackRecordFormatter extends AbstractRecordFormatter { private static final Logger LOG = LoggerFactory.getLogger(MessagePackRecordFormatter.class); public MessagePackRecordFormatter() { this(new Config()); } public MessagePackRecordFormatter(Config config) { super(config); } @Override public byte[] format(String tag, Object timestamp, Map<String, Object> data) { try {
// Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MapRecordAccessor.java // public class MapRecordAccessor // implements RecordAccessor // { // private Map<String, Object> map; // // public MapRecordAccessor(Map<String, Object> map) // { // this.map = new HashMap<>(map); // } // // @Override // public String getAsString(String key) // { // Object value = map.get(key); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // map.putIfAbsent("time", timestamp); // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // try { // return objectMapperForMessagePack.writeValueAsBytes(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to MessagePack format", e); // } // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // try { // return objectMapperForJson.writeValueAsString(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to JSON format", e); // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MessagePackRecordAccessor.java // public class MessagePackRecordAccessor // implements RecordAccessor // { // private static final StringValue KEY_TIME = ValueFactory.newString("time"); // private MapValueBytes mapValueBytes; // // private static class MapValueBytes { // private final byte[] byteArray; // private final Map<Value, Value> map; // // MapValueBytes(ByteBuffer byteBuffer) // { // byte[] mapValueBytes = new byte[byteBuffer.remaining()]; // byteBuffer.get(mapValueBytes); // try (MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(mapValueBytes)) { // this.map = unpacker.unpackValue().asMapValue().map(); // this.byteArray = mapValueBytes; // } // catch (IOException e) { // throw new IllegalArgumentException("Invalid MessagePack ByteBuffer", e); // } // } // // byte[] byteArray() // { // return byteArray; // } // // Map<Value, Value> map() // { // return map; // } // } // // public MessagePackRecordAccessor(ByteBuffer byteBuffer) // { // mapValueBytes = new MapValueBytes(byteBuffer); // } // // @Override // public String getAsString(String key) // { // Value value = mapValueBytes.map().get(ValueFactory.newString(key)); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // int mapSize = mapValueBytes.map().size(); // try (ByteArrayOutputStream output = new ByteArrayOutputStream(mapValueBytes.byteArray().length + 16)) { // try (MessagePacker packer = MessagePack.newDefaultPacker(output)) { // if (mapValueBytes.map().containsKey(KEY_TIME)) { // packer.packMapHeader(mapSize); // } // else { // packer.packMapHeader(mapSize + 1); // KEY_TIME.writeTo(packer); // packer.packLong(timestamp); // } // // for (Map.Entry<Value, Value> entry : mapValueBytes.map().entrySet()) { // packer.packValue(entry.getKey()); // packer.packValue(entry.getValue()); // } // } // mapValueBytes = new MapValueBytes(ByteBuffer.wrap(output.toByteArray())); // } // catch (IOException e) { // throw new IllegalStateException("Failed to upsert `time` field", e); // } // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // return mapValueBytes.byteArray(); // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // return ValueFactory.newMap(mapValueBytes.map()).toJson(); // } // } // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/MessagePackRecordFormatter.java import org.komamitsu.fluency.recordformat.recordaccessor.MapRecordAccessor; import org.komamitsu.fluency.recordformat.recordaccessor.MessagePackRecordAccessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Map; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.recordformat; public class MessagePackRecordFormatter extends AbstractRecordFormatter { private static final Logger LOG = LoggerFactory.getLogger(MessagePackRecordFormatter.class); public MessagePackRecordFormatter() { this(new Config()); } public MessagePackRecordFormatter(Config config) { super(config); } @Override public byte[] format(String tag, Object timestamp, Map<String, Object> data) { try {
MapRecordAccessor recordAccessor = new MapRecordAccessor(data);
komamitsu/fluency
fluency-core/src/main/java/org/komamitsu/fluency/recordformat/MessagePackRecordFormatter.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MapRecordAccessor.java // public class MapRecordAccessor // implements RecordAccessor // { // private Map<String, Object> map; // // public MapRecordAccessor(Map<String, Object> map) // { // this.map = new HashMap<>(map); // } // // @Override // public String getAsString(String key) // { // Object value = map.get(key); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // map.putIfAbsent("time", timestamp); // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // try { // return objectMapperForMessagePack.writeValueAsBytes(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to MessagePack format", e); // } // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // try { // return objectMapperForJson.writeValueAsString(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to JSON format", e); // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MessagePackRecordAccessor.java // public class MessagePackRecordAccessor // implements RecordAccessor // { // private static final StringValue KEY_TIME = ValueFactory.newString("time"); // private MapValueBytes mapValueBytes; // // private static class MapValueBytes { // private final byte[] byteArray; // private final Map<Value, Value> map; // // MapValueBytes(ByteBuffer byteBuffer) // { // byte[] mapValueBytes = new byte[byteBuffer.remaining()]; // byteBuffer.get(mapValueBytes); // try (MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(mapValueBytes)) { // this.map = unpacker.unpackValue().asMapValue().map(); // this.byteArray = mapValueBytes; // } // catch (IOException e) { // throw new IllegalArgumentException("Invalid MessagePack ByteBuffer", e); // } // } // // byte[] byteArray() // { // return byteArray; // } // // Map<Value, Value> map() // { // return map; // } // } // // public MessagePackRecordAccessor(ByteBuffer byteBuffer) // { // mapValueBytes = new MapValueBytes(byteBuffer); // } // // @Override // public String getAsString(String key) // { // Value value = mapValueBytes.map().get(ValueFactory.newString(key)); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // int mapSize = mapValueBytes.map().size(); // try (ByteArrayOutputStream output = new ByteArrayOutputStream(mapValueBytes.byteArray().length + 16)) { // try (MessagePacker packer = MessagePack.newDefaultPacker(output)) { // if (mapValueBytes.map().containsKey(KEY_TIME)) { // packer.packMapHeader(mapSize); // } // else { // packer.packMapHeader(mapSize + 1); // KEY_TIME.writeTo(packer); // packer.packLong(timestamp); // } // // for (Map.Entry<Value, Value> entry : mapValueBytes.map().entrySet()) { // packer.packValue(entry.getKey()); // packer.packValue(entry.getValue()); // } // } // mapValueBytes = new MapValueBytes(ByteBuffer.wrap(output.toByteArray())); // } // catch (IOException e) { // throw new IllegalStateException("Failed to upsert `time` field", e); // } // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // return mapValueBytes.byteArray(); // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // return ValueFactory.newMap(mapValueBytes.map()).toJson(); // } // }
import org.komamitsu.fluency.recordformat.recordaccessor.MapRecordAccessor; import org.komamitsu.fluency.recordformat.recordaccessor.MessagePackRecordAccessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Map;
public MessagePackRecordFormatter() { this(new Config()); } public MessagePackRecordFormatter(Config config) { super(config); } @Override public byte[] format(String tag, Object timestamp, Map<String, Object> data) { try { MapRecordAccessor recordAccessor = new MapRecordAccessor(data); recordAccessor.setTimestamp(getEpoch(timestamp)); return recordAccessor.toMessagePack(objectMapperForMessagePack); } catch (Throwable e) { LOG.error(String.format( "Failed to format a Map record: cause=%s, tag=%s, timestamp=%s, recordCount=%d", e.getMessage(), tag, timestamp, data.size())); throw e; } } @Override public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) { try {
// Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MapRecordAccessor.java // public class MapRecordAccessor // implements RecordAccessor // { // private Map<String, Object> map; // // public MapRecordAccessor(Map<String, Object> map) // { // this.map = new HashMap<>(map); // } // // @Override // public String getAsString(String key) // { // Object value = map.get(key); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // map.putIfAbsent("time", timestamp); // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // try { // return objectMapperForMessagePack.writeValueAsBytes(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to MessagePack format", e); // } // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // try { // return objectMapperForJson.writeValueAsString(map); // } // catch (JsonProcessingException e) { // throw new IllegalStateException("Failed to serialize the map to JSON format", e); // } // } // } // // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/recordaccessor/MessagePackRecordAccessor.java // public class MessagePackRecordAccessor // implements RecordAccessor // { // private static final StringValue KEY_TIME = ValueFactory.newString("time"); // private MapValueBytes mapValueBytes; // // private static class MapValueBytes { // private final byte[] byteArray; // private final Map<Value, Value> map; // // MapValueBytes(ByteBuffer byteBuffer) // { // byte[] mapValueBytes = new byte[byteBuffer.remaining()]; // byteBuffer.get(mapValueBytes); // try (MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(mapValueBytes)) { // this.map = unpacker.unpackValue().asMapValue().map(); // this.byteArray = mapValueBytes; // } // catch (IOException e) { // throw new IllegalArgumentException("Invalid MessagePack ByteBuffer", e); // } // } // // byte[] byteArray() // { // return byteArray; // } // // Map<Value, Value> map() // { // return map; // } // } // // public MessagePackRecordAccessor(ByteBuffer byteBuffer) // { // mapValueBytes = new MapValueBytes(byteBuffer); // } // // @Override // public String getAsString(String key) // { // Value value = mapValueBytes.map().get(ValueFactory.newString(key)); // if (value == null) { // return null; // } // return value.toString(); // } // // @Override // public void setTimestamp(long timestamp) // { // int mapSize = mapValueBytes.map().size(); // try (ByteArrayOutputStream output = new ByteArrayOutputStream(mapValueBytes.byteArray().length + 16)) { // try (MessagePacker packer = MessagePack.newDefaultPacker(output)) { // if (mapValueBytes.map().containsKey(KEY_TIME)) { // packer.packMapHeader(mapSize); // } // else { // packer.packMapHeader(mapSize + 1); // KEY_TIME.writeTo(packer); // packer.packLong(timestamp); // } // // for (Map.Entry<Value, Value> entry : mapValueBytes.map().entrySet()) { // packer.packValue(entry.getKey()); // packer.packValue(entry.getValue()); // } // } // mapValueBytes = new MapValueBytes(ByteBuffer.wrap(output.toByteArray())); // } // catch (IOException e) { // throw new IllegalStateException("Failed to upsert `time` field", e); // } // } // // @Override // public byte[] toMessagePack(ObjectMapper objectMapperForMessagePack) // { // return mapValueBytes.byteArray(); // } // // @Override // public String toJson(ObjectMapper objectMapperForJson) // { // return ValueFactory.newMap(mapValueBytes.map()).toJson(); // } // } // Path: fluency-core/src/main/java/org/komamitsu/fluency/recordformat/MessagePackRecordFormatter.java import org.komamitsu.fluency.recordformat.recordaccessor.MapRecordAccessor; import org.komamitsu.fluency.recordformat.recordaccessor.MessagePackRecordAccessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.Map; public MessagePackRecordFormatter() { this(new Config()); } public MessagePackRecordFormatter(Config config) { super(config); } @Override public byte[] format(String tag, Object timestamp, Map<String, Object> data) { try { MapRecordAccessor recordAccessor = new MapRecordAccessor(data); recordAccessor.setTimestamp(getEpoch(timestamp)); return recordAccessor.toMessagePack(objectMapperForMessagePack); } catch (Throwable e) { LOG.error(String.format( "Failed to format a Map record: cause=%s, tag=%s, timestamp=%s, recordCount=%d", e.getMessage(), tag, timestamp, data.size())); throw e; } } @Override public byte[] formatFromMessagePack(String tag, Object timestamp, byte[] mapValue, int offset, int len) { try {
MessagePackRecordAccessor recordAccessor = new MessagePackRecordAccessor(ByteBuffer.wrap(mapValue, offset, len));
komamitsu/fluency
fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/ExponentialBackOffRetryStrategy.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // }
import org.komamitsu.fluency.validation.Validatable; import org.komamitsu.fluency.validation.annotation.Min;
@Override public int getNextIntervalMillis(int retryCount) { int interval = config.getBaseIntervalMillis() * ((int) Math.pow(2.0, (double) retryCount)); if (interval > config.getMaxIntervalMillis()) { return config.getMaxIntervalMillis(); } return interval; } public int getBaseIntervalMillis() { return config.getBaseIntervalMillis(); } public int getMaxIntervalMillis() { return config.getMaxIntervalMillis(); } @Override public String toString() { return "ExponentialBackOffRetryStrategy{" + "config=" + config + "} " + super.toString(); } public static class Config extends RetryStrategy.Config
// Path: fluency-core/src/main/java/org/komamitsu/fluency/validation/Validatable.java // public interface Validatable // { // class ValidationList { // private static class Validation // { // Class<? extends Annotation> annotationClass; // BiFunction<Annotation, Number, Boolean> isValid; // String messageTemplate; // // Validation( // Class<? extends Annotation> annotationClass, // BiFunction<Annotation, Number, Boolean> isValid, // String messageTemplate) // { // this.annotationClass = annotationClass; // this.isValid = isValid; // this.messageTemplate = messageTemplate; // } // } // // private static final Validation VALIDATION_MAX = new Validation( // Max.class, // (annotation, actual) -> { // Max maxAnnotation = (Max) annotation; // if (maxAnnotation.inclusive()) { // return maxAnnotation.value() >= actual.longValue(); // } // else { // return maxAnnotation.value() > actual.longValue(); // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_MIN = new Validation( // Min.class, // (annotation, actual) -> { // Min minAnnotation = (Min) annotation; // if (minAnnotation.inclusive()) { // return minAnnotation.value() <= actual.longValue(); // } // else { // return minAnnotation.value() < actual.longValue(); // } // }, // "This field (%s) is less than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MAX = new Validation( // DecimalMax.class, // (annotation, actual) -> { // DecimalMax maxAnnotation = (DecimalMax) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) >= 0; // } // else { // return limitValue.compareTo(actualValue) > 0; // } // }, // "This field (%s) is more than (%s)"); // // private static final Validation VALIDATION_DECIMAL_MIN = new Validation( // DecimalMin.class, // (annotation, actual) -> { // DecimalMin maxAnnotation = (DecimalMin) annotation; // BigDecimal limitValue = new BigDecimal(maxAnnotation.value()); // BigDecimal actualValue = new BigDecimal(actual.toString()); // if (maxAnnotation.inclusive()) { // return limitValue.compareTo(actualValue) <= 0; // } // else { // return limitValue.compareTo(actualValue) < 0; // } // }, // "This field (%s) is less than (%s)"); // // private static final List<Validation> VALIDATIONS = Arrays.asList( // VALIDATION_MAX, // VALIDATION_MIN, // VALIDATION_DECIMAL_MAX, // VALIDATION_DECIMAL_MIN); // } // // default void validate() // { // Class<? extends Object> klass = getClass(); // while (klass != Object.class) { // for (Field field : klass.getDeclaredFields()) { // for (ValidationList.Validation validation : ValidationList.VALIDATIONS) { // Class<? extends Annotation> annotationClass = validation.annotationClass; // if (field.isAnnotationPresent(annotationClass)) { // Annotation annotation = field.getAnnotation(annotationClass); // Object value; // try { // field.setAccessible(true); // value = field.get(this); // } // catch (IllegalAccessException e) { // throw new RuntimeException( // String.format("Failed to get a value from field (%s)", field), e); // } // // if (value == null) { // break; // } // // if (!(value instanceof Number)) { // throw new IllegalArgumentException( // String.format("This field has (%s), but actual field is (%s)", annotation, value.getClass())); // } // // if (!validation.isValid.apply(annotation, (Number) value)) { // throw new IllegalArgumentException( // String.format(validation.messageTemplate, field, value)); // } // } // } // } // klass = klass.getSuperclass(); // } // } // } // Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/ExponentialBackOffRetryStrategy.java import org.komamitsu.fluency.validation.Validatable; import org.komamitsu.fluency.validation.annotation.Min; @Override public int getNextIntervalMillis(int retryCount) { int interval = config.getBaseIntervalMillis() * ((int) Math.pow(2.0, (double) retryCount)); if (interval > config.getMaxIntervalMillis()) { return config.getMaxIntervalMillis(); } return interval; } public int getBaseIntervalMillis() { return config.getBaseIntervalMillis(); } public int getMaxIntervalMillis() { return config.getMaxIntervalMillis(); } @Override public String toString() { return "ExponentialBackOffRetryStrategy{" + "config=" + config + "} " + super.toString(); } public static class Config extends RetryStrategy.Config
implements Validatable
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/heartbeat/SSLHeartbeaterTest.java
// Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/SSLTestServerSocketFactory.java // public class SSLTestServerSocketFactory // { // private static final String KEYSTORE_PASSWORD = "keypassword"; // private static final String KEY_PASSWORD = "keypassword"; // // public SSLServerSocket create() // throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException // { // String trustStorePath = SSLSocketBuilder.class.getClassLoader().getResource("truststore.jks").getFile(); // System.getProperties().setProperty("javax.net.ssl.trustStore", trustStorePath); // // String keyStorePath = SSLSocketBuilder.class.getClassLoader().getResource("keystore.jks").getFile(); // // InputStream keystoreStream = null; // try { // KeyStore keystore = KeyStore.getInstance("JKS"); // keystoreStream = new FileInputStream(new File(keyStorePath)); // // keystore.load(keystoreStream, KEYSTORE_PASSWORD.toCharArray()); // KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // // keyManagerFactory.init(keystore, KEY_PASSWORD.toCharArray()); // // SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); // sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); // // SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); // serverSocket.setEnabledCipherSuites(serverSocket.getSupportedCipherSuites()); // serverSocket.bind(new InetSocketAddress(0)); // // return serverSocket; // } // finally { // if (keystoreStream != null) { // keystoreStream.close(); // } // } // } // }
import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.SSLTestServerSocketFactory; import javax.net.ssl.SSLServerSocket; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.concurrent.CountDownLatch;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender.heartbeat; public class SSLHeartbeaterTest { private SSLServerSocket sslServerSocket; private SSLHeartbeater heartbeater; @BeforeEach void setUp() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, KeyManagementException, KeyStoreException {
// Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/SSLTestServerSocketFactory.java // public class SSLTestServerSocketFactory // { // private static final String KEYSTORE_PASSWORD = "keypassword"; // private static final String KEY_PASSWORD = "keypassword"; // // public SSLServerSocket create() // throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException // { // String trustStorePath = SSLSocketBuilder.class.getClassLoader().getResource("truststore.jks").getFile(); // System.getProperties().setProperty("javax.net.ssl.trustStore", trustStorePath); // // String keyStorePath = SSLSocketBuilder.class.getClassLoader().getResource("keystore.jks").getFile(); // // InputStream keystoreStream = null; // try { // KeyStore keystore = KeyStore.getInstance("JKS"); // keystoreStream = new FileInputStream(new File(keyStorePath)); // // keystore.load(keystoreStream, KEYSTORE_PASSWORD.toCharArray()); // KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // // keyManagerFactory.init(keystore, KEY_PASSWORD.toCharArray()); // // SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); // sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); // // SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); // serverSocket.setEnabledCipherSuites(serverSocket.getSupportedCipherSuites()); // serverSocket.bind(new InetSocketAddress(0)); // // return serverSocket; // } // finally { // if (keystoreStream != null) { // keystoreStream.close(); // } // } // } // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/heartbeat/SSLHeartbeaterTest.java import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.SSLTestServerSocketFactory; import javax.net.ssl.SSLServerSocket; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.concurrent.CountDownLatch; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender.heartbeat; public class SSLHeartbeaterTest { private SSLServerSocket sslServerSocket; private SSLHeartbeater heartbeater; @BeforeEach void setUp() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, KeyManagementException, KeyStoreException {
sslServerSocket = new SSLTestServerSocketFactory().create();
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/MockTCPServer.java
// Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/SSLTestServerSocketFactory.java // public class SSLTestServerSocketFactory // { // private static final String KEYSTORE_PASSWORD = "keypassword"; // private static final String KEY_PASSWORD = "keypassword"; // // public SSLServerSocket create() // throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException // { // String trustStorePath = SSLSocketBuilder.class.getClassLoader().getResource("truststore.jks").getFile(); // System.getProperties().setProperty("javax.net.ssl.trustStore", trustStorePath); // // String keyStorePath = SSLSocketBuilder.class.getClassLoader().getResource("keystore.jks").getFile(); // // InputStream keystoreStream = null; // try { // KeyStore keystore = KeyStore.getInstance("JKS"); // keystoreStream = new FileInputStream(new File(keyStorePath)); // // keystore.load(keystoreStream, KEYSTORE_PASSWORD.toCharArray()); // KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // // keyManagerFactory.init(keystore, KEY_PASSWORD.toCharArray()); // // SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); // sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); // // SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); // serverSocket.setEnabledCipherSuites(serverSocket.getSupportedCipherSuites()); // serverSocket.bind(new InetSocketAddress(0)); // // return serverSocket; // } // finally { // if (keystoreStream != null) { // keystoreStream.close(); // } // } // } // }
import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.komamitsu.fluency.fluentd.ingester.sender.SSLTestServerSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLHandshakeException; import java.io.EOFException; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.channels.ClosedByInterruptException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException;
} @Override public void onReceive(Socket acceptSocket, int len, byte[] data) { } @Override public void onClose(Socket acceptSocket) { } }; } public synchronized void start() throws Exception { if (executorService == null) { this.executorService = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, String.format("accepted-socket-worker-%d", threadSeqNum.getAndAdd(1))); } }); } if (serverTask == null) { serverTask = new ServerTask(executorService, lastEventTimeStampMilli, getEventHandler(),
// Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/SSLTestServerSocketFactory.java // public class SSLTestServerSocketFactory // { // private static final String KEYSTORE_PASSWORD = "keypassword"; // private static final String KEY_PASSWORD = "keypassword"; // // public SSLServerSocket create() // throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException // { // String trustStorePath = SSLSocketBuilder.class.getClassLoader().getResource("truststore.jks").getFile(); // System.getProperties().setProperty("javax.net.ssl.trustStore", trustStorePath); // // String keyStorePath = SSLSocketBuilder.class.getClassLoader().getResource("keystore.jks").getFile(); // // InputStream keystoreStream = null; // try { // KeyStore keystore = KeyStore.getInstance("JKS"); // keystoreStream = new FileInputStream(new File(keyStorePath)); // // keystore.load(keystoreStream, KEYSTORE_PASSWORD.toCharArray()); // KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // // keyManagerFactory.init(keystore, KEY_PASSWORD.toCharArray()); // // SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); // sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); // // SSLServerSocket serverSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(); // serverSocket.setEnabledCipherSuites(serverSocket.getSupportedCipherSuites()); // serverSocket.bind(new InetSocketAddress(0)); // // return serverSocket; // } // finally { // if (keystoreStream != null) { // keystoreStream.close(); // } // } // } // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/MockTCPServer.java import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.komamitsu.fluency.fluentd.ingester.sender.SSLTestServerSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLHandshakeException; import java.io.EOFException; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.channels.ClosedByInterruptException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; } @Override public void onReceive(Socket acceptSocket, int len, byte[] data) { } @Override public void onClose(Socket acceptSocket) { } }; } public synchronized void start() throws Exception { if (executorService == null) { this.executorService = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, String.format("accepted-socket-worker-%d", threadSeqNum.getAndAdd(1))); } }); } if (serverTask == null) { serverTask = new ServerTask(executorService, lastEventTimeStampMilli, getEventHandler(),
sslEnabled ? new SSLTestServerSocketFactory().create() : new ServerSocket());
komamitsu/fluency
fluency-aws-s3/src/test/java/org/komamitsu/fluency/aws/s3/ingester/sender/AwsS3SenderTest.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/RetryableException.java // public class RetryableException // extends RuntimeException // { // public RetryableException(String message) // { // super(message); // } // // public RetryableException(String message, Throwable cause) // { // super(message, cause); // } // }
import com.google.common.io.ByteStreams; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.komamitsu.fluency.RetryableException; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPInputStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
verify(s3Client, times(failures + 1)).putObject(any(PutObjectRequest.class), any(RequestBody.class)); sender.close(); } @ParameterizedTest @ValueSource(ints={0, 2}) void send(int failures) throws IOException { AwsS3Sender.Config config = new AwsS3Sender.Config(); testSend(config, true, failures); } @ParameterizedTest @ValueSource(ints={0, 2}) void sendWithoutCompression(int failures) throws IOException { AwsS3Sender.Config config = new AwsS3Sender.Config(); config.setCompressionEnabled(false); testSend(config, false, failures); } @Test void sendButRetryOver() { AwsS3Sender.Config config = new AwsS3Sender.Config(); config.setRetryMax(2);
// Path: fluency-core/src/main/java/org/komamitsu/fluency/RetryableException.java // public class RetryableException // extends RuntimeException // { // public RetryableException(String message) // { // super(message); // } // // public RetryableException(String message, Throwable cause) // { // super(message, cause); // } // } // Path: fluency-aws-s3/src/test/java/org/komamitsu/fluency/aws/s3/ingester/sender/AwsS3SenderTest.java import com.google.common.io.ByteStreams; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.komamitsu.fluency.RetryableException; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPInputStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; verify(s3Client, times(failures + 1)).putObject(any(PutObjectRequest.class), any(RequestBody.class)); sender.close(); } @ParameterizedTest @ValueSource(ints={0, 2}) void send(int failures) throws IOException { AwsS3Sender.Config config = new AwsS3Sender.Config(); testSend(config, true, failures); } @ParameterizedTest @ValueSource(ints={0, 2}) void sendWithoutCompression(int failures) throws IOException { AwsS3Sender.Config config = new AwsS3Sender.Config(); config.setCompressionEnabled(false); testSend(config, false, failures); } @Test void sendButRetryOver() { AwsS3Sender.Config config = new AwsS3Sender.Config(); config.setRetryMax(2);
assertThrows(RetryableException.class, () -> testSend(config, true, 3));
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/heartbeat/HeartbeaterTest.java
// Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple3.java // public class Tuple3<F, S, T> // { // private final F first; // private final S second; // private final T third; // // public Tuple3(F first, S second, T third) // { // this.first = first; // this.second = second; // this.third = third; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // // public T getThird() // { // return third; // } // }
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.util.Tuple3; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue;
/* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender.heartbeat; public class HeartbeaterTest { private TestableHeartbeater.Config config; @BeforeEach public void setup() { config = new TestableHeartbeater.Config(); config.setHost("dummy-hostname"); config.setPort(123456); config.setIntervalMillis(300); } @Test public void testHeartbeater() throws InterruptedException { try (TestableHeartbeater heartbeater = new TestableHeartbeater(config)) { heartbeater.start(); TimeUnit.SECONDS.sleep(1); heartbeater.close(); TimeUnit.MILLISECONDS.sleep(500); assertTrue(1 < heartbeater.pongedRecords.size() && heartbeater.pongedRecords.size() < 4);
// Path: fluency-core/src/main/java/org/komamitsu/fluency/util/Tuple3.java // public class Tuple3<F, S, T> // { // private final F first; // private final S second; // private final T third; // // public Tuple3(F first, S second, T third) // { // this.first = first; // this.second = second; // this.third = third; // } // // public F getFirst() // { // return first; // } // // public S getSecond() // { // return second; // } // // public T getThird() // { // return third; // } // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/heartbeat/HeartbeaterTest.java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.komamitsu.fluency.util.Tuple3; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /* * Copyright 2018 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender.heartbeat; public class HeartbeaterTest { private TestableHeartbeater.Config config; @BeforeEach public void setup() { config = new TestableHeartbeater.Config(); config.setHost("dummy-hostname"); config.setPort(123456); config.setIntervalMillis(300); } @Test public void testHeartbeater() throws InterruptedException { try (TestableHeartbeater heartbeater = new TestableHeartbeater(config)) { heartbeater.start(); TimeUnit.SECONDS.sleep(1); heartbeater.close(); TimeUnit.MILLISECONDS.sleep(500); assertTrue(1 < heartbeater.pongedRecords.size() && heartbeater.pongedRecords.size() < 4);
Tuple3<Long, String, Integer> firstPong = heartbeater.pongedRecords.get(0);
komamitsu/fluency
fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/RetryableSenderTest.java
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/ExponentialBackOffRetryStrategy.java // public class ExponentialBackOffRetryStrategy // extends RetryStrategy // { // private final Config config; // // public ExponentialBackOffRetryStrategy() // { // this(new Config()); // } // // public ExponentialBackOffRetryStrategy(Config config) // { // super(config); // config.validateValues(); // this.config = config; // } // // @Override // public int getNextIntervalMillis(int retryCount) // { // int interval = config.getBaseIntervalMillis() * ((int) Math.pow(2.0, (double) retryCount)); // if (interval > config.getMaxIntervalMillis()) { // return config.getMaxIntervalMillis(); // } // return interval; // } // // public int getBaseIntervalMillis() // { // return config.getBaseIntervalMillis(); // } // // public int getMaxIntervalMillis() // { // return config.getMaxIntervalMillis(); // } // // @Override // public String toString() // { // return "ExponentialBackOffRetryStrategy{" + // "config=" + config + // "} " + super.toString(); // } // // public static class Config // extends RetryStrategy.Config // implements Validatable // { // @Min(10) // private int baseIntervalMillis = 400; // @Min(10) // private int maxIntervalMillis = 30 * 1000; // // public int getBaseIntervalMillis() // { // return baseIntervalMillis; // } // // public void setBaseIntervalMillis(int baseIntervalMillis) // { // this.baseIntervalMillis = baseIntervalMillis; // } // // public int getMaxIntervalMillis() // { // return maxIntervalMillis; // } // // public void setMaxIntervalMillis(int maxIntervalMillis) // { // this.maxIntervalMillis = maxIntervalMillis; // } // // void validateValues() // { // validate(); // } // // @Override // public String toString() // { // return "Config{" + // "baseIntervalMillis=" + baseIntervalMillis + // ", maxIntervalMillis=" + maxIntervalMillis + // "} " + super.toString(); // } // } // }
import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.retry.ExponentialBackOffRetryStrategy; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows;
/* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender; class RetryableSenderTest { @Test void testSend() throws IOException {
// Path: fluency-fluentd/src/main/java/org/komamitsu/fluency/fluentd/ingester/sender/retry/ExponentialBackOffRetryStrategy.java // public class ExponentialBackOffRetryStrategy // extends RetryStrategy // { // private final Config config; // // public ExponentialBackOffRetryStrategy() // { // this(new Config()); // } // // public ExponentialBackOffRetryStrategy(Config config) // { // super(config); // config.validateValues(); // this.config = config; // } // // @Override // public int getNextIntervalMillis(int retryCount) // { // int interval = config.getBaseIntervalMillis() * ((int) Math.pow(2.0, (double) retryCount)); // if (interval > config.getMaxIntervalMillis()) { // return config.getMaxIntervalMillis(); // } // return interval; // } // // public int getBaseIntervalMillis() // { // return config.getBaseIntervalMillis(); // } // // public int getMaxIntervalMillis() // { // return config.getMaxIntervalMillis(); // } // // @Override // public String toString() // { // return "ExponentialBackOffRetryStrategy{" + // "config=" + config + // "} " + super.toString(); // } // // public static class Config // extends RetryStrategy.Config // implements Validatable // { // @Min(10) // private int baseIntervalMillis = 400; // @Min(10) // private int maxIntervalMillis = 30 * 1000; // // public int getBaseIntervalMillis() // { // return baseIntervalMillis; // } // // public void setBaseIntervalMillis(int baseIntervalMillis) // { // this.baseIntervalMillis = baseIntervalMillis; // } // // public int getMaxIntervalMillis() // { // return maxIntervalMillis; // } // // public void setMaxIntervalMillis(int maxIntervalMillis) // { // this.maxIntervalMillis = maxIntervalMillis; // } // // void validateValues() // { // validate(); // } // // @Override // public String toString() // { // return "Config{" + // "baseIntervalMillis=" + baseIntervalMillis + // ", maxIntervalMillis=" + maxIntervalMillis + // "} " + super.toString(); // } // } // } // Path: fluency-fluentd/src/test/java/org/komamitsu/fluency/fluentd/ingester/sender/RetryableSenderTest.java import org.junit.jupiter.api.Test; import org.komamitsu.fluency.fluentd.ingester.sender.retry.ExponentialBackOffRetryStrategy; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; /* * Copyright 2019 Mitsunori Komatsu (komamitsu) * * 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.komamitsu.fluency.fluentd.ingester.sender; class RetryableSenderTest { @Test void testSend() throws IOException {
ExponentialBackOffRetryStrategy.Config retryStrategyConfig =
evilwan/raptor-chess-interface
raptor/src/main/java/raptor/engine/uci/UCIEngine.java
// Path: raptor/src/main/java/raptor/engine/uci/info/NodesSearchedInfo.java // public class NodesSearchedInfo extends UCIInfo { // protected int nodesSearched; // // public int getNodesSearched() { // return nodesSearched; // } // // public void setNodesSearched(int nodesSearched) { // this.nodesSearched = nodesSearched; // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.apache.commons.lang.StringUtils; import raptor.chess.Move; import raptor.engine.uci.info.BestLineFoundInfo; import raptor.engine.uci.info.CPULoadInfo; import raptor.engine.uci.info.CurrentMoveInfo; import raptor.engine.uci.info.DepthInfo; import raptor.engine.uci.info.NodesPerSecondInfo; import raptor.engine.uci.info.NodesSearchedInfo; import raptor.engine.uci.info.ScoreInfo; import raptor.engine.uci.info.SelectiveSearchDepthInfo; import raptor.engine.uci.info.StringInfo; import raptor.engine.uci.info.TableBaseHitsInfo; import raptor.engine.uci.info.TimeInfo; import raptor.engine.uci.options.UCIButton; import raptor.engine.uci.options.UCICheck; import raptor.engine.uci.options.UCICombo; import raptor.engine.uci.options.UCISpinner; import raptor.engine.uci.options.UCIString; import raptor.service.ThreadService; import raptor.util.RaptorLogger; import raptor.util.RaptorStringTokenizer;
String type = null; if (nextType != null) { type = nextType; nextType = null; } else { type = tok.nextToken(); } while (!isSupportedInfoType(type) && tok.hasMoreTokens()) { type = tok.nextToken(); } if (!isSupportedInfoType(type)) { break; } if (type.equalsIgnoreCase("depth")) { DepthInfo depthInfo = new DepthInfo(); depthInfo .setSearchDepthPlies(Integer.parseInt(tok.nextToken())); infos.add(depthInfo); } else if (type.equalsIgnoreCase("seldepth")) { SelectiveSearchDepthInfo ssDepthInfo = new SelectiveSearchDepthInfo(); ssDepthInfo.setDepthInPlies(Integer.parseInt(tok.nextToken())); infos.add(ssDepthInfo); } else if (type.equalsIgnoreCase("time")) { TimeInfo timeInfo = new TimeInfo(); timeInfo.setTimeMillis(Integer.parseInt(tok.nextToken())); infos.add(timeInfo); } else if (type.equalsIgnoreCase("nodes")) {
// Path: raptor/src/main/java/raptor/engine/uci/info/NodesSearchedInfo.java // public class NodesSearchedInfo extends UCIInfo { // protected int nodesSearched; // // public int getNodesSearched() { // return nodesSearched; // } // // public void setNodesSearched(int nodesSearched) { // this.nodesSearched = nodesSearched; // } // // } // Path: raptor/src/main/java/raptor/engine/uci/UCIEngine.java import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.apache.commons.lang.StringUtils; import raptor.chess.Move; import raptor.engine.uci.info.BestLineFoundInfo; import raptor.engine.uci.info.CPULoadInfo; import raptor.engine.uci.info.CurrentMoveInfo; import raptor.engine.uci.info.DepthInfo; import raptor.engine.uci.info.NodesPerSecondInfo; import raptor.engine.uci.info.NodesSearchedInfo; import raptor.engine.uci.info.ScoreInfo; import raptor.engine.uci.info.SelectiveSearchDepthInfo; import raptor.engine.uci.info.StringInfo; import raptor.engine.uci.info.TableBaseHitsInfo; import raptor.engine.uci.info.TimeInfo; import raptor.engine.uci.options.UCIButton; import raptor.engine.uci.options.UCICheck; import raptor.engine.uci.options.UCICombo; import raptor.engine.uci.options.UCISpinner; import raptor.engine.uci.options.UCIString; import raptor.service.ThreadService; import raptor.util.RaptorLogger; import raptor.util.RaptorStringTokenizer; String type = null; if (nextType != null) { type = nextType; nextType = null; } else { type = tok.nextToken(); } while (!isSupportedInfoType(type) && tok.hasMoreTokens()) { type = tok.nextToken(); } if (!isSupportedInfoType(type)) { break; } if (type.equalsIgnoreCase("depth")) { DepthInfo depthInfo = new DepthInfo(); depthInfo .setSearchDepthPlies(Integer.parseInt(tok.nextToken())); infos.add(depthInfo); } else if (type.equalsIgnoreCase("seldepth")) { SelectiveSearchDepthInfo ssDepthInfo = new SelectiveSearchDepthInfo(); ssDepthInfo.setDepthInPlies(Integer.parseInt(tok.nextToken())); infos.add(ssDepthInfo); } else if (type.equalsIgnoreCase("time")) { TimeInfo timeInfo = new TimeInfo(); timeInfo.setTimeMillis(Integer.parseInt(tok.nextToken())); infos.add(timeInfo); } else if (type.equalsIgnoreCase("nodes")) {
NodesSearchedInfo nodesSearched = new NodesSearchedInfo();
michael-rapp/AndroidMaterialPreferences
library/src/main/java/de/mrapp/android/preference/SeekBarPreference.java
// Path: library/src/main/java/de/mrapp/android/preference/view/SeekBar.java // public class SeekBar extends AppCompatSeekBar { // // /** // * The drawable, which is used to visualize the seek bar's thumb. // */ // private Drawable thumb; // // /** // * The seekBarColor of the seek bar. // */ // private int seekBarColor; // // /** // * Applies the attributes of the context's theme on the seek bar. // */ // private void applyTheme() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // setSeekBarColor(ThemeUtil.getColor(getContext(), R.attr.colorAccent)); // } // } // // /** // * Creates a new seek bar. // * // * @param context // * The context, which should be used by the seek bar, as an instance of the class {@link // * Context}. The context may not be null // */ // public SeekBar(@NonNull final Context context) { // super(context); // applyTheme(); // } // // /** // * Creates a new seek bar. // * // * @param context // * The context, which should be used by the seek bar, as an instance of the class {@link // * Context}. The context may not be null // * @param attributeSet // * The attributes of the XML tag that is inflating the view, as an instance of the type // * {@link AttributeSet} or null, if no attributes are available // */ // public SeekBar(@NonNull final Context context, @Nullable final AttributeSet attributeSet) { // super(context, attributeSet); // applyTheme(); // } // // /** // * Creates a new seek bar. // * // * @param context // * The context, which should be used by the seek bar, as an instance of the class {@link // * Context}. The context may not be null // * @param attributeSet // * The attributes of the XML tag that is inflating the view, as an instance of the type // * {@link AttributeSet} or null, if no attributes are available // * @param defaultStyle // * The default style to apply to this view. If 0, no style will be applied (beyond what // * is included in the theme). This may either be an attribute resource, whose value will // * be retrieved from the current theme, or an explicit style resource // */ // public SeekBar(@NonNull final Context context, @Nullable final AttributeSet attributeSet, // @AttrRes final int defaultStyle) { // super(context, attributeSet, defaultStyle); // applyTheme(); // } // // /** // * Returns the color of the seek bar. // * // * @return The color of the seek bar as an {@link Integer} value // */ // public final int getSeekBarColor() { // return seekBarColor; // } // // /** // * Sets the color of the seek bar. // * // * @param color // * The color, which should be set as an {@link Integer} value // */ // public final void setSeekBarColor(@ColorInt final int color) { // this.seekBarColor = color; // ColorFilter colorFilter = new PorterDuffColorFilter(color, Mode.SRC_IN); // getProgressDrawable().setColorFilter(colorFilter); // getThumbDrawable().setColorFilter(colorFilter); // } // // /** // * Returns the drawable, which is used to visualize the seek bar's thumb. // * // * @return The drawable, which is used to visualize the seek bar's thumb, as an instance of the // * class {@link Drawable} // */ // public final Drawable getThumbDrawable() { // return thumb; // } // // @Override // public final void setThumb(final Drawable thumb) { // super.setThumb(thumb); // this.thumb = thumb; // } // // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.content.res.Resources.NotFoundException; import android.content.res.TypedArray; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import androidx.annotation.ArrayRes; import androidx.annotation.AttrRes; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.annotation.StyleRes; import de.mrapp.android.dialog.AbstractButtonBarDialog; import de.mrapp.android.dialog.builder.AbstractButtonBarDialogBuilder; import de.mrapp.android.preference.view.SeekBar; import de.mrapp.android.util.view.AbstractSavedState; import de.mrapp.util.Condition;
} /** * Returns the value, a floating point value has to be multiplied with to transform it to an * integer value which is able to encode all of its decimals. By dividing such an integer value * by the return value of this method, the integer value can be transformed back to the original * floating point value. * * @return The multiplier as an {@link Integer} value */ private int getMultiplier() { return (int) Math.pow(NUMERIC_SYSTEM, getDecimals()); } /** * Creates and returns a listener, which allows to display the currently chosen value of the * pereference's seek bar. The current value is internally stored, but it will not become * persisted, until the user's confirmation. * * @param progressTextView * The text view, which should be used to display the currently chosen value, as an * instance of the class {@link TextView}. The text view may not be null * @return The listener, which has been created, as an instance of the type {@link * OnSeekBarChangeListener} */ private OnSeekBarChangeListener createSeekBarListener( @NonNull final TextView progressTextView) { return new OnSeekBarChangeListener() { @Override
// Path: library/src/main/java/de/mrapp/android/preference/view/SeekBar.java // public class SeekBar extends AppCompatSeekBar { // // /** // * The drawable, which is used to visualize the seek bar's thumb. // */ // private Drawable thumb; // // /** // * The seekBarColor of the seek bar. // */ // private int seekBarColor; // // /** // * Applies the attributes of the context's theme on the seek bar. // */ // private void applyTheme() { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // setSeekBarColor(ThemeUtil.getColor(getContext(), R.attr.colorAccent)); // } // } // // /** // * Creates a new seek bar. // * // * @param context // * The context, which should be used by the seek bar, as an instance of the class {@link // * Context}. The context may not be null // */ // public SeekBar(@NonNull final Context context) { // super(context); // applyTheme(); // } // // /** // * Creates a new seek bar. // * // * @param context // * The context, which should be used by the seek bar, as an instance of the class {@link // * Context}. The context may not be null // * @param attributeSet // * The attributes of the XML tag that is inflating the view, as an instance of the type // * {@link AttributeSet} or null, if no attributes are available // */ // public SeekBar(@NonNull final Context context, @Nullable final AttributeSet attributeSet) { // super(context, attributeSet); // applyTheme(); // } // // /** // * Creates a new seek bar. // * // * @param context // * The context, which should be used by the seek bar, as an instance of the class {@link // * Context}. The context may not be null // * @param attributeSet // * The attributes of the XML tag that is inflating the view, as an instance of the type // * {@link AttributeSet} or null, if no attributes are available // * @param defaultStyle // * The default style to apply to this view. If 0, no style will be applied (beyond what // * is included in the theme). This may either be an attribute resource, whose value will // * be retrieved from the current theme, or an explicit style resource // */ // public SeekBar(@NonNull final Context context, @Nullable final AttributeSet attributeSet, // @AttrRes final int defaultStyle) { // super(context, attributeSet, defaultStyle); // applyTheme(); // } // // /** // * Returns the color of the seek bar. // * // * @return The color of the seek bar as an {@link Integer} value // */ // public final int getSeekBarColor() { // return seekBarColor; // } // // /** // * Sets the color of the seek bar. // * // * @param color // * The color, which should be set as an {@link Integer} value // */ // public final void setSeekBarColor(@ColorInt final int color) { // this.seekBarColor = color; // ColorFilter colorFilter = new PorterDuffColorFilter(color, Mode.SRC_IN); // getProgressDrawable().setColorFilter(colorFilter); // getThumbDrawable().setColorFilter(colorFilter); // } // // /** // * Returns the drawable, which is used to visualize the seek bar's thumb. // * // * @return The drawable, which is used to visualize the seek bar's thumb, as an instance of the // * class {@link Drawable} // */ // public final Drawable getThumbDrawable() { // return thumb; // } // // @Override // public final void setThumb(final Drawable thumb) { // super.setThumb(thumb); // this.thumb = thumb; // } // // } // Path: library/src/main/java/de/mrapp/android/preference/SeekBarPreference.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.content.res.Resources.NotFoundException; import android.content.res.TypedArray; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import androidx.annotation.ArrayRes; import androidx.annotation.AttrRes; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.annotation.StyleRes; import de.mrapp.android.dialog.AbstractButtonBarDialog; import de.mrapp.android.dialog.builder.AbstractButtonBarDialogBuilder; import de.mrapp.android.preference.view.SeekBar; import de.mrapp.android.util.view.AbstractSavedState; import de.mrapp.util.Condition; } /** * Returns the value, a floating point value has to be multiplied with to transform it to an * integer value which is able to encode all of its decimals. By dividing such an integer value * by the return value of this method, the integer value can be transformed back to the original * floating point value. * * @return The multiplier as an {@link Integer} value */ private int getMultiplier() { return (int) Math.pow(NUMERIC_SYSTEM, getDecimals()); } /** * Creates and returns a listener, which allows to display the currently chosen value of the * pereference's seek bar. The current value is internally stored, but it will not become * persisted, until the user's confirmation. * * @param progressTextView * The text view, which should be used to display the currently chosen value, as an * instance of the class {@link TextView}. The text view may not be null * @return The listener, which has been created, as an instance of the type {@link * OnSeekBarChangeListener} */ private OnSeekBarChangeListener createSeekBarListener( @NonNull final TextView progressTextView) { return new OnSeekBarChangeListener() { @Override
public void onStopTrackingTouch(final android.widget.SeekBar seekBar) {
michael-rapp/AndroidMaterialPreferences
library/src/main/java/de/mrapp/android/preference/multithreading/ColorPreviewDataBinder.java
// Path: library/src/main/java/de/mrapp/android/preference/AbstractColorPickerPreference.java // public enum PreviewShape { // // /** // * If the preview is shaped as a circle. // */ // CIRCLE(0), // // /** // * If the preview is shaped as a square. // */ // SQUARE(1); // // /** // * The value of the shape. // */ // private final int value; // // /** // * Creates a new shape. // * // * @param value // * The value of the shape as an {@link Integer} value // */ // PreviewShape(final int value) { // this.value = value; // } // // /** // * Returns the value of the shape. // * // * @return The value of the shape as an {@link Integer} value // */ // public final int getValue() { // return value; // } // // /** // * Returns the shape, which corresponds to a specific value. // * // * @param value // * The value of the shape, which should be returned, as an {@link Integer} value // * @return The shape, which corresponds to the given value, as an instance of the enum // * {@link PreviewShape} // */ // public static PreviewShape fromValue(final int value) { // for (PreviewShape shape : values()) { // if (shape.getValue() == value) { // return shape; // } // } // // throw new IllegalArgumentException("Invalid enum value"); // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import de.mrapp.android.preference.AbstractColorPickerPreference.PreviewShape; import de.mrapp.android.util.multithreading.AbstractDataBinder; import de.mrapp.util.Condition; import static de.mrapp.android.util.BitmapUtil.clipCircle; import static de.mrapp.android.util.BitmapUtil.clipSquare; import static de.mrapp.android.util.BitmapUtil.drawableToBitmap; import static de.mrapp.android.util.BitmapUtil.tile; import static de.mrapp.android.util.BitmapUtil.tint;
/* * Copyright 2014 - 2020 Michael Rapp * * 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 de.mrapp.android.preference.multithreading; /** * A data loader, which allows to load the previews of colors. * * @author Michael Rapp * @since 1.7.0 */ public class ColorPreviewDataBinder extends AbstractDataBinder<Bitmap, Integer, ImageView, Void> { /** * The background of the preview. */ private Drawable background; /** * The shape of the preview. */
// Path: library/src/main/java/de/mrapp/android/preference/AbstractColorPickerPreference.java // public enum PreviewShape { // // /** // * If the preview is shaped as a circle. // */ // CIRCLE(0), // // /** // * If the preview is shaped as a square. // */ // SQUARE(1); // // /** // * The value of the shape. // */ // private final int value; // // /** // * Creates a new shape. // * // * @param value // * The value of the shape as an {@link Integer} value // */ // PreviewShape(final int value) { // this.value = value; // } // // /** // * Returns the value of the shape. // * // * @return The value of the shape as an {@link Integer} value // */ // public final int getValue() { // return value; // } // // /** // * Returns the shape, which corresponds to a specific value. // * // * @param value // * The value of the shape, which should be returned, as an {@link Integer} value // * @return The shape, which corresponds to the given value, as an instance of the enum // * {@link PreviewShape} // */ // public static PreviewShape fromValue(final int value) { // for (PreviewShape shape : values()) { // if (shape.getValue() == value) { // return shape; // } // } // // throw new IllegalArgumentException("Invalid enum value"); // } // // } // Path: library/src/main/java/de/mrapp/android/preference/multithreading/ColorPreviewDataBinder.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import de.mrapp.android.preference.AbstractColorPickerPreference.PreviewShape; import de.mrapp.android.util.multithreading.AbstractDataBinder; import de.mrapp.util.Condition; import static de.mrapp.android.util.BitmapUtil.clipCircle; import static de.mrapp.android.util.BitmapUtil.clipSquare; import static de.mrapp.android.util.BitmapUtil.drawableToBitmap; import static de.mrapp.android.util.BitmapUtil.tile; import static de.mrapp.android.util.BitmapUtil.tint; /* * Copyright 2014 - 2020 Michael Rapp * * 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 de.mrapp.android.preference.multithreading; /** * A data loader, which allows to load the previews of colors. * * @author Michael Rapp * @since 1.7.0 */ public class ColorPreviewDataBinder extends AbstractDataBinder<Bitmap, Integer, ImageView, Void> { /** * The background of the preview. */ private Drawable background; /** * The shape of the preview. */
private PreviewShape shape;
maker56/UltimateSurvivalGames
UltimateSurvivalGames/src/me/maker56/survivalgames/UpdateCheck.java
// Path: UltimateSurvivalGames/src/me/maker56/survivalgames/listener/UpdateListener.java // public class UpdateListener implements Listener { // // private static String version = null, updateInfo = null;; // // public static void update(String version) { // UpdateListener.version = version; // System.out.println("[SurvivalGames] A newer version of survivalgames is available. (" + version + ") You can download it here: http://dev.bukkit.org/bukkit-plugins/ultimatesurvivalgames/ You're using " + SurvivalGames.version); // updateInfo = MessageHandler.getMessage("prefix") + "§eA newer version of SurvivalGames is available. §7(§b" + version + "§7) §eYou can download it here: §bhttp://dev.bukkit.org/bukkit-plugins/ultimatesurvivalgames/ §7You're using §o" + SurvivalGames.version; // for(Player p : Bukkit.getOnlinePlayers()) { // if(PermissionHandler.hasPermission(p, Permission.LOBBY) || PermissionHandler.hasPermission(p, Permission.ARENA)) { // p.sendMessage(updateInfo); // } // } // // } // // @EventHandler(priority = EventPriority.MONITOR) // public void onPlayerJoin(PlayerJoinEvent event) { // Player p = event.getPlayer(); // if(PermissionHandler.hasPermission(p, Permission.LOBBY) || PermissionHandler.hasPermission(p, Permission.ARENA)) { // if(version != null) // p.sendMessage(updateInfo); // if(outdated != null) { // p.sendMessage(""); // p.sendMessage(outdated); // } // } // } // // // TEMPORARY UPDATE STUFF // private static String outdated = null; // public static void setOutdatedMaps(String s) { // outdated = s; // for(Player p : Bukkit.getOnlinePlayers()) { // if(PermissionHandler.hasPermission(p, Permission.LOBBY) || PermissionHandler.hasPermission(p, Permission.ARENA)) { // p.sendMessage(s); // } // } // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import me.maker56.survivalgames.listener.UpdateListener; import org.bukkit.plugin.Plugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue;
} this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } return false; } } private class UpdateRunnable implements Runnable { @Override public void run() { if (UpdateCheck.this.url != null) { // Obtain the results of the project's file feed if (UpdateCheck.this.read()) { if(!SurvivalGames.version.equals(UpdateCheck.this.versionName)) {
// Path: UltimateSurvivalGames/src/me/maker56/survivalgames/listener/UpdateListener.java // public class UpdateListener implements Listener { // // private static String version = null, updateInfo = null;; // // public static void update(String version) { // UpdateListener.version = version; // System.out.println("[SurvivalGames] A newer version of survivalgames is available. (" + version + ") You can download it here: http://dev.bukkit.org/bukkit-plugins/ultimatesurvivalgames/ You're using " + SurvivalGames.version); // updateInfo = MessageHandler.getMessage("prefix") + "§eA newer version of SurvivalGames is available. §7(§b" + version + "§7) §eYou can download it here: §bhttp://dev.bukkit.org/bukkit-plugins/ultimatesurvivalgames/ §7You're using §o" + SurvivalGames.version; // for(Player p : Bukkit.getOnlinePlayers()) { // if(PermissionHandler.hasPermission(p, Permission.LOBBY) || PermissionHandler.hasPermission(p, Permission.ARENA)) { // p.sendMessage(updateInfo); // } // } // // } // // @EventHandler(priority = EventPriority.MONITOR) // public void onPlayerJoin(PlayerJoinEvent event) { // Player p = event.getPlayer(); // if(PermissionHandler.hasPermission(p, Permission.LOBBY) || PermissionHandler.hasPermission(p, Permission.ARENA)) { // if(version != null) // p.sendMessage(updateInfo); // if(outdated != null) { // p.sendMessage(""); // p.sendMessage(outdated); // } // } // } // // // TEMPORARY UPDATE STUFF // private static String outdated = null; // public static void setOutdatedMaps(String s) { // outdated = s; // for(Player p : Bukkit.getOnlinePlayers()) { // if(PermissionHandler.hasPermission(p, Permission.LOBBY) || PermissionHandler.hasPermission(p, Permission.ARENA)) { // p.sendMessage(s); // } // } // } // // } // Path: UltimateSurvivalGames/src/me/maker56/survivalgames/UpdateCheck.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Level; import me.maker56.survivalgames.listener.UpdateListener; import org.bukkit.plugin.Plugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(UpdateCheck.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } return false; } } private class UpdateRunnable implements Runnable { @Override public void run() { if (UpdateCheck.this.url != null) { // Obtain the results of the project's file feed if (UpdateCheck.this.read()) { if(!SurvivalGames.version.equals(UpdateCheck.this.versionName)) {
UpdateListener.update(UpdateCheck.this.versionName);
maker56/UltimateSurvivalGames
UltimateSurvivalGames/src/me/maker56/survivalgames/listener/SelectionListener.java
// Path: UltimateSurvivalGames/src/me/maker56/survivalgames/commands/messages/MessageHandler.java // public class MessageHandler { // // private static HashMap<String, String> messages = new HashMap<>(); // private static List<String> withoutPrefix = new ArrayList<>(); // // public static void reload() { // messages.clear(); // for(String key : SurvivalGames.messages.getConfigurationSection("").getKeys(false)) { // messages.put(key, replaceColors(SurvivalGames.messages.getString(key))); // } // // withoutPrefix.add("prefix"); // withoutPrefix.add("stats-kills"); // withoutPrefix.add("stats-deaths"); // withoutPrefix.add("stats-kdr"); // withoutPrefix.add("stats-wins"); // withoutPrefix.add("stats-played"); // withoutPrefix.add("stats-points"); // withoutPrefix.add("stats-footer"); // // System.out.println("[SurvivalGames] " + messages.size() + " messages loaded!"); // } // // public static String getMessage(String name) { // if(messages.containsKey(name)) { // if(withoutPrefix.contains(name)) { // return messages.get(name); // } else { // return messages.get("prefix") + messages.get(name); // } // } else { // return "§cMessage not found!"; // } // } // // public static String replaceColors(String s) { // return ChatColor.translateAlternateColorCodes('&', s); // } // // } // // Path: UltimateSurvivalGames/src/me/maker56/survivalgames/reset/Selection.java // public class Selection { // // private Location min, max; // public int xMin, yMin, zMin, xMax, yMax, zMax; // // public Selection(Location min, Location max) { // setMinimumLocation(min); // setMaximumLocation(max); // } // // private void redefineLocations() { // if(min != null && max != null) { // xMin = Math.min(min.getBlockX(), max.getBlockX()); // yMin = Math.min(min.getBlockY(), max.getBlockY()); // zMin = Math.min(min.getBlockZ(), max.getBlockZ()); // // xMax = Math.max(min.getBlockX(), max.getBlockX()); // yMax = Math.max(min.getBlockY(), max.getBlockY()); // zMax = Math.max(min.getBlockZ(), max.getBlockZ()); // } // } // // public void setMinimumLocation(Location min) { // Util.debug("set selection min location: " + Util.serializeLocation(min, false)); // this.min = min; // redefineLocations(); // } // // public void setMaximumLocation(Location max) { // Util.debug("set selection max location: " + Util.serializeLocation(max, false)); // this.max = max; // redefineLocations(); // } // // public Location getMinimumLocation() { // return min; // } // // public Location getMaximumLocation() { // return max; // } // // public int getLength() { // return xMax - xMin + 1; // } // // public int getWidth() { // return zMax - zMin + 1; // } // // public int getHeight() { // return yMax - yMin + 1; // } // // @Deprecated // public List<Location> getSelectedLocations() { // ArrayList<Location> al = new ArrayList<>(); // World world = min.getWorld(); // // for(int x = xMin; x <= xMax; x++) { // for(int y = yMin; y <= yMax; y++) { // for(int z = zMin; z <= zMax; z++) { // al.add(new Location(world, x, y, z)); // } // } // } // return al; // } // // public boolean contains(Location loc) { // return(loc.getBlockX() >= xMin && loc.getBlockX() <= xMax && loc.getBlockY() >= yMin && loc.getBlockY() <= yMax && loc.getBlockZ() >= zMin && loc.getBlockZ() <= zMax); // } // // public int getSize() { // return getLength() * getWidth() * getHeight(); // } // // public boolean isFullDefined() { // return min != null && max != null; // } // // }
import java.util.HashMap; import me.maker56.survivalgames.commands.messages.MessageHandler; import me.maker56.survivalgames.reset.Selection; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta;
package me.maker56.survivalgames.listener; public class SelectionListener implements Listener { public static HashMap<String, Selection> selections = new HashMap<>(); @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); ItemStack is = p.getItemInHand(); if(is == null) { return; } ItemMeta im = is.getItemMeta(); if(im == null) return; if(im.getDisplayName() == null) return; if(im.getDisplayName().equals("SurvivalGames Selection Tool")) { event.setCancelled(true);
// Path: UltimateSurvivalGames/src/me/maker56/survivalgames/commands/messages/MessageHandler.java // public class MessageHandler { // // private static HashMap<String, String> messages = new HashMap<>(); // private static List<String> withoutPrefix = new ArrayList<>(); // // public static void reload() { // messages.clear(); // for(String key : SurvivalGames.messages.getConfigurationSection("").getKeys(false)) { // messages.put(key, replaceColors(SurvivalGames.messages.getString(key))); // } // // withoutPrefix.add("prefix"); // withoutPrefix.add("stats-kills"); // withoutPrefix.add("stats-deaths"); // withoutPrefix.add("stats-kdr"); // withoutPrefix.add("stats-wins"); // withoutPrefix.add("stats-played"); // withoutPrefix.add("stats-points"); // withoutPrefix.add("stats-footer"); // // System.out.println("[SurvivalGames] " + messages.size() + " messages loaded!"); // } // // public static String getMessage(String name) { // if(messages.containsKey(name)) { // if(withoutPrefix.contains(name)) { // return messages.get(name); // } else { // return messages.get("prefix") + messages.get(name); // } // } else { // return "§cMessage not found!"; // } // } // // public static String replaceColors(String s) { // return ChatColor.translateAlternateColorCodes('&', s); // } // // } // // Path: UltimateSurvivalGames/src/me/maker56/survivalgames/reset/Selection.java // public class Selection { // // private Location min, max; // public int xMin, yMin, zMin, xMax, yMax, zMax; // // public Selection(Location min, Location max) { // setMinimumLocation(min); // setMaximumLocation(max); // } // // private void redefineLocations() { // if(min != null && max != null) { // xMin = Math.min(min.getBlockX(), max.getBlockX()); // yMin = Math.min(min.getBlockY(), max.getBlockY()); // zMin = Math.min(min.getBlockZ(), max.getBlockZ()); // // xMax = Math.max(min.getBlockX(), max.getBlockX()); // yMax = Math.max(min.getBlockY(), max.getBlockY()); // zMax = Math.max(min.getBlockZ(), max.getBlockZ()); // } // } // // public void setMinimumLocation(Location min) { // Util.debug("set selection min location: " + Util.serializeLocation(min, false)); // this.min = min; // redefineLocations(); // } // // public void setMaximumLocation(Location max) { // Util.debug("set selection max location: " + Util.serializeLocation(max, false)); // this.max = max; // redefineLocations(); // } // // public Location getMinimumLocation() { // return min; // } // // public Location getMaximumLocation() { // return max; // } // // public int getLength() { // return xMax - xMin + 1; // } // // public int getWidth() { // return zMax - zMin + 1; // } // // public int getHeight() { // return yMax - yMin + 1; // } // // @Deprecated // public List<Location> getSelectedLocations() { // ArrayList<Location> al = new ArrayList<>(); // World world = min.getWorld(); // // for(int x = xMin; x <= xMax; x++) { // for(int y = yMin; y <= yMax; y++) { // for(int z = zMin; z <= zMax; z++) { // al.add(new Location(world, x, y, z)); // } // } // } // return al; // } // // public boolean contains(Location loc) { // return(loc.getBlockX() >= xMin && loc.getBlockX() <= xMax && loc.getBlockY() >= yMin && loc.getBlockY() <= yMax && loc.getBlockZ() >= zMin && loc.getBlockZ() <= zMax); // } // // public int getSize() { // return getLength() * getWidth() * getHeight(); // } // // public boolean isFullDefined() { // return min != null && max != null; // } // // } // Path: UltimateSurvivalGames/src/me/maker56/survivalgames/listener/SelectionListener.java import java.util.HashMap; import me.maker56.survivalgames.commands.messages.MessageHandler; import me.maker56.survivalgames.reset.Selection; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; package me.maker56.survivalgames.listener; public class SelectionListener implements Listener { public static HashMap<String, Selection> selections = new HashMap<>(); @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); ItemStack is = p.getItemInHand(); if(is == null) { return; } ItemMeta im = is.getItemMeta(); if(im == null) return; if(im.getDisplayName() == null) return; if(im.getDisplayName().equals("SurvivalGames Selection Tool")) { event.setCancelled(true);
String message = MessageHandler.getMessage("prefix");
maker56/UltimateSurvivalGames
UltimateSurvivalGames/src/me/maker56/survivalgames/chat/Helper.java
// Path: UltimateSurvivalGames/src/me/maker56/survivalgames/commands/messages/MessageHandler.java // public class MessageHandler { // // private static HashMap<String, String> messages = new HashMap<>(); // private static List<String> withoutPrefix = new ArrayList<>(); // // public static void reload() { // messages.clear(); // for(String key : SurvivalGames.messages.getConfigurationSection("").getKeys(false)) { // messages.put(key, replaceColors(SurvivalGames.messages.getString(key))); // } // // withoutPrefix.add("prefix"); // withoutPrefix.add("stats-kills"); // withoutPrefix.add("stats-deaths"); // withoutPrefix.add("stats-kdr"); // withoutPrefix.add("stats-wins"); // withoutPrefix.add("stats-played"); // withoutPrefix.add("stats-points"); // withoutPrefix.add("stats-footer"); // // System.out.println("[SurvivalGames] " + messages.size() + " messages loaded!"); // } // // public static String getMessage(String name) { // if(messages.containsKey(name)) { // if(withoutPrefix.contains(name)) { // return messages.get(name); // } else { // return messages.get("prefix") + messages.get(name); // } // } else { // return "§cMessage not found!"; // } // } // // public static String replaceColors(String s) { // return ChatColor.translateAlternateColorCodes('&', s); // } // // }
import java.util.ArrayList; import java.util.List; import me.maker56.survivalgames.commands.messages.MessageHandler; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent.Action; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import org.bukkit.entity.Player;
package me.maker56.survivalgames.chat; public class Helper { public static void showLobbyHelpsite(Player p) {
// Path: UltimateSurvivalGames/src/me/maker56/survivalgames/commands/messages/MessageHandler.java // public class MessageHandler { // // private static HashMap<String, String> messages = new HashMap<>(); // private static List<String> withoutPrefix = new ArrayList<>(); // // public static void reload() { // messages.clear(); // for(String key : SurvivalGames.messages.getConfigurationSection("").getKeys(false)) { // messages.put(key, replaceColors(SurvivalGames.messages.getString(key))); // } // // withoutPrefix.add("prefix"); // withoutPrefix.add("stats-kills"); // withoutPrefix.add("stats-deaths"); // withoutPrefix.add("stats-kdr"); // withoutPrefix.add("stats-wins"); // withoutPrefix.add("stats-played"); // withoutPrefix.add("stats-points"); // withoutPrefix.add("stats-footer"); // // System.out.println("[SurvivalGames] " + messages.size() + " messages loaded!"); // } // // public static String getMessage(String name) { // if(messages.containsKey(name)) { // if(withoutPrefix.contains(name)) { // return messages.get(name); // } else { // return messages.get("prefix") + messages.get(name); // } // } else { // return "§cMessage not found!"; // } // } // // public static String replaceColors(String s) { // return ChatColor.translateAlternateColorCodes('&', s); // } // // } // Path: UltimateSurvivalGames/src/me/maker56/survivalgames/chat/Helper.java import java.util.ArrayList; import java.util.List; import me.maker56.survivalgames.commands.messages.MessageHandler; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent.Action; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import org.bukkit.entity.Player; package me.maker56.survivalgames.chat; public class Helper { public static void showLobbyHelpsite(Player p) {
p.sendMessage(MessageHandler.getMessage("prefix") + "Lobby Management §7§m---§r §6Helpsite");
SecUSo/privacy-friendly-memo-game
app/src/test/java/org/secuso/privacyfriendlymemory/MemoGameDeckTest.java
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/model/MemoGameCard.java // public class MemoGameCard { // // private final int matchingId; // private final int resImageID; // private final Uri imageUri; // // public MemoGameCard(int matchingId, @DrawableRes int resImageID, Uri imageUri){ // this.matchingId = matchingId; // this.resImageID = resImageID; // this.imageUri = imageUri; // } // // // public int getMatchingId() { // return matchingId; // } // // // public int getResImageID() { // return resImageID; // } // // public Uri getImageUri(){ return imageUri; } // } // // Path: app/src/main/java/org/secuso/privacyfriendlymemory/model/MemoGameDeck.java // public class MemoGameDeck { // // // mapping between position(k), card(v) // private Map<Integer, MemoGameCard> deck = new HashMap<>(); // // public MemoGameDeck(List<Integer> imagesResIds){ // // generate for each image two cards with the same matching id // int matchingId = 1; // List<MemoGameCard> cards = new LinkedList<>(); // for(Integer imageResId : imagesResIds){ // for(int i = 0; i<=1;i++) { // MemoGameCard card = new MemoGameCard(matchingId, imageResId, null); // cards.add(card); // } // matchingId++; // } // // // generate random position for cards and map between position and card // Collections.shuffle(cards); // // Integer position = 0; // for(MemoGameCard card : cards){ // deck.put(position, card); // position++; // } // } // // public MemoGameDeck(Set<Uri> imageUris){ // // generate for each image two cards with the same matching id // int matchingId = 1; // List<MemoGameCard> cards = new LinkedList<>(); // for(Uri imageUri : imageUris){ // for(int i = 0; i<=1;i++) { // MemoGameCard card = new MemoGameCard(matchingId, 0, imageUri); // cards.add(card); // } // matchingId++; // } // // // generate random position for cards and map between position and card // Collections.shuffle(cards); // // Integer position = 0; // for(MemoGameCard card : cards){ // deck.put(position, card); // position++; // } // } // // public Map<Integer, MemoGameCard> getDeck(){ // return deck; // } // // // }
import org.junit.Before; import org.junit.Test; import org.secuso.privacyfriendlymemory.model.MemoGameCard; import org.secuso.privacyfriendlymemory.model.MemoGameDeck; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals;
package org.secuso.privacyfriendlymemory; /** * Created by Hannes on 21.05.2016. */ public class MemoGameDeckTest { private Map<Integer, MemoGameCard> cardMapping = new HashMap<>(); private final static List<Integer> IMAGE_RES_IDS = new LinkedList<>(); static{ IMAGE_RES_IDS.add(1); IMAGE_RES_IDS.add(2); IMAGE_RES_IDS.add(3); } @Before public void setupMapping(){
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/model/MemoGameCard.java // public class MemoGameCard { // // private final int matchingId; // private final int resImageID; // private final Uri imageUri; // // public MemoGameCard(int matchingId, @DrawableRes int resImageID, Uri imageUri){ // this.matchingId = matchingId; // this.resImageID = resImageID; // this.imageUri = imageUri; // } // // // public int getMatchingId() { // return matchingId; // } // // // public int getResImageID() { // return resImageID; // } // // public Uri getImageUri(){ return imageUri; } // } // // Path: app/src/main/java/org/secuso/privacyfriendlymemory/model/MemoGameDeck.java // public class MemoGameDeck { // // // mapping between position(k), card(v) // private Map<Integer, MemoGameCard> deck = new HashMap<>(); // // public MemoGameDeck(List<Integer> imagesResIds){ // // generate for each image two cards with the same matching id // int matchingId = 1; // List<MemoGameCard> cards = new LinkedList<>(); // for(Integer imageResId : imagesResIds){ // for(int i = 0; i<=1;i++) { // MemoGameCard card = new MemoGameCard(matchingId, imageResId, null); // cards.add(card); // } // matchingId++; // } // // // generate random position for cards and map between position and card // Collections.shuffle(cards); // // Integer position = 0; // for(MemoGameCard card : cards){ // deck.put(position, card); // position++; // } // } // // public MemoGameDeck(Set<Uri> imageUris){ // // generate for each image two cards with the same matching id // int matchingId = 1; // List<MemoGameCard> cards = new LinkedList<>(); // for(Uri imageUri : imageUris){ // for(int i = 0; i<=1;i++) { // MemoGameCard card = new MemoGameCard(matchingId, 0, imageUri); // cards.add(card); // } // matchingId++; // } // // // generate random position for cards and map between position and card // Collections.shuffle(cards); // // Integer position = 0; // for(MemoGameCard card : cards){ // deck.put(position, card); // position++; // } // } // // public Map<Integer, MemoGameCard> getDeck(){ // return deck; // } // // // } // Path: app/src/test/java/org/secuso/privacyfriendlymemory/MemoGameDeckTest.java import org.junit.Before; import org.junit.Test; import org.secuso.privacyfriendlymemory.model.MemoGameCard; import org.secuso.privacyfriendlymemory.model.MemoGameDeck; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; package org.secuso.privacyfriendlymemory; /** * Created by Hannes on 21.05.2016. */ public class MemoGameDeckTest { private Map<Integer, MemoGameCard> cardMapping = new HashMap<>(); private final static List<Integer> IMAGE_RES_IDS = new LinkedList<>(); static{ IMAGE_RES_IDS.add(1); IMAGE_RES_IDS.add(2); IMAGE_RES_IDS.add(3); } @Before public void setupMapping(){
MemoGameDeck deck = new MemoGameDeck(IMAGE_RES_IDS);
SecUSo/privacy-friendly-memo-game
app/src/main/java/org/secuso/privacyfriendlymemory/model/MemoGame.java
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/common/MemoGamePlayerFactory.java // public class MemoGamePlayerFactory { // // public static List<MemoGamePlayer> createPlayers(MemoGameMode memoryMode){ // List<MemoGamePlayer> players = new LinkedList<>(); // int playerCount = memoryMode.getPlayerCount(); // MemoGamePlayer player; // for(int i = 1; i <= playerCount; i++){ // player = new MemoGamePlayer(String.valueOf(i)); // players.add(player); // } // return players; // } // }
import android.net.Uri; import org.secuso.privacyfriendlymemory.common.MemoGamePlayerFactory; import org.secuso.privacyfriendlymemory.ui.R; import java.util.LinkedList; import java.util.List; import java.util.Map;
package org.secuso.privacyfriendlymemory.model; /** * Created by Hannes on 20.05.2016. */ public class MemoGame { private final MemoGameDifficulty memoryDifficulty; private final MemoGameMode memoryMode; private final CardDesign cardDesign; private final Map<Integer, MemoGameCard> deck; private final int notFoundImageResID; private Integer[] falseSelectedCards = new Integer[2]; private boolean falseSelected = false; private MemoGamePlayer currentPlayer; private MemoGameCard selectedCard = null; private MemoGameTimer timer; private MemoGameCard[] temporarySelectedCards = new MemoGameCard[2]; private List<MemoGameCard> foundCards = new LinkedList<>(); private List<MemoGamePlayer> players = new LinkedList<>(); private int selectedCardsCount = 0; public MemoGame(CardDesign cardDesign, MemoGameMode memoryMode, MemoGameDifficulty memoryDifficulty) { this.memoryDifficulty = memoryDifficulty; this.memoryMode = memoryMode; this.cardDesign = cardDesign; if(cardDesign == CardDesign.CUSTOM){ this.deck = new MemoGameDeck(MemoGameCustomImages.getUris(memoryDifficulty)).getDeck(); }else{ this.deck = new MemoGameDeck(MemoGameDefaultImages.getResIDs(cardDesign, memoryDifficulty, true)).getDeck(); } this.notFoundImageResID = MemoGameDefaultImages.getNotFoundImageResID();
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/common/MemoGamePlayerFactory.java // public class MemoGamePlayerFactory { // // public static List<MemoGamePlayer> createPlayers(MemoGameMode memoryMode){ // List<MemoGamePlayer> players = new LinkedList<>(); // int playerCount = memoryMode.getPlayerCount(); // MemoGamePlayer player; // for(int i = 1; i <= playerCount; i++){ // player = new MemoGamePlayer(String.valueOf(i)); // players.add(player); // } // return players; // } // } // Path: app/src/main/java/org/secuso/privacyfriendlymemory/model/MemoGame.java import android.net.Uri; import org.secuso.privacyfriendlymemory.common.MemoGamePlayerFactory; import org.secuso.privacyfriendlymemory.ui.R; import java.util.LinkedList; import java.util.List; import java.util.Map; package org.secuso.privacyfriendlymemory.model; /** * Created by Hannes on 20.05.2016. */ public class MemoGame { private final MemoGameDifficulty memoryDifficulty; private final MemoGameMode memoryMode; private final CardDesign cardDesign; private final Map<Integer, MemoGameCard> deck; private final int notFoundImageResID; private Integer[] falseSelectedCards = new Integer[2]; private boolean falseSelected = false; private MemoGamePlayer currentPlayer; private MemoGameCard selectedCard = null; private MemoGameTimer timer; private MemoGameCard[] temporarySelectedCards = new MemoGameCard[2]; private List<MemoGameCard> foundCards = new LinkedList<>(); private List<MemoGamePlayer> players = new LinkedList<>(); private int selectedCardsCount = 0; public MemoGame(CardDesign cardDesign, MemoGameMode memoryMode, MemoGameDifficulty memoryDifficulty) { this.memoryDifficulty = memoryDifficulty; this.memoryMode = memoryMode; this.cardDesign = cardDesign; if(cardDesign == CardDesign.CUSTOM){ this.deck = new MemoGameDeck(MemoGameCustomImages.getUris(memoryDifficulty)).getDeck(); }else{ this.deck = new MemoGameDeck(MemoGameDefaultImages.getResIDs(cardDesign, memoryDifficulty, true)).getDeck(); } this.notFoundImageResID = MemoGameDefaultImages.getNotFoundImageResID();
this.players = MemoGamePlayerFactory.createPlayers(memoryMode);
SecUSo/privacy-friendly-memo-game
app/src/main/java/org/secuso/privacyfriendlymemory/ui/navigation/HighscoreActivity.java
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/Constants.java // public final class Constants { // // private Constants(){} // this class should not be initialized // // // Preferences Constants // public final static String FIRST_APP_START = "FIRST_APP_START"; // public final static String SELECTED_CARD_DESIGN = "SELECTED_CARD_DESIGN"; // public final static String CUSTOM_CARDS_URIS = "CUSTOM_CARDS_URIS"; // // // Preferences Constants Highscore // public final static String HIGHSCORE_EASY = "HIGHSCORE_EASY"; // public final static String HIGHSCORE_EASY_TRIES = "HIGHSCORE_EASY_TRIES"; // public final static String HIGHSCORE_EASY_TIME = "HIGHSCORE_EASY_TIME"; // // public final static String HIGHSCORE_MODERATE = "HIGHSCORE_MODERATE"; // public final static String HIGHSCORE_MODERATE_TRIES = "HIGHSCORE_MODERATE_TRIES"; // public final static String HIGHSCORE_MODERATE_TIME = "HIGHSCORE_MODERATE_TIME"; // // public final static String HIGHSCORE_HARD = "HIGHSCORE_HARD"; // public final static String HIGHSCORE_HARD_TRIES = "HIGHSCORE_HARD_TRIES"; // public final static String HIGHSCORE_HARD_TIME = "HIGHSCORE_HARD_TIME"; // // // // Preferences Constants Statistics // public final static String STATISTICS_DECK_ONE = "STATISTICS_DECK_ONE"; // public final static String STATISTICS_DECK_TWO = "STATISTICS_DECK_TWO"; // // // Intent Extra Constants // public final static String GAME_DIFFICULTY = "GAME_DIFFICULTY"; // public final static String GAME_MODE = "GAME_MODE"; // public final static String CARD_DESIGN = "CARD_DESIGN"; // // // } // // Path: app/src/main/java/org/secuso/privacyfriendlymemory/ui/AppCompatPreferenceActivity.java // public abstract class AppCompatPreferenceActivity extends PreferenceActivity { // // private AppCompatDelegate mDelegate; // // @Override // protected void onCreate(Bundle savedInstanceState) { // getDelegate().installViewFactory(); // getDelegate().onCreate(savedInstanceState); // super.onCreate(savedInstanceState); // } // // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // getDelegate().onPostCreate(savedInstanceState); // } // // public ActionBar getSupportActionBar() { // return getDelegate().getSupportActionBar(); // } // // public void setSupportActionBar(@Nullable Toolbar toolbar) { // getDelegate().setSupportActionBar(toolbar); // } // // @Override // public MenuInflater getMenuInflater() { // return getDelegate().getMenuInflater(); // } // // @Override // public void setContentView(@LayoutRes int layoutResID) { // getDelegate().setContentView(layoutResID); // } // // @Override // public void setContentView(View view) { // getDelegate().setContentView(view); // } // // @Override // public void setContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().setContentView(view, params); // } // // @Override // public void addContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().addContentView(view, params); // } // // @Override // protected void onPostResume() { // super.onPostResume(); // getDelegate().onPostResume(); // } // // @Override // protected void onTitleChanged(CharSequence title, int color) { // super.onTitleChanged(title, color); // getDelegate().setTitle(title); // } // // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // getDelegate().onConfigurationChanged(newConfig); // } // // @Override // protected void onStop() { // super.onStop(); // getDelegate().onStop(); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // getDelegate().onDestroy(); // } // // public void invalidateOptionsMenu() { // getDelegate().invalidateOptionsMenu(); // } // // private AppCompatDelegate getDelegate() { // if (mDelegate == null) { // mDelegate = AppCompatDelegate.create(this, null); // } // return mDelegate; // } // }
import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import org.secuso.privacyfriendlymemory.Constants; import org.secuso.privacyfriendlymemory.ui.AppCompatPreferenceActivity; import org.secuso.privacyfriendlymemory.ui.R; import java.util.List;
package org.secuso.privacyfriendlymemory.ui.navigation; public class HighscoreActivity extends AppCompatPreferenceActivity { private FragmentRefreshListener fragmentRefreshListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); } public FragmentRefreshListener getFragmentRefreshListener() { return fragmentRefreshListener; } public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListener = fragmentRefreshListener; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_highscore, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch(id){ case android.R.id.home: finish(); return true; case R.id.menu_highscore_reset: SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // reset score, tries and time for each mode
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/Constants.java // public final class Constants { // // private Constants(){} // this class should not be initialized // // // Preferences Constants // public final static String FIRST_APP_START = "FIRST_APP_START"; // public final static String SELECTED_CARD_DESIGN = "SELECTED_CARD_DESIGN"; // public final static String CUSTOM_CARDS_URIS = "CUSTOM_CARDS_URIS"; // // // Preferences Constants Highscore // public final static String HIGHSCORE_EASY = "HIGHSCORE_EASY"; // public final static String HIGHSCORE_EASY_TRIES = "HIGHSCORE_EASY_TRIES"; // public final static String HIGHSCORE_EASY_TIME = "HIGHSCORE_EASY_TIME"; // // public final static String HIGHSCORE_MODERATE = "HIGHSCORE_MODERATE"; // public final static String HIGHSCORE_MODERATE_TRIES = "HIGHSCORE_MODERATE_TRIES"; // public final static String HIGHSCORE_MODERATE_TIME = "HIGHSCORE_MODERATE_TIME"; // // public final static String HIGHSCORE_HARD = "HIGHSCORE_HARD"; // public final static String HIGHSCORE_HARD_TRIES = "HIGHSCORE_HARD_TRIES"; // public final static String HIGHSCORE_HARD_TIME = "HIGHSCORE_HARD_TIME"; // // // // Preferences Constants Statistics // public final static String STATISTICS_DECK_ONE = "STATISTICS_DECK_ONE"; // public final static String STATISTICS_DECK_TWO = "STATISTICS_DECK_TWO"; // // // Intent Extra Constants // public final static String GAME_DIFFICULTY = "GAME_DIFFICULTY"; // public final static String GAME_MODE = "GAME_MODE"; // public final static String CARD_DESIGN = "CARD_DESIGN"; // // // } // // Path: app/src/main/java/org/secuso/privacyfriendlymemory/ui/AppCompatPreferenceActivity.java // public abstract class AppCompatPreferenceActivity extends PreferenceActivity { // // private AppCompatDelegate mDelegate; // // @Override // protected void onCreate(Bundle savedInstanceState) { // getDelegate().installViewFactory(); // getDelegate().onCreate(savedInstanceState); // super.onCreate(savedInstanceState); // } // // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // getDelegate().onPostCreate(savedInstanceState); // } // // public ActionBar getSupportActionBar() { // return getDelegate().getSupportActionBar(); // } // // public void setSupportActionBar(@Nullable Toolbar toolbar) { // getDelegate().setSupportActionBar(toolbar); // } // // @Override // public MenuInflater getMenuInflater() { // return getDelegate().getMenuInflater(); // } // // @Override // public void setContentView(@LayoutRes int layoutResID) { // getDelegate().setContentView(layoutResID); // } // // @Override // public void setContentView(View view) { // getDelegate().setContentView(view); // } // // @Override // public void setContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().setContentView(view, params); // } // // @Override // public void addContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().addContentView(view, params); // } // // @Override // protected void onPostResume() { // super.onPostResume(); // getDelegate().onPostResume(); // } // // @Override // protected void onTitleChanged(CharSequence title, int color) { // super.onTitleChanged(title, color); // getDelegate().setTitle(title); // } // // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // getDelegate().onConfigurationChanged(newConfig); // } // // @Override // protected void onStop() { // super.onStop(); // getDelegate().onStop(); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // getDelegate().onDestroy(); // } // // public void invalidateOptionsMenu() { // getDelegate().invalidateOptionsMenu(); // } // // private AppCompatDelegate getDelegate() { // if (mDelegate == null) { // mDelegate = AppCompatDelegate.create(this, null); // } // return mDelegate; // } // } // Path: app/src/main/java/org/secuso/privacyfriendlymemory/ui/navigation/HighscoreActivity.java import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import org.secuso.privacyfriendlymemory.Constants; import org.secuso.privacyfriendlymemory.ui.AppCompatPreferenceActivity; import org.secuso.privacyfriendlymemory.ui.R; import java.util.List; package org.secuso.privacyfriendlymemory.ui.navigation; public class HighscoreActivity extends AppCompatPreferenceActivity { private FragmentRefreshListener fragmentRefreshListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); } public FragmentRefreshListener getFragmentRefreshListener() { return fragmentRefreshListener; } public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) { this.fragmentRefreshListener = fragmentRefreshListener; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_highscore, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch(id){ case android.R.id.home: finish(); return true; case R.id.menu_highscore_reset: SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // reset score, tries and time for each mode
preferences.edit().putInt(Constants.HIGHSCORE_EASY, 0).commit();
SecUSo/privacy-friendly-memo-game
app/src/main/java/org/secuso/privacyfriendlymemory/ui/MemoImageAdapter.java
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/common/MemoGameLayoutProvider.java // public class MemoGameLayoutProvider { // // private final static int MARGIN_LEFT = 35; // in pixel // private final static int MARGIN_RIGHT = 35; // in pixel // private final Context context; // private final MemoGame memory; // private final MemoGameDifficulty memoryDifficulty; // private static Map<MemoGameDifficulty, Integer> columnCountMapping = new HashMap<>(); // // static { // columnCountMapping.put(MemoGameDifficulty.Easy, 4); // columnCountMapping.put(MemoGameDifficulty.Moderate, 6); // columnCountMapping.put(MemoGameDifficulty.Hard, 8); // } // // public MemoGameLayoutProvider(Context context, MemoGame memory) { // this.context = context; // this.memory = memory; // this.memoryDifficulty = memory.getDifficulty(); // } // // public int getColumnCount() { // return columnCountMapping.get(memoryDifficulty); // } // // public int getDeckSize() { // return memoryDifficulty.getDeckSize(); // } // // public int getImageResID(int position) { // return memory.getImageResID(position); // } // // public Uri getImageUri(int position) { // return memory.getImageUri(position); // } // // public int getCardSizePixel() { // // calculate the card size in pixel based on the screen width // // [remember: card = square, so width=height] // int orientation=context.getResources().getConfiguration().orientation; // if(orientation== Configuration.ORIENTATION_PORTRAIT){ // int displayWidth = context.getResources().getDisplayMetrics().widthPixels; // int cardSize = (displayWidth - getMarginLeft() - getMarginRight()) / getColumnCount(); // return cardSize; // } // else{ // int displayHeight = context.getResources().getDisplayMetrics().heightPixels; // int displayHeightWithoutStats = (int)(displayHeight*(47.5f/100.f)); // int cardSize = displayHeightWithoutStats/getColumnCount(); // return cardSize; // } // } // // public int getMargin() { // int displayHeight = context.getResources().getDisplayMetrics().heightPixels; // int cardsHeight = getColumnCount() * getCardSizePixel(); // int heightLeft = displayHeight - cardsHeight; // return heightLeft / 2; // } // // // public int getMarginLeft() { // int orientation=context.getResources().getConfiguration().orientation; // if(orientation== Configuration.ORIENTATION_PORTRAIT){ // return MARGIN_LEFT; // }else{ // return calculateLandscapeSideMargin(); // } // } // // public int getMarginRight() { // int orientation=context.getResources().getConfiguration().orientation; // if(orientation== Configuration.ORIENTATION_PORTRAIT){ // return MARGIN_RIGHT; // }else{ // return calculateLandscapeSideMargin(); // } // } // // private int calculateLandscapeSideMargin(){ // int cardSpaceWidth = getColumnCount()*getCardSizePixel(); // int displayWidth = context.getResources().getDisplayMetrics().widthPixels; // int spaceLeft = displayWidth-cardSpaceWidth; // return spaceLeft/2; // } // // public boolean isCustomDeck() { // return memory.isCustomDesign(); // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import org.secuso.privacyfriendlymemory.common.MemoGameLayoutProvider; import java.io.IOException; import java.util.HashMap; import java.util.Map;
package org.secuso.privacyfriendlymemory.ui; /** * Created by Hannes on 21.05.2016. */ public class MemoImageAdapter extends BaseAdapter { private final Context context;
// Path: app/src/main/java/org/secuso/privacyfriendlymemory/common/MemoGameLayoutProvider.java // public class MemoGameLayoutProvider { // // private final static int MARGIN_LEFT = 35; // in pixel // private final static int MARGIN_RIGHT = 35; // in pixel // private final Context context; // private final MemoGame memory; // private final MemoGameDifficulty memoryDifficulty; // private static Map<MemoGameDifficulty, Integer> columnCountMapping = new HashMap<>(); // // static { // columnCountMapping.put(MemoGameDifficulty.Easy, 4); // columnCountMapping.put(MemoGameDifficulty.Moderate, 6); // columnCountMapping.put(MemoGameDifficulty.Hard, 8); // } // // public MemoGameLayoutProvider(Context context, MemoGame memory) { // this.context = context; // this.memory = memory; // this.memoryDifficulty = memory.getDifficulty(); // } // // public int getColumnCount() { // return columnCountMapping.get(memoryDifficulty); // } // // public int getDeckSize() { // return memoryDifficulty.getDeckSize(); // } // // public int getImageResID(int position) { // return memory.getImageResID(position); // } // // public Uri getImageUri(int position) { // return memory.getImageUri(position); // } // // public int getCardSizePixel() { // // calculate the card size in pixel based on the screen width // // [remember: card = square, so width=height] // int orientation=context.getResources().getConfiguration().orientation; // if(orientation== Configuration.ORIENTATION_PORTRAIT){ // int displayWidth = context.getResources().getDisplayMetrics().widthPixels; // int cardSize = (displayWidth - getMarginLeft() - getMarginRight()) / getColumnCount(); // return cardSize; // } // else{ // int displayHeight = context.getResources().getDisplayMetrics().heightPixels; // int displayHeightWithoutStats = (int)(displayHeight*(47.5f/100.f)); // int cardSize = displayHeightWithoutStats/getColumnCount(); // return cardSize; // } // } // // public int getMargin() { // int displayHeight = context.getResources().getDisplayMetrics().heightPixels; // int cardsHeight = getColumnCount() * getCardSizePixel(); // int heightLeft = displayHeight - cardsHeight; // return heightLeft / 2; // } // // // public int getMarginLeft() { // int orientation=context.getResources().getConfiguration().orientation; // if(orientation== Configuration.ORIENTATION_PORTRAIT){ // return MARGIN_LEFT; // }else{ // return calculateLandscapeSideMargin(); // } // } // // public int getMarginRight() { // int orientation=context.getResources().getConfiguration().orientation; // if(orientation== Configuration.ORIENTATION_PORTRAIT){ // return MARGIN_RIGHT; // }else{ // return calculateLandscapeSideMargin(); // } // } // // private int calculateLandscapeSideMargin(){ // int cardSpaceWidth = getColumnCount()*getCardSizePixel(); // int displayWidth = context.getResources().getDisplayMetrics().widthPixels; // int spaceLeft = displayWidth-cardSpaceWidth; // return spaceLeft/2; // } // // public boolean isCustomDeck() { // return memory.isCustomDesign(); // } // // } // Path: app/src/main/java/org/secuso/privacyfriendlymemory/ui/MemoImageAdapter.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import org.secuso.privacyfriendlymemory.common.MemoGameLayoutProvider; import java.io.IOException; import java.util.HashMap; import java.util.Map; package org.secuso.privacyfriendlymemory.ui; /** * Created by Hannes on 21.05.2016. */ public class MemoImageAdapter extends BaseAdapter { private final Context context;
private final MemoGameLayoutProvider layoutProvider;
release-engineering/buildmetadata-maven-plugin
src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/BuildReportMojo.java
// Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/util/FilePathNormalizer.java // public final class FilePathNormalizer implements Normalizer // { // // ********************************* Fields ********************************* // // // --- constants ------------------------------------------------------------ // // // --- members -------------------------------------------------------------- // // /** // * The path to the root folder. Used to trim references to project files. // */ // private final String baseDir; // // /** // * The precalculated length of the {@link #baseDir} string. // */ // private final int prefixLength; // // // ****************************** Initializer ******************************* // // // ****************************** Constructors ****************************** // // /** // * Default constructor. // * // * @param baseDir the path to the root folder. // * @throws NullPointerException if {@code baseDir} is <code>null</code>. // */ // public FilePathNormalizer(final String baseDir) throws NullPointerException // { // this.baseDir = baseDir.trim(); // this.prefixLength = baseDir.length(); // } // // // ****************************** Inner Classes ***************************** // // // ********************************* Methods ******************************** // // // --- init ----------------------------------------------------------------- // // // --- get&set -------------------------------------------------------------- // // /** // * Returns the path to the root folder. Used to trim references to project // * files. // * // * @return the path to the root folder. // */ // public String getBaseDir() // { // return baseDir; // } // // // --- business ------------------------------------------------------------- // // /** // * {@inheritDoc} // * <p> // * Removed the prefix path defined by the {@code baseDir} passed in via the // * {@link #FilePathNormalizer(String)} constructor. // * </p> // */ // public String normalize(final String input) // { // final String prefixed = // input.startsWith(baseDir) ? input.substring(prefixLength) : input; // final String norm = prefixed.replace('\\', '/'); // if (norm.charAt(0) == '/' && norm.length() > 1) // { // return norm.substring(1); // } // return norm; // } // // // --- object basics -------------------------------------------------------- // // }
import java.io.File; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.reporting.MavenReportException; import com.redhat.rcm.maven.plugin.buildmetadata.common.Property; import com.redhat.rcm.maven.plugin.buildmetadata.util.FilePathNormalizer;
"build.properties"); this.propertyOutputFileMapping = mapper.initOutputFileMapping(); if (createPropertiesReport) { propertiesOutputFile = mapper.getPropertiesOutputFile(activatePropertyOutputFileMapping, propertiesOutputFile); } else { propertiesOutputFile = new File(project.getBuild().getDirectory(), "build.properties"); } } } /** * {@inheritDoc} * * @see org.apache.maven.reporting.AbstractMavenReport#executeReport(java.util.Locale) */ @Override protected void executeReport(final Locale locale) throws MavenReportException { super.executeReport(locale); final Sink sink = getSink(); final ResourceBundle messages = getBundle(locale); final String baseDir = project.getBasedir().getAbsolutePath(); final BuildReportRenderer renderer =
// Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/util/FilePathNormalizer.java // public final class FilePathNormalizer implements Normalizer // { // // ********************************* Fields ********************************* // // // --- constants ------------------------------------------------------------ // // // --- members -------------------------------------------------------------- // // /** // * The path to the root folder. Used to trim references to project files. // */ // private final String baseDir; // // /** // * The precalculated length of the {@link #baseDir} string. // */ // private final int prefixLength; // // // ****************************** Initializer ******************************* // // // ****************************** Constructors ****************************** // // /** // * Default constructor. // * // * @param baseDir the path to the root folder. // * @throws NullPointerException if {@code baseDir} is <code>null</code>. // */ // public FilePathNormalizer(final String baseDir) throws NullPointerException // { // this.baseDir = baseDir.trim(); // this.prefixLength = baseDir.length(); // } // // // ****************************** Inner Classes ***************************** // // // ********************************* Methods ******************************** // // // --- init ----------------------------------------------------------------- // // // --- get&set -------------------------------------------------------------- // // /** // * Returns the path to the root folder. Used to trim references to project // * files. // * // * @return the path to the root folder. // */ // public String getBaseDir() // { // return baseDir; // } // // // --- business ------------------------------------------------------------- // // /** // * {@inheritDoc} // * <p> // * Removed the prefix path defined by the {@code baseDir} passed in via the // * {@link #FilePathNormalizer(String)} constructor. // * </p> // */ // public String normalize(final String input) // { // final String prefixed = // input.startsWith(baseDir) ? input.substring(prefixLength) : input; // final String norm = prefixed.replace('\\', '/'); // if (norm.charAt(0) == '/' && norm.length() > 1) // { // return norm.substring(1); // } // return norm; // } // // // --- object basics -------------------------------------------------------- // // } // Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/BuildReportMojo.java import java.io.File; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.reporting.MavenReportException; import com.redhat.rcm.maven.plugin.buildmetadata.common.Property; import com.redhat.rcm.maven.plugin.buildmetadata.util.FilePathNormalizer; "build.properties"); this.propertyOutputFileMapping = mapper.initOutputFileMapping(); if (createPropertiesReport) { propertiesOutputFile = mapper.getPropertiesOutputFile(activatePropertyOutputFileMapping, propertiesOutputFile); } else { propertiesOutputFile = new File(project.getBuild().getDirectory(), "build.properties"); } } } /** * {@inheritDoc} * * @see org.apache.maven.reporting.AbstractMavenReport#executeReport(java.util.Locale) */ @Override protected void executeReport(final Locale locale) throws MavenReportException { super.executeReport(locale); final Sink sink = getSink(); final ResourceBundle messages = getBundle(locale); final String baseDir = project.getBasedir().getAbsolutePath(); final BuildReportRenderer renderer =
new BuildReportRenderer(new FilePathNormalizer(baseDir), messages,
release-engineering/buildmetadata-maven-plugin
src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/io/AdditionalLocationsSupport.java
// Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/util/MojoFileUtils.java // public final class MojoFileUtils // { // // ********************************* Fields ********************************* // // // --- constants ------------------------------------------------------------ // // // --- members -------------------------------------------------------------- // // // ****************************** Initializer ******************************* // // // ****************************** Constructors ****************************** // // private MojoFileUtils() // { // } // // // ****************************** Inner Classes ***************************** // // // ********************************* Methods ******************************** // // // --- init ----------------------------------------------------------------- // // // --- get&set -------------------------------------------------------------- // // // --- business ------------------------------------------------------------- // // /** // * Ensures that the given directory exists. // * // * @param directory the directory to check. It is not checked, if this is a // * directory or a file. // * @throws MojoExecutionException if the directory does not exist and cannot // * be created. // */ // public static void ensureExists(final File directory) // throws MojoExecutionException // { // if (!directory.exists()) // { // final boolean created = directory.mkdirs(); // if (!created) // { // throw new MojoExecutionException("Cannot create output directory '" // + directory + "'."); // } // } // } // // // --- object basics -------------------------------------------------------- // // }
import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import com.redhat.rcm.maven.plugin.buildmetadata.util.MojoFileUtils;
"maven-source-plugin")); if (sourcesPlugin != null) { // TODO: Should we check if the plugin is to be run? return true; } return false; } private void addFileToSources(final File propertiesFile, final String targetLocation, final boolean attach) throws MojoExecutionException { final File testFile = new File(targetLocation); final File targetLocationDir; final File generatedSourcesMetaInfDir; if (testFile.isAbsolute()) { targetLocationDir = null; generatedSourcesMetaInfDir = testFile; } else { targetLocationDir = new File(project.getBuild().getDirectory(), targetLocation); generatedSourcesMetaInfDir = new File(targetLocationDir, "META-INF"); }
// Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/util/MojoFileUtils.java // public final class MojoFileUtils // { // // ********************************* Fields ********************************* // // // --- constants ------------------------------------------------------------ // // // --- members -------------------------------------------------------------- // // // ****************************** Initializer ******************************* // // // ****************************** Constructors ****************************** // // private MojoFileUtils() // { // } // // // ****************************** Inner Classes ***************************** // // // ********************************* Methods ******************************** // // // --- init ----------------------------------------------------------------- // // // --- get&set -------------------------------------------------------------- // // // --- business ------------------------------------------------------------- // // /** // * Ensures that the given directory exists. // * // * @param directory the directory to check. It is not checked, if this is a // * directory or a file. // * @throws MojoExecutionException if the directory does not exist and cannot // * be created. // */ // public static void ensureExists(final File directory) // throws MojoExecutionException // { // if (!directory.exists()) // { // final boolean created = directory.mkdirs(); // if (!created) // { // throw new MojoExecutionException("Cannot create output directory '" // + directory + "'."); // } // } // } // // // --- object basics -------------------------------------------------------- // // } // Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/io/AdditionalLocationsSupport.java import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import com.redhat.rcm.maven.plugin.buildmetadata.util.MojoFileUtils; "maven-source-plugin")); if (sourcesPlugin != null) { // TODO: Should we check if the plugin is to be run? return true; } return false; } private void addFileToSources(final File propertiesFile, final String targetLocation, final boolean attach) throws MojoExecutionException { final File testFile = new File(targetLocation); final File targetLocationDir; final File generatedSourcesMetaInfDir; if (testFile.isAbsolute()) { targetLocationDir = null; generatedSourcesMetaInfDir = testFile; } else { targetLocationDir = new File(project.getBuild().getDirectory(), targetLocation); generatedSourcesMetaInfDir = new File(targetLocationDir, "META-INF"); }
MojoFileUtils.ensureExists(generatedSourcesMetaInfDir);
release-engineering/buildmetadata-maven-plugin
src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/scm/maven/ScmConnectionInfo.java
// Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/scm/ScmException.java // public class ScmException extends RuntimeException // { // // ********************************* Fields ********************************* // // // --- constants ------------------------------------------------------------ // // /** // * The class version identifier. // * <p> // * The value of this constant is {@value}. // */ // private static final long serialVersionUID = 1L; // // // --- members -------------------------------------------------------------- // // // ****************************** Initializer ******************************* // // // ****************************** Constructors ****************************** // // /** // * Default Constructor. // * // * @param message the detail message (which is saved for later retrieval by // * the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <tt>null</tt> value is permitted, // * and indicates that the cause is nonexistent or unknown.) // * @see java.lang.RuntimeException#RuntimeException(java.lang.String, // * java.lang.Throwable) // */ // public ScmException(final String message, final Throwable cause) // { // super(message, cause); // } // // /** // * Convenience constructor providing no cause. // * // * @param message the detail message. The detail message is saved for later // * retrieval by the {@link #getMessage()} method. // * @see java.lang.RuntimeException#RuntimeException(java.lang.String) // */ // public ScmException(final String message) // { // super(message); // } // // /** // * Convenience constructor providing no message. // * // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <tt>null</tt> value is permitted, // * and indicates that the cause is nonexistent or unknown.) // * @see java.lang.RuntimeException#RuntimeException(java.lang.Throwable) // */ // public ScmException(final Throwable cause) // { // super(cause); // } // // // ****************************** Inner Classes ***************************** // // // ********************************* Methods ******************************** // // // --- init ----------------------------------------------------------------- // // // --- get&set -------------------------------------------------------------- // // // --- business ------------------------------------------------------------- // // // --- object basics -------------------------------------------------------- // // }
import java.io.Serializable; import org.apache.maven.scm.ScmVersion; import org.apache.maven.scm.manager.ScmManager; import org.apache.maven.scm.provider.ScmProviderRepository; import org.apache.maven.scm.provider.ScmProviderRepositoryWithHost; import org.apache.maven.scm.provider.svn.repository.SvnScmProviderRepository; import org.apache.maven.scm.repository.ScmRepository; import org.codehaus.plexus.util.StringUtils; import com.redhat.rcm.maven.plugin.buildmetadata.scm.ScmException;
{ return remoteVersion; } /** * Sets the branch or tag version on the remote server to compare against. If * <code>null</code>, the SCM status will be used to determine the * differences. * * @param remoteVersion the branch or tag version on the remote server to * compare against. */ public void setRemoteVersion(final ScmVersion remoteVersion) { this.remoteVersion = remoteVersion; } // --- business ------------------------------------------------------------- /** * Creates and configures the SCM repository. * * @param scmManager the manager to create the repository dependent on the * {@link #getConnectionUrl() connection URL}. * @return the repository implementation to connect to the SCM system. * @throws ScmException if the repository implementation cannot be created or * configured. This happens especially if no provider exists for the * given connection URL. */ public ScmRepository createRepository(final ScmManager scmManager)
// Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/scm/ScmException.java // public class ScmException extends RuntimeException // { // // ********************************* Fields ********************************* // // // --- constants ------------------------------------------------------------ // // /** // * The class version identifier. // * <p> // * The value of this constant is {@value}. // */ // private static final long serialVersionUID = 1L; // // // --- members -------------------------------------------------------------- // // // ****************************** Initializer ******************************* // // // ****************************** Constructors ****************************** // // /** // * Default Constructor. // * // * @param message the detail message (which is saved for later retrieval by // * the {@link #getMessage()} method). // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <tt>null</tt> value is permitted, // * and indicates that the cause is nonexistent or unknown.) // * @see java.lang.RuntimeException#RuntimeException(java.lang.String, // * java.lang.Throwable) // */ // public ScmException(final String message, final Throwable cause) // { // super(message, cause); // } // // /** // * Convenience constructor providing no cause. // * // * @param message the detail message. The detail message is saved for later // * retrieval by the {@link #getMessage()} method. // * @see java.lang.RuntimeException#RuntimeException(java.lang.String) // */ // public ScmException(final String message) // { // super(message); // } // // /** // * Convenience constructor providing no message. // * // * @param cause the cause (which is saved for later retrieval by the // * {@link #getCause()} method). (A <tt>null</tt> value is permitted, // * and indicates that the cause is nonexistent or unknown.) // * @see java.lang.RuntimeException#RuntimeException(java.lang.Throwable) // */ // public ScmException(final Throwable cause) // { // super(cause); // } // // // ****************************** Inner Classes ***************************** // // // ********************************* Methods ******************************** // // // --- init ----------------------------------------------------------------- // // // --- get&set -------------------------------------------------------------- // // // --- business ------------------------------------------------------------- // // // --- object basics -------------------------------------------------------- // // } // Path: src/main/java/com/redhat/rcm/maven/plugin/buildmetadata/scm/maven/ScmConnectionInfo.java import java.io.Serializable; import org.apache.maven.scm.ScmVersion; import org.apache.maven.scm.manager.ScmManager; import org.apache.maven.scm.provider.ScmProviderRepository; import org.apache.maven.scm.provider.ScmProviderRepositoryWithHost; import org.apache.maven.scm.provider.svn.repository.SvnScmProviderRepository; import org.apache.maven.scm.repository.ScmRepository; import org.codehaus.plexus.util.StringUtils; import com.redhat.rcm.maven.plugin.buildmetadata.scm.ScmException; { return remoteVersion; } /** * Sets the branch or tag version on the remote server to compare against. If * <code>null</code>, the SCM status will be used to determine the * differences. * * @param remoteVersion the branch or tag version on the remote server to * compare against. */ public void setRemoteVersion(final ScmVersion remoteVersion) { this.remoteVersion = remoteVersion; } // --- business ------------------------------------------------------------- /** * Creates and configures the SCM repository. * * @param scmManager the manager to create the repository dependent on the * {@link #getConnectionUrl() connection URL}. * @return the repository implementation to connect to the SCM system. * @throws ScmException if the repository implementation cannot be created or * configured. This happens especially if no provider exists for the * given connection URL. */ public ScmRepository createRepository(final ScmManager scmManager)
throws ScmException
mruffalo/seal
src/external/AlignmentToolInterface.java
// Path: src/io/SamReader.java // public class SamReader // { // /** // * TODO: Use this // */ // private final BufferedReader source; // // public SamReader(Reader in) // { // source = new BufferedReader(in); // } // // public static Set<String> readMappedFragmentSet(File sam_output, int size) // { // Set<String> correctlyMappedFragments = new HashSet<String>(size); // try // { // BufferedReader r = new BufferedReader(new FileReader(sam_output)); // String line = null; // while ((line = r.readLine()) != null) // { // if (line.startsWith("@") || line.startsWith("#")) // { // continue; // } // String[] pieces = line.split("\\s+"); // if (pieces.length <= 3) // { // continue; // } // String fragmentIdentifier = pieces[0]; // int readPosition = -1; // Matcher m = Constants.READ_POSITION_HEADER.matcher(pieces[0]); // if (m.matches()) // { // readPosition = Integer.parseInt(m.group(2)); // } // int alignedPosition = Integer.parseInt(pieces[3]) - 1; // if (readPosition == alignedPosition) // { // correctlyMappedFragments.add(fragmentIdentifier); // } // } // } // catch (FileNotFoundException e) // { // e.printStackTrace(); // } // catch (IOException e) // { // e.printStackTrace(); // } // return correctlyMappedFragments; // } // // public static AlignmentResults readAlignment(Logger log, Options o, int fragmentCount, // Set<String> correctlyMappedFragments) // { // log.info("Reading alignment"); // Set<String> totalMappedFragments = new HashSet<String>(fragmentCount); // AlignmentResults rs = new AlignmentResults(); // try // { // BufferedReader r = new BufferedReader(new FileReader(o.sam_output)); // String line = null; // while ((line = r.readLine()) != null) // { // if (line.startsWith("@") || line.startsWith("#")) // { // continue; // } // String[] pieces = line.split("\\s+"); // if (pieces.length <= 3) // { // continue; // } // String fragmentIdentifier = pieces[0]; // int readPosition = -1; // Matcher m = Constants.READ_POSITION_HEADER.matcher(fragmentIdentifier); // if (m.matches()) // { // readPosition = Integer.parseInt(m.group(2)); // } // int alignedPosition = Integer.parseInt(pieces[3]) - 1; // int mappingScore = Integer.parseInt(pieces[4]); // if (!rs.positives.containsKey(mappingScore)) // { // rs.positives.put(mappingScore, 0); // } // if (!rs.negatives.containsKey(mappingScore)) // { // rs.negatives.put(mappingScore, 0); // } // if (readPosition == alignedPosition) // { // rs.positives.put(mappingScore, rs.positives.get(mappingScore) + 1); // } // else if (o.penalize_duplicate_mappings // || (!o.penalize_duplicate_mappings && !correctlyMappedFragments.contains(fragmentIdentifier))) // { // rs.negatives.put(mappingScore, rs.negatives.get(mappingScore) + 1); // } // totalMappedFragments.add(fragmentIdentifier); // } // /* // * If a fragment didn't appear in the output at all, count it as a // * false negative // */ // if (fragmentCount >= totalMappedFragments.size()) // { // rs.missingFragments += (fragmentCount - totalMappedFragments.size()); // } // } // catch (FileNotFoundException e) // { // e.printStackTrace(); // } // catch (IOException e) // { // e.printStackTrace(); // } // return rs; // } // }
import io.SamReader; import org.apache.log4j.*; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.Callable;
catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } public void commonPreAlignmentProcessing() { linkGenome(); linkFragments(); } public abstract void preAlignmentProcessing(); public abstract void align(); public abstract void postAlignmentProcessing(); /** * Default implementation reads SAM output. Can be overridden if the tool has a different output format. * * @return results */ public AlignmentResults readAlignment() {
// Path: src/io/SamReader.java // public class SamReader // { // /** // * TODO: Use this // */ // private final BufferedReader source; // // public SamReader(Reader in) // { // source = new BufferedReader(in); // } // // public static Set<String> readMappedFragmentSet(File sam_output, int size) // { // Set<String> correctlyMappedFragments = new HashSet<String>(size); // try // { // BufferedReader r = new BufferedReader(new FileReader(sam_output)); // String line = null; // while ((line = r.readLine()) != null) // { // if (line.startsWith("@") || line.startsWith("#")) // { // continue; // } // String[] pieces = line.split("\\s+"); // if (pieces.length <= 3) // { // continue; // } // String fragmentIdentifier = pieces[0]; // int readPosition = -1; // Matcher m = Constants.READ_POSITION_HEADER.matcher(pieces[0]); // if (m.matches()) // { // readPosition = Integer.parseInt(m.group(2)); // } // int alignedPosition = Integer.parseInt(pieces[3]) - 1; // if (readPosition == alignedPosition) // { // correctlyMappedFragments.add(fragmentIdentifier); // } // } // } // catch (FileNotFoundException e) // { // e.printStackTrace(); // } // catch (IOException e) // { // e.printStackTrace(); // } // return correctlyMappedFragments; // } // // public static AlignmentResults readAlignment(Logger log, Options o, int fragmentCount, // Set<String> correctlyMappedFragments) // { // log.info("Reading alignment"); // Set<String> totalMappedFragments = new HashSet<String>(fragmentCount); // AlignmentResults rs = new AlignmentResults(); // try // { // BufferedReader r = new BufferedReader(new FileReader(o.sam_output)); // String line = null; // while ((line = r.readLine()) != null) // { // if (line.startsWith("@") || line.startsWith("#")) // { // continue; // } // String[] pieces = line.split("\\s+"); // if (pieces.length <= 3) // { // continue; // } // String fragmentIdentifier = pieces[0]; // int readPosition = -1; // Matcher m = Constants.READ_POSITION_HEADER.matcher(fragmentIdentifier); // if (m.matches()) // { // readPosition = Integer.parseInt(m.group(2)); // } // int alignedPosition = Integer.parseInt(pieces[3]) - 1; // int mappingScore = Integer.parseInt(pieces[4]); // if (!rs.positives.containsKey(mappingScore)) // { // rs.positives.put(mappingScore, 0); // } // if (!rs.negatives.containsKey(mappingScore)) // { // rs.negatives.put(mappingScore, 0); // } // if (readPosition == alignedPosition) // { // rs.positives.put(mappingScore, rs.positives.get(mappingScore) + 1); // } // else if (o.penalize_duplicate_mappings // || (!o.penalize_duplicate_mappings && !correctlyMappedFragments.contains(fragmentIdentifier))) // { // rs.negatives.put(mappingScore, rs.negatives.get(mappingScore) + 1); // } // totalMappedFragments.add(fragmentIdentifier); // } // /* // * If a fragment didn't appear in the output at all, count it as a // * false negative // */ // if (fragmentCount >= totalMappedFragments.size()) // { // rs.missingFragments += (fragmentCount - totalMappedFragments.size()); // } // } // catch (FileNotFoundException e) // { // e.printStackTrace(); // } // catch (IOException e) // { // e.printStackTrace(); // } // return rs; // } // } // Path: src/external/AlignmentToolInterface.java import io.SamReader; import org.apache.log4j.*; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.Callable; catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } public void commonPreAlignmentProcessing() { linkGenome(); linkFragments(); } public abstract void preAlignmentProcessing(); public abstract void align(); public abstract void postAlignmentProcessing(); /** * Default implementation reads SAM output. Can be overridden if the tool has a different output format. * * @return results */ public AlignmentResults readAlignment() {
return SamReader.readAlignment(log, o, fragmentCount, correctlyMappedFragments);
mruffalo/seal
test/assembly/FragmentTest.java
// Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java // public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator // { // Random random = new Random(); // // @Override // public CharSequence generateSequence(Options o) // { // FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters, // o.repeatErrorProbability); // final CharSequence repeatedSequence = generateSequence(o.characters, o.repeatLength); // StringBuilder sb = new StringBuilder(o.length); // int[] repeatedSequenceIndices = new int[o.repeatCount]; // int nonRepeatedLength = o.length - o.repeatCount * o.repeatLength; // if (nonRepeatedLength > 0) // { // for (int i = 0; i < o.repeatCount; i++) // { // repeatedSequenceIndices[i] = random.nextInt(nonRepeatedLength); // } // Arrays.sort(repeatedSequenceIndices); // sb.append(generateSequence(o.characters, nonRepeatedLength)); // } // int repeatStart = 0; // for (int i = 0; i < o.repeatCount; i++) // { // if (verbose) // { // for (int j = 0; j < repeatedSequenceIndices[i] - repeatStart; j++) // { // System.out.print(" "); // } // System.out.print(repeatedSequence); // repeatStart = repeatedSequenceIndices[i]; // } // CharSequence currentRepeatedSequence; // if (o.repeatErrorProbability > 0.0) // { // currentRepeatedSequence = eg.generateErrors(repeatedSequence); // } // else // { // currentRepeatedSequence = repeatedSequence; // } // sb.insert(i * o.repeatLength + repeatedSequenceIndices[i], currentRepeatedSequence); // } // String string = sb.toString(); // if (verbose) // { // System.out.println(); // System.out.println(string); // } // return string; // } // // /** // * Standalone debug method // * // * @param args // */ // @SuppressWarnings("unused") // public static void main(String[] args) // { // if (args.length < 3) // { // System.err.printf("*** Usage: %s m r l e", // SeqGenSingleSequenceMultipleRepeats.class.getCanonicalName()); // System.exit(1); // } // Options o = new Options(); // o.length = Integer.parseInt(args[0]); // o.repeatCount = Integer.parseInt(args[1]); // o.repeatLength = Integer.parseInt(args[2]); // o.repeatErrorProbability = Double.parseDouble(args[3]); // SequenceGenerator generator = new SeqGenSingleSequenceMultipleRepeats(); // generator.setVerboseOutput(true); // CharSequence generated = generator.generateSequence(o); // } // } // // Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // }
import static org.junit.Assert.*; import java.util.List; import generator.SeqGenSingleSequenceMultipleRepeats; import generator.SequenceGenerator; import org.junit.Test;
package assembly; public class FragmentTest { private static final int PAIRED_END_LENGTH = 100; @Test public void testPairedEndClone() {
// Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java // public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator // { // Random random = new Random(); // // @Override // public CharSequence generateSequence(Options o) // { // FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters, // o.repeatErrorProbability); // final CharSequence repeatedSequence = generateSequence(o.characters, o.repeatLength); // StringBuilder sb = new StringBuilder(o.length); // int[] repeatedSequenceIndices = new int[o.repeatCount]; // int nonRepeatedLength = o.length - o.repeatCount * o.repeatLength; // if (nonRepeatedLength > 0) // { // for (int i = 0; i < o.repeatCount; i++) // { // repeatedSequenceIndices[i] = random.nextInt(nonRepeatedLength); // } // Arrays.sort(repeatedSequenceIndices); // sb.append(generateSequence(o.characters, nonRepeatedLength)); // } // int repeatStart = 0; // for (int i = 0; i < o.repeatCount; i++) // { // if (verbose) // { // for (int j = 0; j < repeatedSequenceIndices[i] - repeatStart; j++) // { // System.out.print(" "); // } // System.out.print(repeatedSequence); // repeatStart = repeatedSequenceIndices[i]; // } // CharSequence currentRepeatedSequence; // if (o.repeatErrorProbability > 0.0) // { // currentRepeatedSequence = eg.generateErrors(repeatedSequence); // } // else // { // currentRepeatedSequence = repeatedSequence; // } // sb.insert(i * o.repeatLength + repeatedSequenceIndices[i], currentRepeatedSequence); // } // String string = sb.toString(); // if (verbose) // { // System.out.println(); // System.out.println(string); // } // return string; // } // // /** // * Standalone debug method // * // * @param args // */ // @SuppressWarnings("unused") // public static void main(String[] args) // { // if (args.length < 3) // { // System.err.printf("*** Usage: %s m r l e", // SeqGenSingleSequenceMultipleRepeats.class.getCanonicalName()); // System.exit(1); // } // Options o = new Options(); // o.length = Integer.parseInt(args[0]); // o.repeatCount = Integer.parseInt(args[1]); // o.repeatLength = Integer.parseInt(args[2]); // o.repeatErrorProbability = Double.parseDouble(args[3]); // SequenceGenerator generator = new SeqGenSingleSequenceMultipleRepeats(); // generator.setVerboseOutput(true); // CharSequence generated = generator.generateSequence(o); // } // } // // Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // } // Path: test/assembly/FragmentTest.java import static org.junit.Assert.*; import java.util.List; import generator.SeqGenSingleSequenceMultipleRepeats; import generator.SequenceGenerator; import org.junit.Test; package assembly; public class FragmentTest { private static final int PAIRED_END_LENGTH = 100; @Test public void testPairedEndClone() {
SequenceGenerator g = new SeqGenSingleSequenceMultipleRepeats();
mruffalo/seal
test/assembly/FragmentTest.java
// Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java // public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator // { // Random random = new Random(); // // @Override // public CharSequence generateSequence(Options o) // { // FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters, // o.repeatErrorProbability); // final CharSequence repeatedSequence = generateSequence(o.characters, o.repeatLength); // StringBuilder sb = new StringBuilder(o.length); // int[] repeatedSequenceIndices = new int[o.repeatCount]; // int nonRepeatedLength = o.length - o.repeatCount * o.repeatLength; // if (nonRepeatedLength > 0) // { // for (int i = 0; i < o.repeatCount; i++) // { // repeatedSequenceIndices[i] = random.nextInt(nonRepeatedLength); // } // Arrays.sort(repeatedSequenceIndices); // sb.append(generateSequence(o.characters, nonRepeatedLength)); // } // int repeatStart = 0; // for (int i = 0; i < o.repeatCount; i++) // { // if (verbose) // { // for (int j = 0; j < repeatedSequenceIndices[i] - repeatStart; j++) // { // System.out.print(" "); // } // System.out.print(repeatedSequence); // repeatStart = repeatedSequenceIndices[i]; // } // CharSequence currentRepeatedSequence; // if (o.repeatErrorProbability > 0.0) // { // currentRepeatedSequence = eg.generateErrors(repeatedSequence); // } // else // { // currentRepeatedSequence = repeatedSequence; // } // sb.insert(i * o.repeatLength + repeatedSequenceIndices[i], currentRepeatedSequence); // } // String string = sb.toString(); // if (verbose) // { // System.out.println(); // System.out.println(string); // } // return string; // } // // /** // * Standalone debug method // * // * @param args // */ // @SuppressWarnings("unused") // public static void main(String[] args) // { // if (args.length < 3) // { // System.err.printf("*** Usage: %s m r l e", // SeqGenSingleSequenceMultipleRepeats.class.getCanonicalName()); // System.exit(1); // } // Options o = new Options(); // o.length = Integer.parseInt(args[0]); // o.repeatCount = Integer.parseInt(args[1]); // o.repeatLength = Integer.parseInt(args[2]); // o.repeatErrorProbability = Double.parseDouble(args[3]); // SequenceGenerator generator = new SeqGenSingleSequenceMultipleRepeats(); // generator.setVerboseOutput(true); // CharSequence generated = generator.generateSequence(o); // } // } // // Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // }
import static org.junit.Assert.*; import java.util.List; import generator.SeqGenSingleSequenceMultipleRepeats; import generator.SequenceGenerator; import org.junit.Test;
package assembly; public class FragmentTest { private static final int PAIRED_END_LENGTH = 100; @Test public void testPairedEndClone() {
// Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java // public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator // { // Random random = new Random(); // // @Override // public CharSequence generateSequence(Options o) // { // FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters, // o.repeatErrorProbability); // final CharSequence repeatedSequence = generateSequence(o.characters, o.repeatLength); // StringBuilder sb = new StringBuilder(o.length); // int[] repeatedSequenceIndices = new int[o.repeatCount]; // int nonRepeatedLength = o.length - o.repeatCount * o.repeatLength; // if (nonRepeatedLength > 0) // { // for (int i = 0; i < o.repeatCount; i++) // { // repeatedSequenceIndices[i] = random.nextInt(nonRepeatedLength); // } // Arrays.sort(repeatedSequenceIndices); // sb.append(generateSequence(o.characters, nonRepeatedLength)); // } // int repeatStart = 0; // for (int i = 0; i < o.repeatCount; i++) // { // if (verbose) // { // for (int j = 0; j < repeatedSequenceIndices[i] - repeatStart; j++) // { // System.out.print(" "); // } // System.out.print(repeatedSequence); // repeatStart = repeatedSequenceIndices[i]; // } // CharSequence currentRepeatedSequence; // if (o.repeatErrorProbability > 0.0) // { // currentRepeatedSequence = eg.generateErrors(repeatedSequence); // } // else // { // currentRepeatedSequence = repeatedSequence; // } // sb.insert(i * o.repeatLength + repeatedSequenceIndices[i], currentRepeatedSequence); // } // String string = sb.toString(); // if (verbose) // { // System.out.println(); // System.out.println(string); // } // return string; // } // // /** // * Standalone debug method // * // * @param args // */ // @SuppressWarnings("unused") // public static void main(String[] args) // { // if (args.length < 3) // { // System.err.printf("*** Usage: %s m r l e", // SeqGenSingleSequenceMultipleRepeats.class.getCanonicalName()); // System.exit(1); // } // Options o = new Options(); // o.length = Integer.parseInt(args[0]); // o.repeatCount = Integer.parseInt(args[1]); // o.repeatLength = Integer.parseInt(args[2]); // o.repeatErrorProbability = Double.parseDouble(args[3]); // SequenceGenerator generator = new SeqGenSingleSequenceMultipleRepeats(); // generator.setVerboseOutput(true); // CharSequence generated = generator.generateSequence(o); // } // } // // Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // } // Path: test/assembly/FragmentTest.java import static org.junit.Assert.*; import java.util.List; import generator.SeqGenSingleSequenceMultipleRepeats; import generator.SequenceGenerator; import org.junit.Test; package assembly; public class FragmentTest { private static final int PAIRED_END_LENGTH = 100; @Test public void testPairedEndClone() {
SequenceGenerator g = new SeqGenSingleSequenceMultipleRepeats();
mruffalo/seal
src/external/AccuracyEvaluationProgram.java
// Path: src/util/DoubleConverter.java // public class DoubleConverter implements IStringConverter<Double> // { // @Override // public Double convert(String s) // { // return Double.parseDouble(s); // } // } // // Path: src/util/GenomeConverter.java // public class GenomeConverter implements IStringConverter<AlignmentToolService.Genome> // { // @Override // public AlignmentToolService.Genome convert(String s) // { // AlignmentToolService.Genome g = AlignmentToolService.Genome.valueOf(s); // return g; // } // }
import com.beust.jcommander.Parameter; import util.DoubleConverter; import util.GenomeConverter;
package external; public class AccuracyEvaluationProgram extends EvaluationProgram { @Parameter(names = "--length", description = "Length of genome (if generated)") protected int generatedGenomeLength = AlignmentToolService.DEFAULT_GENERATED_GENOME_LENGTH; @Parameter(names = "--genome", description = "Genome to use; HUMAN and HUMAN_CHR22 require FASTA files to read",
// Path: src/util/DoubleConverter.java // public class DoubleConverter implements IStringConverter<Double> // { // @Override // public Double convert(String s) // { // return Double.parseDouble(s); // } // } // // Path: src/util/GenomeConverter.java // public class GenomeConverter implements IStringConverter<AlignmentToolService.Genome> // { // @Override // public AlignmentToolService.Genome convert(String s) // { // AlignmentToolService.Genome g = AlignmentToolService.Genome.valueOf(s); // return g; // } // } // Path: src/external/AccuracyEvaluationProgram.java import com.beust.jcommander.Parameter; import util.DoubleConverter; import util.GenomeConverter; package external; public class AccuracyEvaluationProgram extends EvaluationProgram { @Parameter(names = "--length", description = "Length of genome (if generated)") protected int generatedGenomeLength = AlignmentToolService.DEFAULT_GENERATED_GENOME_LENGTH; @Parameter(names = "--genome", description = "Genome to use; HUMAN and HUMAN_CHR22 require FASTA files to read",
converter = GenomeConverter.class)
mruffalo/seal
src/external/AccuracyEvaluationProgram.java
// Path: src/util/DoubleConverter.java // public class DoubleConverter implements IStringConverter<Double> // { // @Override // public Double convert(String s) // { // return Double.parseDouble(s); // } // } // // Path: src/util/GenomeConverter.java // public class GenomeConverter implements IStringConverter<AlignmentToolService.Genome> // { // @Override // public AlignmentToolService.Genome convert(String s) // { // AlignmentToolService.Genome g = AlignmentToolService.Genome.valueOf(s); // return g; // } // }
import com.beust.jcommander.Parameter; import util.DoubleConverter; import util.GenomeConverter;
package external; public class AccuracyEvaluationProgram extends EvaluationProgram { @Parameter(names = "--length", description = "Length of genome (if generated)") protected int generatedGenomeLength = AlignmentToolService.DEFAULT_GENERATED_GENOME_LENGTH; @Parameter(names = "--genome", description = "Genome to use; HUMAN and HUMAN_CHR22 require FASTA files to read", converter = GenomeConverter.class) protected AlignmentToolService.Genome genome = AlignmentToolService.Genome.RANDOM_HARD; @Parameter(names = "--fragment-length", description = "Fragment length (mean)") protected int fragmentLength = AlignmentToolService.DEFAULT_FRAGMENT_LENGTH_MEAN; @Parameter(names = "--fragment-length-sd", description = "Fragment length (std.dev.)",
// Path: src/util/DoubleConverter.java // public class DoubleConverter implements IStringConverter<Double> // { // @Override // public Double convert(String s) // { // return Double.parseDouble(s); // } // } // // Path: src/util/GenomeConverter.java // public class GenomeConverter implements IStringConverter<AlignmentToolService.Genome> // { // @Override // public AlignmentToolService.Genome convert(String s) // { // AlignmentToolService.Genome g = AlignmentToolService.Genome.valueOf(s); // return g; // } // } // Path: src/external/AccuracyEvaluationProgram.java import com.beust.jcommander.Parameter; import util.DoubleConverter; import util.GenomeConverter; package external; public class AccuracyEvaluationProgram extends EvaluationProgram { @Parameter(names = "--length", description = "Length of genome (if generated)") protected int generatedGenomeLength = AlignmentToolService.DEFAULT_GENERATED_GENOME_LENGTH; @Parameter(names = "--genome", description = "Genome to use; HUMAN and HUMAN_CHR22 require FASTA files to read", converter = GenomeConverter.class) protected AlignmentToolService.Genome genome = AlignmentToolService.Genome.RANDOM_HARD; @Parameter(names = "--fragment-length", description = "Fragment length (mean)") protected int fragmentLength = AlignmentToolService.DEFAULT_FRAGMENT_LENGTH_MEAN; @Parameter(names = "--fragment-length-sd", description = "Fragment length (std.dev.)",
converter = DoubleConverter.class)
mruffalo/seal
src/generator/errors/IndelGenerator.java
// Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java // public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator // { // Random random = new Random(); // // @Override // public CharSequence generateSequence(Options o) // { // FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters, // o.repeatErrorProbability); // final CharSequence repeatedSequence = generateSequence(o.characters, o.repeatLength); // StringBuilder sb = new StringBuilder(o.length); // int[] repeatedSequenceIndices = new int[o.repeatCount]; // int nonRepeatedLength = o.length - o.repeatCount * o.repeatLength; // if (nonRepeatedLength > 0) // { // for (int i = 0; i < o.repeatCount; i++) // { // repeatedSequenceIndices[i] = random.nextInt(nonRepeatedLength); // } // Arrays.sort(repeatedSequenceIndices); // sb.append(generateSequence(o.characters, nonRepeatedLength)); // } // int repeatStart = 0; // for (int i = 0; i < o.repeatCount; i++) // { // if (verbose) // { // for (int j = 0; j < repeatedSequenceIndices[i] - repeatStart; j++) // { // System.out.print(" "); // } // System.out.print(repeatedSequence); // repeatStart = repeatedSequenceIndices[i]; // } // CharSequence currentRepeatedSequence; // if (o.repeatErrorProbability > 0.0) // { // currentRepeatedSequence = eg.generateErrors(repeatedSequence); // } // else // { // currentRepeatedSequence = repeatedSequence; // } // sb.insert(i * o.repeatLength + repeatedSequenceIndices[i], currentRepeatedSequence); // } // String string = sb.toString(); // if (verbose) // { // System.out.println(); // System.out.println(string); // } // return string; // } // // /** // * Standalone debug method // * // * @param args // */ // @SuppressWarnings("unused") // public static void main(String[] args) // { // if (args.length < 3) // { // System.err.printf("*** Usage: %s m r l e", // SeqGenSingleSequenceMultipleRepeats.class.getCanonicalName()); // System.exit(1); // } // Options o = new Options(); // o.length = Integer.parseInt(args[0]); // o.repeatCount = Integer.parseInt(args[1]); // o.repeatLength = Integer.parseInt(args[2]); // o.repeatErrorProbability = Double.parseDouble(args[3]); // SequenceGenerator generator = new SeqGenSingleSequenceMultipleRepeats(); // generator.setVerboseOutput(true); // CharSequence generated = generator.generateSequence(o); // } // } // // Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // }
import generator.SeqGenSingleSequenceMultipleRepeats; import generator.SequenceGenerator;
package generator.errors; /** * TODO: Examine whether this should really subclass * {@link FragmentErrorGenerator} * * @author mruffalo */ public class IndelGenerator extends FragmentErrorGenerator { private Options o;
// Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java // public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator // { // Random random = new Random(); // // @Override // public CharSequence generateSequence(Options o) // { // FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters, // o.repeatErrorProbability); // final CharSequence repeatedSequence = generateSequence(o.characters, o.repeatLength); // StringBuilder sb = new StringBuilder(o.length); // int[] repeatedSequenceIndices = new int[o.repeatCount]; // int nonRepeatedLength = o.length - o.repeatCount * o.repeatLength; // if (nonRepeatedLength > 0) // { // for (int i = 0; i < o.repeatCount; i++) // { // repeatedSequenceIndices[i] = random.nextInt(nonRepeatedLength); // } // Arrays.sort(repeatedSequenceIndices); // sb.append(generateSequence(o.characters, nonRepeatedLength)); // } // int repeatStart = 0; // for (int i = 0; i < o.repeatCount; i++) // { // if (verbose) // { // for (int j = 0; j < repeatedSequenceIndices[i] - repeatStart; j++) // { // System.out.print(" "); // } // System.out.print(repeatedSequence); // repeatStart = repeatedSequenceIndices[i]; // } // CharSequence currentRepeatedSequence; // if (o.repeatErrorProbability > 0.0) // { // currentRepeatedSequence = eg.generateErrors(repeatedSequence); // } // else // { // currentRepeatedSequence = repeatedSequence; // } // sb.insert(i * o.repeatLength + repeatedSequenceIndices[i], currentRepeatedSequence); // } // String string = sb.toString(); // if (verbose) // { // System.out.println(); // System.out.println(string); // } // return string; // } // // /** // * Standalone debug method // * // * @param args // */ // @SuppressWarnings("unused") // public static void main(String[] args) // { // if (args.length < 3) // { // System.err.printf("*** Usage: %s m r l e", // SeqGenSingleSequenceMultipleRepeats.class.getCanonicalName()); // System.exit(1); // } // Options o = new Options(); // o.length = Integer.parseInt(args[0]); // o.repeatCount = Integer.parseInt(args[1]); // o.repeatLength = Integer.parseInt(args[2]); // o.repeatErrorProbability = Double.parseDouble(args[3]); // SequenceGenerator generator = new SeqGenSingleSequenceMultipleRepeats(); // generator.setVerboseOutput(true); // CharSequence generated = generator.generateSequence(o); // } // } // // Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // } // Path: src/generator/errors/IndelGenerator.java import generator.SeqGenSingleSequenceMultipleRepeats; import generator.SequenceGenerator; package generator.errors; /** * TODO: Examine whether this should really subclass * {@link FragmentErrorGenerator} * * @author mruffalo */ public class IndelGenerator extends FragmentErrorGenerator { private Options o;
private SequenceGenerator sg;
mruffalo/seal
src/generator/SeqGenSingleSequenceMultipleRepeats.java
// Path: src/generator/errors/FragmentErrorGenerator.java // public abstract class FragmentErrorGenerator // { // /** // * Used to determine which character to randomly insert/switch // */ // protected final Random characterChoiceRandomizer; // /** // * Intended for use by each generator to determine whether to introduce an // * error (e.g. substitute a character, start an indel) // */ // protected final Random random; // protected final String allowedCharacters; // protected boolean verbose; // // public FragmentErrorGenerator(String allowedCharacters_) // { // allowedCharacters = allowedCharacters_; // characterChoiceRandomizer = new Random(); // random = new Random(); // } // // public abstract CharSequence generateErrors(CharSequence sequence); // // public Fragment generateErrors(Fragment fragment) // { // String s = fragment.toString(); // Fragment errored = new Fragment(generateErrors(s).toString()); // errored.clonePositionsAndReadQuality(fragment); // for (int i = 0; i < errored.getSequence().length(); i++) // { // errored.setReadQuality(i, getQuality(i, errored.getSequence().length())); // } // return errored; // } // // public List<? extends Fragment> generateErrors(List<? extends Fragment> fragments) // { // List<Fragment> list = new ArrayList<Fragment>(fragments.size()); // for (Fragment fragment : fragments) // { // list.add(generateErrors(fragment)); // } // return list; // } // // /** // * @deprecated You should probably use // * {@link Fragmentizer#fragmentizeToFile(CharSequence, generator.Fragmentizer.Options, File)} // * and set the {@link Fragmentizer.Options#errorGenerators} // * field appropriately instead of using this. // * @param errorGenerators // * @param fragmentList // * @param fragmentFile // */ // @Deprecated // public static void generateErrorsToFile(List<FragmentErrorGenerator> errorGenerators, // List<? extends Fragment> fragmentList, File fragmentFile) // { // try // { // FastqWriter w = new FastqWriter(new FileWriter(fragmentFile)); // for (int i = 0; i < fragmentList.size(); i++) // { // Fragment f = fragmentList.get(i); // for (FragmentErrorGenerator eg : errorGenerators) // { // f = eg.generateErrors(f); // } // w.writeFragment(f, 0, i); // } // w.close(); // } // catch (IOException e) // { // e.printStackTrace(); // } // } // // public abstract int getQuality(int position, int length); // // public static int phredScaleProbability(double errorProbability) // { // return (int) (-10 * Math.log10(errorProbability)); // } // // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // } // // Path: src/generator/errors/UniformErrorGenerator.java // public class UniformErrorGenerator extends SubstitutionErrorGenerator // { // private double errorProbability; // // public UniformErrorGenerator(String allowedCharacters_, double errorProbability_) // { // super(allowedCharacters_); // setErrorProbability(errorProbability_); // } // // @Override // protected double getSubstitutionProbability(int position, int length) // { // return errorProbability; // } // // public void setErrorProbability(double errorProbability_) // { // if (errorProbability_ <= 1.0 && errorProbability_ >= 0.0) // { // errorProbability = errorProbability_; // } // else // { // // TODO: be nicer about this :) // throw new IllegalArgumentException("error probability must be >= 0.0 and <= 1.0"); // } // } // // public double getErrorProbability() // { // return errorProbability; // } // // /** // * Don't need to use the nice {@link #getErrorProbability} method, // * since we know that it's the same for every character position in this // * class. // */ // @Override // public CharSequence generateErrors(CharSequence sequence) // { // if (verbose) // { // System.err.println(); // System.err.printf("Original sequence: %s%n", sequence); // System.err.print(" "); // } // StringBuilder sb = new StringBuilder(sequence.length()); // StringBuilder errorIndicator = new StringBuilder(sequence.length()); // for (int i = 0; i < sequence.length(); i++) // { // char orig = sequence.charAt(i); // if (random.nextDouble() < getSubstitutionProbability(i, sequence.length())) // { // sb.append(chooseRandomReplacementCharacter(orig)); // if (verbose) // { // errorIndicator.append("X"); // } // } // else // { // sb.append(orig); // if (verbose) // { // errorIndicator.append(" "); // } // } // } // if (verbose) // { // System.err.println(errorIndicator.toString()); // System.err.printf("New sequence: %s%n%n", sb.toString()); // } // return sb; // } // }
import generator.errors.FragmentErrorGenerator; import generator.errors.UniformErrorGenerator; import java.util.Arrays; import java.util.Random;
package generator; public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator { Random random = new Random(); @Override public CharSequence generateSequence(Options o) {
// Path: src/generator/errors/FragmentErrorGenerator.java // public abstract class FragmentErrorGenerator // { // /** // * Used to determine which character to randomly insert/switch // */ // protected final Random characterChoiceRandomizer; // /** // * Intended for use by each generator to determine whether to introduce an // * error (e.g. substitute a character, start an indel) // */ // protected final Random random; // protected final String allowedCharacters; // protected boolean verbose; // // public FragmentErrorGenerator(String allowedCharacters_) // { // allowedCharacters = allowedCharacters_; // characterChoiceRandomizer = new Random(); // random = new Random(); // } // // public abstract CharSequence generateErrors(CharSequence sequence); // // public Fragment generateErrors(Fragment fragment) // { // String s = fragment.toString(); // Fragment errored = new Fragment(generateErrors(s).toString()); // errored.clonePositionsAndReadQuality(fragment); // for (int i = 0; i < errored.getSequence().length(); i++) // { // errored.setReadQuality(i, getQuality(i, errored.getSequence().length())); // } // return errored; // } // // public List<? extends Fragment> generateErrors(List<? extends Fragment> fragments) // { // List<Fragment> list = new ArrayList<Fragment>(fragments.size()); // for (Fragment fragment : fragments) // { // list.add(generateErrors(fragment)); // } // return list; // } // // /** // * @deprecated You should probably use // * {@link Fragmentizer#fragmentizeToFile(CharSequence, generator.Fragmentizer.Options, File)} // * and set the {@link Fragmentizer.Options#errorGenerators} // * field appropriately instead of using this. // * @param errorGenerators // * @param fragmentList // * @param fragmentFile // */ // @Deprecated // public static void generateErrorsToFile(List<FragmentErrorGenerator> errorGenerators, // List<? extends Fragment> fragmentList, File fragmentFile) // { // try // { // FastqWriter w = new FastqWriter(new FileWriter(fragmentFile)); // for (int i = 0; i < fragmentList.size(); i++) // { // Fragment f = fragmentList.get(i); // for (FragmentErrorGenerator eg : errorGenerators) // { // f = eg.generateErrors(f); // } // w.writeFragment(f, 0, i); // } // w.close(); // } // catch (IOException e) // { // e.printStackTrace(); // } // } // // public abstract int getQuality(int position, int length); // // public static int phredScaleProbability(double errorProbability) // { // return (int) (-10 * Math.log10(errorProbability)); // } // // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // } // // Path: src/generator/errors/UniformErrorGenerator.java // public class UniformErrorGenerator extends SubstitutionErrorGenerator // { // private double errorProbability; // // public UniformErrorGenerator(String allowedCharacters_, double errorProbability_) // { // super(allowedCharacters_); // setErrorProbability(errorProbability_); // } // // @Override // protected double getSubstitutionProbability(int position, int length) // { // return errorProbability; // } // // public void setErrorProbability(double errorProbability_) // { // if (errorProbability_ <= 1.0 && errorProbability_ >= 0.0) // { // errorProbability = errorProbability_; // } // else // { // // TODO: be nicer about this :) // throw new IllegalArgumentException("error probability must be >= 0.0 and <= 1.0"); // } // } // // public double getErrorProbability() // { // return errorProbability; // } // // /** // * Don't need to use the nice {@link #getErrorProbability} method, // * since we know that it's the same for every character position in this // * class. // */ // @Override // public CharSequence generateErrors(CharSequence sequence) // { // if (verbose) // { // System.err.println(); // System.err.printf("Original sequence: %s%n", sequence); // System.err.print(" "); // } // StringBuilder sb = new StringBuilder(sequence.length()); // StringBuilder errorIndicator = new StringBuilder(sequence.length()); // for (int i = 0; i < sequence.length(); i++) // { // char orig = sequence.charAt(i); // if (random.nextDouble() < getSubstitutionProbability(i, sequence.length())) // { // sb.append(chooseRandomReplacementCharacter(orig)); // if (verbose) // { // errorIndicator.append("X"); // } // } // else // { // sb.append(orig); // if (verbose) // { // errorIndicator.append(" "); // } // } // } // if (verbose) // { // System.err.println(errorIndicator.toString()); // System.err.printf("New sequence: %s%n%n", sb.toString()); // } // return sb; // } // } // Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java import generator.errors.FragmentErrorGenerator; import generator.errors.UniformErrorGenerator; import java.util.Arrays; import java.util.Random; package generator; public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator { Random random = new Random(); @Override public CharSequence generateSequence(Options o) {
FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters,
mruffalo/seal
src/generator/SeqGenSingleSequenceMultipleRepeats.java
// Path: src/generator/errors/FragmentErrorGenerator.java // public abstract class FragmentErrorGenerator // { // /** // * Used to determine which character to randomly insert/switch // */ // protected final Random characterChoiceRandomizer; // /** // * Intended for use by each generator to determine whether to introduce an // * error (e.g. substitute a character, start an indel) // */ // protected final Random random; // protected final String allowedCharacters; // protected boolean verbose; // // public FragmentErrorGenerator(String allowedCharacters_) // { // allowedCharacters = allowedCharacters_; // characterChoiceRandomizer = new Random(); // random = new Random(); // } // // public abstract CharSequence generateErrors(CharSequence sequence); // // public Fragment generateErrors(Fragment fragment) // { // String s = fragment.toString(); // Fragment errored = new Fragment(generateErrors(s).toString()); // errored.clonePositionsAndReadQuality(fragment); // for (int i = 0; i < errored.getSequence().length(); i++) // { // errored.setReadQuality(i, getQuality(i, errored.getSequence().length())); // } // return errored; // } // // public List<? extends Fragment> generateErrors(List<? extends Fragment> fragments) // { // List<Fragment> list = new ArrayList<Fragment>(fragments.size()); // for (Fragment fragment : fragments) // { // list.add(generateErrors(fragment)); // } // return list; // } // // /** // * @deprecated You should probably use // * {@link Fragmentizer#fragmentizeToFile(CharSequence, generator.Fragmentizer.Options, File)} // * and set the {@link Fragmentizer.Options#errorGenerators} // * field appropriately instead of using this. // * @param errorGenerators // * @param fragmentList // * @param fragmentFile // */ // @Deprecated // public static void generateErrorsToFile(List<FragmentErrorGenerator> errorGenerators, // List<? extends Fragment> fragmentList, File fragmentFile) // { // try // { // FastqWriter w = new FastqWriter(new FileWriter(fragmentFile)); // for (int i = 0; i < fragmentList.size(); i++) // { // Fragment f = fragmentList.get(i); // for (FragmentErrorGenerator eg : errorGenerators) // { // f = eg.generateErrors(f); // } // w.writeFragment(f, 0, i); // } // w.close(); // } // catch (IOException e) // { // e.printStackTrace(); // } // } // // public abstract int getQuality(int position, int length); // // public static int phredScaleProbability(double errorProbability) // { // return (int) (-10 * Math.log10(errorProbability)); // } // // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // } // // Path: src/generator/errors/UniformErrorGenerator.java // public class UniformErrorGenerator extends SubstitutionErrorGenerator // { // private double errorProbability; // // public UniformErrorGenerator(String allowedCharacters_, double errorProbability_) // { // super(allowedCharacters_); // setErrorProbability(errorProbability_); // } // // @Override // protected double getSubstitutionProbability(int position, int length) // { // return errorProbability; // } // // public void setErrorProbability(double errorProbability_) // { // if (errorProbability_ <= 1.0 && errorProbability_ >= 0.0) // { // errorProbability = errorProbability_; // } // else // { // // TODO: be nicer about this :) // throw new IllegalArgumentException("error probability must be >= 0.0 and <= 1.0"); // } // } // // public double getErrorProbability() // { // return errorProbability; // } // // /** // * Don't need to use the nice {@link #getErrorProbability} method, // * since we know that it's the same for every character position in this // * class. // */ // @Override // public CharSequence generateErrors(CharSequence sequence) // { // if (verbose) // { // System.err.println(); // System.err.printf("Original sequence: %s%n", sequence); // System.err.print(" "); // } // StringBuilder sb = new StringBuilder(sequence.length()); // StringBuilder errorIndicator = new StringBuilder(sequence.length()); // for (int i = 0; i < sequence.length(); i++) // { // char orig = sequence.charAt(i); // if (random.nextDouble() < getSubstitutionProbability(i, sequence.length())) // { // sb.append(chooseRandomReplacementCharacter(orig)); // if (verbose) // { // errorIndicator.append("X"); // } // } // else // { // sb.append(orig); // if (verbose) // { // errorIndicator.append(" "); // } // } // } // if (verbose) // { // System.err.println(errorIndicator.toString()); // System.err.printf("New sequence: %s%n%n", sb.toString()); // } // return sb; // } // }
import generator.errors.FragmentErrorGenerator; import generator.errors.UniformErrorGenerator; import java.util.Arrays; import java.util.Random;
package generator; public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator { Random random = new Random(); @Override public CharSequence generateSequence(Options o) {
// Path: src/generator/errors/FragmentErrorGenerator.java // public abstract class FragmentErrorGenerator // { // /** // * Used to determine which character to randomly insert/switch // */ // protected final Random characterChoiceRandomizer; // /** // * Intended for use by each generator to determine whether to introduce an // * error (e.g. substitute a character, start an indel) // */ // protected final Random random; // protected final String allowedCharacters; // protected boolean verbose; // // public FragmentErrorGenerator(String allowedCharacters_) // { // allowedCharacters = allowedCharacters_; // characterChoiceRandomizer = new Random(); // random = new Random(); // } // // public abstract CharSequence generateErrors(CharSequence sequence); // // public Fragment generateErrors(Fragment fragment) // { // String s = fragment.toString(); // Fragment errored = new Fragment(generateErrors(s).toString()); // errored.clonePositionsAndReadQuality(fragment); // for (int i = 0; i < errored.getSequence().length(); i++) // { // errored.setReadQuality(i, getQuality(i, errored.getSequence().length())); // } // return errored; // } // // public List<? extends Fragment> generateErrors(List<? extends Fragment> fragments) // { // List<Fragment> list = new ArrayList<Fragment>(fragments.size()); // for (Fragment fragment : fragments) // { // list.add(generateErrors(fragment)); // } // return list; // } // // /** // * @deprecated You should probably use // * {@link Fragmentizer#fragmentizeToFile(CharSequence, generator.Fragmentizer.Options, File)} // * and set the {@link Fragmentizer.Options#errorGenerators} // * field appropriately instead of using this. // * @param errorGenerators // * @param fragmentList // * @param fragmentFile // */ // @Deprecated // public static void generateErrorsToFile(List<FragmentErrorGenerator> errorGenerators, // List<? extends Fragment> fragmentList, File fragmentFile) // { // try // { // FastqWriter w = new FastqWriter(new FileWriter(fragmentFile)); // for (int i = 0; i < fragmentList.size(); i++) // { // Fragment f = fragmentList.get(i); // for (FragmentErrorGenerator eg : errorGenerators) // { // f = eg.generateErrors(f); // } // w.writeFragment(f, 0, i); // } // w.close(); // } // catch (IOException e) // { // e.printStackTrace(); // } // } // // public abstract int getQuality(int position, int length); // // public static int phredScaleProbability(double errorProbability) // { // return (int) (-10 * Math.log10(errorProbability)); // } // // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // } // // Path: src/generator/errors/UniformErrorGenerator.java // public class UniformErrorGenerator extends SubstitutionErrorGenerator // { // private double errorProbability; // // public UniformErrorGenerator(String allowedCharacters_, double errorProbability_) // { // super(allowedCharacters_); // setErrorProbability(errorProbability_); // } // // @Override // protected double getSubstitutionProbability(int position, int length) // { // return errorProbability; // } // // public void setErrorProbability(double errorProbability_) // { // if (errorProbability_ <= 1.0 && errorProbability_ >= 0.0) // { // errorProbability = errorProbability_; // } // else // { // // TODO: be nicer about this :) // throw new IllegalArgumentException("error probability must be >= 0.0 and <= 1.0"); // } // } // // public double getErrorProbability() // { // return errorProbability; // } // // /** // * Don't need to use the nice {@link #getErrorProbability} method, // * since we know that it's the same for every character position in this // * class. // */ // @Override // public CharSequence generateErrors(CharSequence sequence) // { // if (verbose) // { // System.err.println(); // System.err.printf("Original sequence: %s%n", sequence); // System.err.print(" "); // } // StringBuilder sb = new StringBuilder(sequence.length()); // StringBuilder errorIndicator = new StringBuilder(sequence.length()); // for (int i = 0; i < sequence.length(); i++) // { // char orig = sequence.charAt(i); // if (random.nextDouble() < getSubstitutionProbability(i, sequence.length())) // { // sb.append(chooseRandomReplacementCharacter(orig)); // if (verbose) // { // errorIndicator.append("X"); // } // } // else // { // sb.append(orig); // if (verbose) // { // errorIndicator.append(" "); // } // } // } // if (verbose) // { // System.err.println(errorIndicator.toString()); // System.err.printf("New sequence: %s%n%n", sb.toString()); // } // return sb; // } // } // Path: src/generator/SeqGenSingleSequenceMultipleRepeats.java import generator.errors.FragmentErrorGenerator; import generator.errors.UniformErrorGenerator; import java.util.Arrays; import java.util.Random; package generator; public class SeqGenSingleSequenceMultipleRepeats extends SequenceGenerator { Random random = new Random(); @Override public CharSequence generateSequence(Options o) {
FragmentErrorGenerator eg = new UniformErrorGenerator(o.characters,
mruffalo/seal
src/io/SamReader.java
// Path: src/external/AlignmentResults.java // public class AlignmentResults // { // public AlignmentResults() // { // positives = new TreeMap<Integer, Integer>(); // negatives = new TreeMap<Integer, Integer>(); // } // // /** // * Quality values of alignments that are at the correct location in the // * genome // */ // public Map<Integer, Integer> positives; // /** // * Quality values of alignments that are at an incorrect location in the // * genome. // */ // public Map<Integer, Integer> negatives; // /** // * Number of fragments that were missing from the tool's output. Always // * added to false negative counts. // */ // public int missingFragments = 0; // /** // * Stores time for each operation // */ // public Map<AlignmentOperation, Long> timeMap; // // public FilteredAlignmentResults filter(int threshold) // { // int tp = 0; // int tn = 0; // int fp = 0; // int fn = missingFragments; // for (Map.Entry<Integer, Integer> p : positives.entrySet()) // { // if (p.getKey() >= threshold) // { // tp += p.getValue(); // } // else // { // fn += p.getValue(); // } // } // for (Map.Entry<Integer, Integer> n : negatives.entrySet()) // { // if (n.getKey() >= threshold) // { // fp += n.getValue(); // } // else // { // tn += n.getValue(); // } // } // return new FilteredAlignmentResults(threshold, tp, tn, fp, fn); // } // // } // // Path: src/external/AlignmentToolInterface.java // public static class Options // { // /** // * TODO: Examine how good an idea this was // * // * @author mruffalo // */ // public static class Reads // { // public Reads(int index_) // { // index = index_; // } // // public final int index; // /** // * The original reads that will be linked into this tool's directory // */ // public File orig_reads; // /** // * The read file that is used by this tool // */ // public File reads; // /** // * Not used for every tool // */ // public File binary_reads; // public File aligned_reads; // } // // public Options(boolean is_paired_end_, double error_rate_) // { // is_paired_end = is_paired_end_; // error_rate = error_rate_; // } // // public File tool_path; // public final boolean is_paired_end; // /** // * This might be the base call error rate, or the indel size or indel frequency. Always specified as a double even // * though indel size is an integer -- don't want any NumberFormatExceptions while printing this // */ // public final double error_rate; // /** // * This is the original genome file that is hardlinked to each tool's directory // */ // public File orig_genome; // /** // * This is the genome file that is used by each tool // */ // public File genome; // public File binary_genome; // public List<Reads> reads = new ArrayList<Reads>(2); // public File raw_output; // public File sam_output; // public File index; // /** // * Produced by this code, not the alignment tool // */ // public File converted_output; // public File unmapped_output; // public File roc_output; // public boolean penalize_duplicate_mappings = true; // // /** // * Only used for paired-end. XXX Move this // */ // public int readLength; // /** // * Only used for paired-end. XXX move this // */ // public double readLengthSd; // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import external.AlignmentResults; import external.AlignmentToolInterface.Options; import org.apache.log4j.Logger;
String[] pieces = line.split("\\s+"); if (pieces.length <= 3) { continue; } String fragmentIdentifier = pieces[0]; int readPosition = -1; Matcher m = Constants.READ_POSITION_HEADER.matcher(pieces[0]); if (m.matches()) { readPosition = Integer.parseInt(m.group(2)); } int alignedPosition = Integer.parseInt(pieces[3]) - 1; if (readPosition == alignedPosition) { correctlyMappedFragments.add(fragmentIdentifier); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return correctlyMappedFragments; }
// Path: src/external/AlignmentResults.java // public class AlignmentResults // { // public AlignmentResults() // { // positives = new TreeMap<Integer, Integer>(); // negatives = new TreeMap<Integer, Integer>(); // } // // /** // * Quality values of alignments that are at the correct location in the // * genome // */ // public Map<Integer, Integer> positives; // /** // * Quality values of alignments that are at an incorrect location in the // * genome. // */ // public Map<Integer, Integer> negatives; // /** // * Number of fragments that were missing from the tool's output. Always // * added to false negative counts. // */ // public int missingFragments = 0; // /** // * Stores time for each operation // */ // public Map<AlignmentOperation, Long> timeMap; // // public FilteredAlignmentResults filter(int threshold) // { // int tp = 0; // int tn = 0; // int fp = 0; // int fn = missingFragments; // for (Map.Entry<Integer, Integer> p : positives.entrySet()) // { // if (p.getKey() >= threshold) // { // tp += p.getValue(); // } // else // { // fn += p.getValue(); // } // } // for (Map.Entry<Integer, Integer> n : negatives.entrySet()) // { // if (n.getKey() >= threshold) // { // fp += n.getValue(); // } // else // { // tn += n.getValue(); // } // } // return new FilteredAlignmentResults(threshold, tp, tn, fp, fn); // } // // } // // Path: src/external/AlignmentToolInterface.java // public static class Options // { // /** // * TODO: Examine how good an idea this was // * // * @author mruffalo // */ // public static class Reads // { // public Reads(int index_) // { // index = index_; // } // // public final int index; // /** // * The original reads that will be linked into this tool's directory // */ // public File orig_reads; // /** // * The read file that is used by this tool // */ // public File reads; // /** // * Not used for every tool // */ // public File binary_reads; // public File aligned_reads; // } // // public Options(boolean is_paired_end_, double error_rate_) // { // is_paired_end = is_paired_end_; // error_rate = error_rate_; // } // // public File tool_path; // public final boolean is_paired_end; // /** // * This might be the base call error rate, or the indel size or indel frequency. Always specified as a double even // * though indel size is an integer -- don't want any NumberFormatExceptions while printing this // */ // public final double error_rate; // /** // * This is the original genome file that is hardlinked to each tool's directory // */ // public File orig_genome; // /** // * This is the genome file that is used by each tool // */ // public File genome; // public File binary_genome; // public List<Reads> reads = new ArrayList<Reads>(2); // public File raw_output; // public File sam_output; // public File index; // /** // * Produced by this code, not the alignment tool // */ // public File converted_output; // public File unmapped_output; // public File roc_output; // public boolean penalize_duplicate_mappings = true; // // /** // * Only used for paired-end. XXX Move this // */ // public int readLength; // /** // * Only used for paired-end. XXX move this // */ // public double readLengthSd; // } // Path: src/io/SamReader.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import external.AlignmentResults; import external.AlignmentToolInterface.Options; import org.apache.log4j.Logger; String[] pieces = line.split("\\s+"); if (pieces.length <= 3) { continue; } String fragmentIdentifier = pieces[0]; int readPosition = -1; Matcher m = Constants.READ_POSITION_HEADER.matcher(pieces[0]); if (m.matches()) { readPosition = Integer.parseInt(m.group(2)); } int alignedPosition = Integer.parseInt(pieces[3]) - 1; if (readPosition == alignedPosition) { correctlyMappedFragments.add(fragmentIdentifier); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return correctlyMappedFragments; }
public static AlignmentResults readAlignment(Logger log, Options o, int fragmentCount,
mruffalo/seal
src/io/SamReader.java
// Path: src/external/AlignmentResults.java // public class AlignmentResults // { // public AlignmentResults() // { // positives = new TreeMap<Integer, Integer>(); // negatives = new TreeMap<Integer, Integer>(); // } // // /** // * Quality values of alignments that are at the correct location in the // * genome // */ // public Map<Integer, Integer> positives; // /** // * Quality values of alignments that are at an incorrect location in the // * genome. // */ // public Map<Integer, Integer> negatives; // /** // * Number of fragments that were missing from the tool's output. Always // * added to false negative counts. // */ // public int missingFragments = 0; // /** // * Stores time for each operation // */ // public Map<AlignmentOperation, Long> timeMap; // // public FilteredAlignmentResults filter(int threshold) // { // int tp = 0; // int tn = 0; // int fp = 0; // int fn = missingFragments; // for (Map.Entry<Integer, Integer> p : positives.entrySet()) // { // if (p.getKey() >= threshold) // { // tp += p.getValue(); // } // else // { // fn += p.getValue(); // } // } // for (Map.Entry<Integer, Integer> n : negatives.entrySet()) // { // if (n.getKey() >= threshold) // { // fp += n.getValue(); // } // else // { // tn += n.getValue(); // } // } // return new FilteredAlignmentResults(threshold, tp, tn, fp, fn); // } // // } // // Path: src/external/AlignmentToolInterface.java // public static class Options // { // /** // * TODO: Examine how good an idea this was // * // * @author mruffalo // */ // public static class Reads // { // public Reads(int index_) // { // index = index_; // } // // public final int index; // /** // * The original reads that will be linked into this tool's directory // */ // public File orig_reads; // /** // * The read file that is used by this tool // */ // public File reads; // /** // * Not used for every tool // */ // public File binary_reads; // public File aligned_reads; // } // // public Options(boolean is_paired_end_, double error_rate_) // { // is_paired_end = is_paired_end_; // error_rate = error_rate_; // } // // public File tool_path; // public final boolean is_paired_end; // /** // * This might be the base call error rate, or the indel size or indel frequency. Always specified as a double even // * though indel size is an integer -- don't want any NumberFormatExceptions while printing this // */ // public final double error_rate; // /** // * This is the original genome file that is hardlinked to each tool's directory // */ // public File orig_genome; // /** // * This is the genome file that is used by each tool // */ // public File genome; // public File binary_genome; // public List<Reads> reads = new ArrayList<Reads>(2); // public File raw_output; // public File sam_output; // public File index; // /** // * Produced by this code, not the alignment tool // */ // public File converted_output; // public File unmapped_output; // public File roc_output; // public boolean penalize_duplicate_mappings = true; // // /** // * Only used for paired-end. XXX Move this // */ // public int readLength; // /** // * Only used for paired-end. XXX move this // */ // public double readLengthSd; // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import external.AlignmentResults; import external.AlignmentToolInterface.Options; import org.apache.log4j.Logger;
String[] pieces = line.split("\\s+"); if (pieces.length <= 3) { continue; } String fragmentIdentifier = pieces[0]; int readPosition = -1; Matcher m = Constants.READ_POSITION_HEADER.matcher(pieces[0]); if (m.matches()) { readPosition = Integer.parseInt(m.group(2)); } int alignedPosition = Integer.parseInt(pieces[3]) - 1; if (readPosition == alignedPosition) { correctlyMappedFragments.add(fragmentIdentifier); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return correctlyMappedFragments; }
// Path: src/external/AlignmentResults.java // public class AlignmentResults // { // public AlignmentResults() // { // positives = new TreeMap<Integer, Integer>(); // negatives = new TreeMap<Integer, Integer>(); // } // // /** // * Quality values of alignments that are at the correct location in the // * genome // */ // public Map<Integer, Integer> positives; // /** // * Quality values of alignments that are at an incorrect location in the // * genome. // */ // public Map<Integer, Integer> negatives; // /** // * Number of fragments that were missing from the tool's output. Always // * added to false negative counts. // */ // public int missingFragments = 0; // /** // * Stores time for each operation // */ // public Map<AlignmentOperation, Long> timeMap; // // public FilteredAlignmentResults filter(int threshold) // { // int tp = 0; // int tn = 0; // int fp = 0; // int fn = missingFragments; // for (Map.Entry<Integer, Integer> p : positives.entrySet()) // { // if (p.getKey() >= threshold) // { // tp += p.getValue(); // } // else // { // fn += p.getValue(); // } // } // for (Map.Entry<Integer, Integer> n : negatives.entrySet()) // { // if (n.getKey() >= threshold) // { // fp += n.getValue(); // } // else // { // tn += n.getValue(); // } // } // return new FilteredAlignmentResults(threshold, tp, tn, fp, fn); // } // // } // // Path: src/external/AlignmentToolInterface.java // public static class Options // { // /** // * TODO: Examine how good an idea this was // * // * @author mruffalo // */ // public static class Reads // { // public Reads(int index_) // { // index = index_; // } // // public final int index; // /** // * The original reads that will be linked into this tool's directory // */ // public File orig_reads; // /** // * The read file that is used by this tool // */ // public File reads; // /** // * Not used for every tool // */ // public File binary_reads; // public File aligned_reads; // } // // public Options(boolean is_paired_end_, double error_rate_) // { // is_paired_end = is_paired_end_; // error_rate = error_rate_; // } // // public File tool_path; // public final boolean is_paired_end; // /** // * This might be the base call error rate, or the indel size or indel frequency. Always specified as a double even // * though indel size is an integer -- don't want any NumberFormatExceptions while printing this // */ // public final double error_rate; // /** // * This is the original genome file that is hardlinked to each tool's directory // */ // public File orig_genome; // /** // * This is the genome file that is used by each tool // */ // public File genome; // public File binary_genome; // public List<Reads> reads = new ArrayList<Reads>(2); // public File raw_output; // public File sam_output; // public File index; // /** // * Produced by this code, not the alignment tool // */ // public File converted_output; // public File unmapped_output; // public File roc_output; // public boolean penalize_duplicate_mappings = true; // // /** // * Only used for paired-end. XXX Move this // */ // public int readLength; // /** // * Only used for paired-end. XXX move this // */ // public double readLengthSd; // } // Path: src/io/SamReader.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import external.AlignmentResults; import external.AlignmentToolInterface.Options; import org.apache.log4j.Logger; String[] pieces = line.split("\\s+"); if (pieces.length <= 3) { continue; } String fragmentIdentifier = pieces[0]; int readPosition = -1; Matcher m = Constants.READ_POSITION_HEADER.matcher(pieces[0]); if (m.matches()) { readPosition = Integer.parseInt(m.group(2)); } int alignedPosition = Integer.parseInt(pieces[3]) - 1; if (readPosition == alignedPosition) { correctlyMappedFragments.add(fragmentIdentifier); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return correctlyMappedFragments; }
public static AlignmentResults readAlignment(Logger log, Options o, int fragmentCount,
mruffalo/seal
src/external/AlignmentResults.java
// Path: src/external/AlignmentToolInterface.java // public enum AlignmentOperation // { // PREPROCESSING, // ALIGNMENT, // POSTPROCESSING, // TOTAL, // }
import java.util.Map; import java.util.TreeMap; import external.AlignmentToolInterface.AlignmentOperation;
/** * */ package external; public class AlignmentResults { public AlignmentResults() { positives = new TreeMap<Integer, Integer>(); negatives = new TreeMap<Integer, Integer>(); } /** * Quality values of alignments that are at the correct location in the * genome */ public Map<Integer, Integer> positives; /** * Quality values of alignments that are at an incorrect location in the * genome. */ public Map<Integer, Integer> negatives; /** * Number of fragments that were missing from the tool's output. Always * added to false negative counts. */ public int missingFragments = 0; /** * Stores time for each operation */
// Path: src/external/AlignmentToolInterface.java // public enum AlignmentOperation // { // PREPROCESSING, // ALIGNMENT, // POSTPROCESSING, // TOTAL, // } // Path: src/external/AlignmentResults.java import java.util.Map; import java.util.TreeMap; import external.AlignmentToolInterface.AlignmentOperation; /** * */ package external; public class AlignmentResults { public AlignmentResults() { positives = new TreeMap<Integer, Integer>(); negatives = new TreeMap<Integer, Integer>(); } /** * Quality values of alignments that are at the correct location in the * genome */ public Map<Integer, Integer> positives; /** * Quality values of alignments that are at an incorrect location in the * genome. */ public Map<Integer, Integer> negatives; /** * Number of fragments that were missing from the tool's output. Always * added to false negative counts. */ public int missingFragments = 0; /** * Stores time for each operation */
public Map<AlignmentOperation, Long> timeMap;
mruffalo/seal
src/assembly/PairedEndFragment.java
// Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // }
import generator.SequenceGenerator; import java.util.HashMap; import java.util.Map;
package assembly; public class PairedEndFragment extends Fragment { /** * TODO: Move this */ protected static final Map<Character, Character> NUCLEOTIDE_COMPLEMENTS = new HashMap<Character, Character>(
// Path: src/generator/SequenceGenerator.java // public abstract class SequenceGenerator // { // public static final String NUCLEOTIDES = "ACGT"; // public static final String NUCLEIC_ACID_ALLOWED_CHARACTERS = "ACGTURYKMSWBDHVNX-"; // public static final String AMINO_ACID_ALLOWED_CHARACTERS = "ABCDEFGHIKLMNOPQRSTUVWYZX*-"; // // protected boolean verbose; // // public static class Options // { // /** // * Characters in the generated sequence come from here // */ // public String characters = NUCLEOTIDES; // public int length; // public int repeatCount; // public int repeatLength; // /** // * Each character in each repeat will be substituted with a random // * choice from {@link #characters} at this probability // */ // public double repeatErrorProbability; // } // // /** // * Generates a single sequence with the provided length from the given // * characters. XXX Make this protected again after fixing all of the // * horrible design decisions I've recently made // * // * @param sample // * @param length // * @return // */ // public static CharSequence generateSequence(String sample, int length) // { // Random random = new Random(); // StringBuilder sb = new StringBuilder(length); // for (int i = 0; i < length; i++) // { // int index = random.nextInt(sample.length()); // sb.append(sample.substring(index, index + 1)); // } // return sb; // } // // /** // * Controls whether debugging information will be printed to // * <code>System.err</code>. TODO: Maybe allow a separate // * {@link java.io.OutputStream} to be specified. // * // * @param verbose_ // */ // public void setVerboseOutput(boolean verbose_) // { // verbose = verbose_; // } // // /** // * Generates a sequence according to the provided options // * // * @param o // * Options specifying length, repeat count, repeat length, // * characters to sample, error rate, etc. // * @return // */ // public abstract CharSequence generateSequence(Options o); // } // Path: src/assembly/PairedEndFragment.java import generator.SequenceGenerator; import java.util.HashMap; import java.util.Map; package assembly; public class PairedEndFragment extends Fragment { /** * TODO: Move this */ protected static final Map<Character, Character> NUCLEOTIDE_COMPLEMENTS = new HashMap<Character, Character>(
SequenceGenerator.NUCLEOTIDES.length());
Belgabor/AMTweaker
src/main/java/mods/belgabor/amtweaker/mods/emt/configuration/EMTConfiguration.java
// Path: src/main/java/mods/belgabor/amtweaker/AMTweaker.java // @Mod(modid = AMTweaker.MODID, version = AMTweaker.VERSION, name = "AMTweaker", dependencies = "required-after:MineTweaker3;after:DCsAppleMilk;after:ModTweaker;after:AWWayofTime;after:DCsEcoMT;after:mceconomy2") // public class AMTweaker implements IEventHandler<MineTweakerImplementationAPI.ReloadEvent> // { // public static final String MODID = "AMTweaker"; // public static final String VERSION = "1.0"; // // @Mod.Instance(MODID) // public static AMTweaker INSTANCE; // // public static File confDir; // public static File logsDir; // public static Logger logger; // public static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); // // public static void log(Level level, String message, Object ... args) { // logger.log(level, String.format(message, args)); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // logger = event.getModLog(); // confDir = new File(event.getModConfigurationDirectory(), "AMTweaker/"); // logsDir = new File("logs/"); // // Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); // try { // cfg.load(); // // cfg.setCategoryComment(SS2.MODID, "Sextiary Sector 2 specific options"); // // SS2.configIEHeatFurnaces = cfg.getBoolean("IEHeatFurnaces", SS2.MODID, SS2.configIEHeatFurnaces, // "Allow the Immersive Engineering Furnace Heater to heat the Fluid and Large Furnace"); // SS2.configIEHeatSmokers = cfg.getBoolean("IEHeatSmokers", SS2.MODID, SS2.configIEHeatSmokers, // "Allow the Immersive Engineering Furnace Heater to heat the Food Smokers"); // } catch (Exception e) { // e.printStackTrace(); // } finally { // if (cfg.hasChanged()) // cfg.save(); // } // // if (Loader.isModLoaded(EMT.MODID)) { // ensureConfDir(); // EMTConfiguration.read(); // } // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // new Vanilla(); // TweakerPlugin.register(AMT.MODID, AMT.class); // TweakerPlugin.register(EMT.MODID, EMT.class); // TweakerPlugin.register(MCE.MODID, MCE.class); // TweakerPlugin.register(SS2.MODID, SS2.class); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // if (Loader.isModLoaded(EMT.MODID)) { // EMTConfiguration.apply(); // } // } // // @EventHandler // public void onServerStart(FMLServerStartingEvent event) { // registerCommands(); // registerLoggers(); // MineTweakerImplementationAPI.onReloadEvent(this); // } // // private void registerCommands() { // MinecraftServer server = MinecraftServer.getServer(); // ICommandManager command = server.getCommandManager(); // ServerCommandManager manager = (ServerCommandManager) command; // manager.registerCommand(new VanillaCommandBlockstats()); // } // // public void handle(MineTweakerImplementationAPI.ReloadEvent event) { // registerLoggers(); // } // // private void ensureConfDir() { // if (!confDir.exists()) { // //noinspection ResultOfMethodCallIgnored // confDir.mkdirs(); // } // } // // private void registerLoggers() { // VanillaCommandLoggerItem.register(); // if (Loader.isModLoaded(AMT.MODID)) // AMTCommandLogger.register(); // if (Loader.isModLoaded(CW2.MODID)) // CW2CommandLogger.register(); // if (Loader.isModLoaded(EMT.MODID)) // EMTCommandLogger.register(); // if (Loader.isModLoaded(MCE.MODID)) // MCECommandLogger.register(); // if (Loader.isModLoaded(SS2.MODID)) // SS2CommandLogger.register(); // } // }
import com.google.gson.JsonElement; import defeatedcrow.addonforamt.economy.api.RecipeManagerEMT; import defeatedcrow.addonforamt.economy.api.order.IOrder; import defeatedcrow.addonforamt.economy.api.order.OrderBiome; import defeatedcrow.addonforamt.economy.api.order.OrderSeason; import defeatedcrow.addonforamt.economy.api.order.OrderType; import mods.belgabor.amtweaker.AMTweaker; import org.apache.logging.log4j.Level; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package mods.belgabor.amtweaker.mods.emt.configuration; /** * Created by Belgabor on 27.05.2016. */ public class EMTConfiguration { private static ArrayList<OrderData> orders; public static void read() { orders = new ArrayList<>();
// Path: src/main/java/mods/belgabor/amtweaker/AMTweaker.java // @Mod(modid = AMTweaker.MODID, version = AMTweaker.VERSION, name = "AMTweaker", dependencies = "required-after:MineTweaker3;after:DCsAppleMilk;after:ModTweaker;after:AWWayofTime;after:DCsEcoMT;after:mceconomy2") // public class AMTweaker implements IEventHandler<MineTweakerImplementationAPI.ReloadEvent> // { // public static final String MODID = "AMTweaker"; // public static final String VERSION = "1.0"; // // @Mod.Instance(MODID) // public static AMTweaker INSTANCE; // // public static File confDir; // public static File logsDir; // public static Logger logger; // public static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); // // public static void log(Level level, String message, Object ... args) { // logger.log(level, String.format(message, args)); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) // { // logger = event.getModLog(); // confDir = new File(event.getModConfigurationDirectory(), "AMTweaker/"); // logsDir = new File("logs/"); // // Configuration cfg = new Configuration(event.getSuggestedConfigurationFile()); // try { // cfg.load(); // // cfg.setCategoryComment(SS2.MODID, "Sextiary Sector 2 specific options"); // // SS2.configIEHeatFurnaces = cfg.getBoolean("IEHeatFurnaces", SS2.MODID, SS2.configIEHeatFurnaces, // "Allow the Immersive Engineering Furnace Heater to heat the Fluid and Large Furnace"); // SS2.configIEHeatSmokers = cfg.getBoolean("IEHeatSmokers", SS2.MODID, SS2.configIEHeatSmokers, // "Allow the Immersive Engineering Furnace Heater to heat the Food Smokers"); // } catch (Exception e) { // e.printStackTrace(); // } finally { // if (cfg.hasChanged()) // cfg.save(); // } // // if (Loader.isModLoaded(EMT.MODID)) { // ensureConfDir(); // EMTConfiguration.read(); // } // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // new Vanilla(); // TweakerPlugin.register(AMT.MODID, AMT.class); // TweakerPlugin.register(EMT.MODID, EMT.class); // TweakerPlugin.register(MCE.MODID, MCE.class); // TweakerPlugin.register(SS2.MODID, SS2.class); // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // if (Loader.isModLoaded(EMT.MODID)) { // EMTConfiguration.apply(); // } // } // // @EventHandler // public void onServerStart(FMLServerStartingEvent event) { // registerCommands(); // registerLoggers(); // MineTweakerImplementationAPI.onReloadEvent(this); // } // // private void registerCommands() { // MinecraftServer server = MinecraftServer.getServer(); // ICommandManager command = server.getCommandManager(); // ServerCommandManager manager = (ServerCommandManager) command; // manager.registerCommand(new VanillaCommandBlockstats()); // } // // public void handle(MineTweakerImplementationAPI.ReloadEvent event) { // registerLoggers(); // } // // private void ensureConfDir() { // if (!confDir.exists()) { // //noinspection ResultOfMethodCallIgnored // confDir.mkdirs(); // } // } // // private void registerLoggers() { // VanillaCommandLoggerItem.register(); // if (Loader.isModLoaded(AMT.MODID)) // AMTCommandLogger.register(); // if (Loader.isModLoaded(CW2.MODID)) // CW2CommandLogger.register(); // if (Loader.isModLoaded(EMT.MODID)) // EMTCommandLogger.register(); // if (Loader.isModLoaded(MCE.MODID)) // MCECommandLogger.register(); // if (Loader.isModLoaded(SS2.MODID)) // SS2CommandLogger.register(); // } // } // Path: src/main/java/mods/belgabor/amtweaker/mods/emt/configuration/EMTConfiguration.java import com.google.gson.JsonElement; import defeatedcrow.addonforamt.economy.api.RecipeManagerEMT; import defeatedcrow.addonforamt.economy.api.order.IOrder; import defeatedcrow.addonforamt.economy.api.order.OrderBiome; import defeatedcrow.addonforamt.economy.api.order.OrderSeason; import defeatedcrow.addonforamt.economy.api.order.OrderType; import mods.belgabor.amtweaker.AMTweaker; import org.apache.logging.log4j.Level; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package mods.belgabor.amtweaker.mods.emt.configuration; /** * Created by Belgabor on 27.05.2016. */ public class EMTConfiguration { private static ArrayList<OrderData> orders; public static void read() { orders = new ArrayList<>();
File emtConfig = new File(AMTweaker.confDir, "emt.json");
Belgabor/AMTweaker
src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Slag.java
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java // public static ItemStack toStack(IItemStack iStack) { // return toStack(iStack, false); // } // // Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java // public static boolean areEqual(ItemStack stack, ItemStack stack2) { // return !(stack == null || stack2 == null) && stack.isItemEqual(stack2); // }
import stanhebben.zenscript.annotations.ZenMethod; import java.util.ArrayList; import java.util.List; import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import mods.defeatedcrow.api.recipe.RecipeRegisterManager; import net.minecraft.item.ItemStack; import stanhebben.zenscript.annotations.ZenClass;
@ZenMethod public static void removeLoot(IItemStack item) { MineTweakerAPI.apply(new SlagLootRemoveAllAction(item)); } /* private static List<ItemStack> getLootList(int tier) { switch(tier) { case 1: return OreCrushRecipe.tier1; case 2: return OreCrushRecipe.tier2; case 3: return OreCrushRecipe.tier3; case 4: return OreCrushRecipe.tier4; case 5: return OreCrushRecipe.tier5; default: return null; } } */ private static class SlagLootAddAction implements IUndoableAction { private final ItemStack item; private final int tier; private final List<ItemStack> list; public SlagLootAddAction(IItemStack item, int tier) {
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java // public static ItemStack toStack(IItemStack iStack) { // return toStack(iStack, false); // } // // Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java // public static boolean areEqual(ItemStack stack, ItemStack stack2) { // return !(stack == null || stack2 == null) && stack.isItemEqual(stack2); // } // Path: src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Slag.java import stanhebben.zenscript.annotations.ZenMethod; import java.util.ArrayList; import java.util.List; import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import mods.defeatedcrow.api.recipe.RecipeRegisterManager; import net.minecraft.item.ItemStack; import stanhebben.zenscript.annotations.ZenClass; @ZenMethod public static void removeLoot(IItemStack item) { MineTweakerAPI.apply(new SlagLootRemoveAllAction(item)); } /* private static List<ItemStack> getLootList(int tier) { switch(tier) { case 1: return OreCrushRecipe.tier1; case 2: return OreCrushRecipe.tier2; case 3: return OreCrushRecipe.tier3; case 4: return OreCrushRecipe.tier4; case 5: return OreCrushRecipe.tier5; default: return null; } } */ private static class SlagLootAddAction implements IUndoableAction { private final ItemStack item; private final int tier; private final List<ItemStack> list; public SlagLootAddAction(IItemStack item, int tier) {
this.item = toStack(item);
Belgabor/AMTweaker
src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Slag.java
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java // public static ItemStack toStack(IItemStack iStack) { // return toStack(iStack, false); // } // // Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java // public static boolean areEqual(ItemStack stack, ItemStack stack2) { // return !(stack == null || stack2 == null) && stack.isItemEqual(stack2); // }
import stanhebben.zenscript.annotations.ZenMethod; import java.util.ArrayList; import java.util.List; import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import mods.defeatedcrow.api.recipe.RecipeRegisterManager; import net.minecraft.item.ItemStack; import stanhebben.zenscript.annotations.ZenClass;
} } */ private static class SlagLootAddAction implements IUndoableAction { private final ItemStack item; private final int tier; private final List<ItemStack> list; public SlagLootAddAction(IItemStack item, int tier) { this.item = toStack(item); this.tier = tier; this.list = RecipeRegisterManager.slagLoot.getLootList(tier); //this.list = getLootList(tier); } @Override public void apply() { RecipeRegisterManager.slagLoot.addLoot(item, tier); } @Override public boolean canUndo() { return true; } @Override public void undo() { boolean found = false; for(ItemStack i: list) {
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java // public static ItemStack toStack(IItemStack iStack) { // return toStack(iStack, false); // } // // Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java // public static boolean areEqual(ItemStack stack, ItemStack stack2) { // return !(stack == null || stack2 == null) && stack.isItemEqual(stack2); // } // Path: src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Slag.java import stanhebben.zenscript.annotations.ZenMethod; import java.util.ArrayList; import java.util.List; import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; import minetweaker.IUndoableAction; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IItemStack; import mods.defeatedcrow.api.recipe.RecipeRegisterManager; import net.minecraft.item.ItemStack; import stanhebben.zenscript.annotations.ZenClass; } } */ private static class SlagLootAddAction implements IUndoableAction { private final ItemStack item; private final int tier; private final List<ItemStack> list; public SlagLootAddAction(IItemStack item, int tier) { this.item = toStack(item); this.tier = tier; this.list = RecipeRegisterManager.slagLoot.getLootList(tier); //this.list = getLootList(tier); } @Override public void apply() { RecipeRegisterManager.slagLoot.addLoot(item, tier); } @Override public boolean canUndo() { return true; } @Override public void undo() { boolean found = false; for(ItemStack i: list) {
if (areEqual(i, item)) {