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
sundevin/utilsLibrary
utilslibrary/src/main/java/com/devin/util/SystemIntent.java
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import android.content.Intent; import android.net.Uri; import android.provider.Settings; import com.devin.UtilManager; import static android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS;
package com.devin.util; /** * <p>Description: 关于一些系统设置跳转的工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/26. */ public class SystemIntent { /** * 跳转到桌面 */ public static void startHomeActivity() { try { Intent homeIntent = new Intent(Intent.ACTION_MAIN); homeIntent.addCategory(Intent.CATEGORY_HOME); homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: utilslibrary/src/main/java/com/devin/util/SystemIntent.java import android.content.Intent; import android.net.Uri; import android.provider.Settings; import com.devin.UtilManager; import static android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS; package com.devin.util; /** * <p>Description: 关于一些系统设置跳转的工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/26. */ public class SystemIntent { /** * 跳转到桌面 */ public static void startHomeActivity() { try { Intent homeIntent = new Intent(Intent.ACTION_MAIN); homeIntent.addCategory(Intent.CATEGORY_HOME); homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
UtilManager.getContext().startActivity(homeIntent);
sundevin/utilsLibrary
utilslibrary/src/main/java/com/devin/util/NetworkUtils.java
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; import com.devin.UtilManager;
package com.devin.util; /** * <p>Description: 关于设备网络的工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/26. */ public class NetworkUtils { /** * 未知网络 */ public static final int NETWORK_TYPE_UNKNOWN = 0; /** * 没有网络 */ public static final int NETWORK_TYPE_INVALID = 0; /** * wap网络 */ public static final int NETWORK_TYPE_WAP = 1; /** * 2G网络 */ public static final int NETWORK_TYPE_2G = 2; /** * 3G网络 */ public static final int NETWORK_TYPE_3G = 3; /** * 4G网络 */ public static final int NETWORK_TYPE_4G = 4; /** * wifi网络 */ public static final int NETWORK_TYPE_WIFI = 10; /** * 检查是否有网络 * * @return true 有网,false 无网 */ public static boolean isAvailable() {
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: utilslibrary/src/main/java/com/devin/util/NetworkUtils.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; import com.devin.UtilManager; package com.devin.util; /** * <p>Description: 关于设备网络的工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/26. */ public class NetworkUtils { /** * 未知网络 */ public static final int NETWORK_TYPE_UNKNOWN = 0; /** * 没有网络 */ public static final int NETWORK_TYPE_INVALID = 0; /** * wap网络 */ public static final int NETWORK_TYPE_WAP = 1; /** * 2G网络 */ public static final int NETWORK_TYPE_2G = 2; /** * 3G网络 */ public static final int NETWORK_TYPE_3G = 3; /** * 4G网络 */ public static final int NETWORK_TYPE_4G = 4; /** * wifi网络 */ public static final int NETWORK_TYPE_WIFI = 10; /** * 检查是否有网络 * * @return true 有网,false 无网 */ public static boolean isAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) UtilManager.getContext()
sundevin/utilsLibrary
app/src/main/java/com/devin/utilscenter/MyApplication.java
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import android.app.Application; import com.devin.UtilManager;
package com.devin.utilscenter; /** * <p>Description: * <p>Company: * <p>Email:bjxm2013@163.com * <p>@author:Created by Devin Sun on 2017/11/30. */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate();
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: app/src/main/java/com/devin/utilscenter/MyApplication.java import android.app.Application; import com.devin.UtilManager; package com.devin.utilscenter; /** * <p>Description: * <p>Company: * <p>Email:bjxm2013@163.com * <p>@author:Created by Devin Sun on 2017/11/30. */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate();
UtilManager.init(this);
sundevin/utilsLibrary
utilslibrary/src/main/java/com/devin/util/DeviceInfo.java
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.FeatureInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Point; import android.graphics.Rect; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Environment; import android.os.PowerManager; import android.os.StatFs; import android.provider.Settings; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.WindowManager; import com.devin.UtilManager; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
package com.devin.util; /** * <p>Description: 关于设备信息的一些工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/25. */ public class DeviceInfo { /** * 得到屏幕的宽 适用安卓3.0以上 * * @return 屏幕的宽 px单位 */ public static int getScreenWidth() { // 得到手机窗体管理者
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: utilslibrary/src/main/java/com/devin/util/DeviceInfo.java import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.FeatureInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Point; import android.graphics.Rect; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Environment; import android.os.PowerManager; import android.os.StatFs; import android.provider.Settings; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import android.view.WindowManager; import com.devin.UtilManager; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; package com.devin.util; /** * <p>Description: 关于设备信息的一些工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/25. */ public class DeviceInfo { /** * 得到屏幕的宽 适用安卓3.0以上 * * @return 屏幕的宽 px单位 */ public static int getScreenWidth() { // 得到手机窗体管理者
WindowManager wm = (WindowManager) UtilManager.getContext()
sundevin/utilsLibrary
utilslibrary/src/main/java/com/devin/util/AppActivityManager.java
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import com.devin.UtilManager; import java.util.Stack;
/** * 结束堆栈中最后一个压入Activity */ public void finishLastActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 结束指定类名的Activity * * @param cls */ public void finishActivity(Class<? extends Activity> cls) { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); } } } /** * 退出应用程序 */ public void exitApp() { try { finishAllActivity();
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: utilslibrary/src/main/java/com/devin/util/AppActivityManager.java import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import com.devin.UtilManager; import java.util.Stack; /** * 结束堆栈中最后一个压入Activity */ public void finishLastActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 结束指定类名的Activity * * @param cls */ public void finishActivity(Class<? extends Activity> cls) { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); } } } /** * 退出应用程序 */ public void exitApp() { try { finishAllActivity();
ActivityManager activityMgr = (ActivityManager) UtilManager.getContext().getSystemService(Context.ACTIVITY_SERVICE);
sundevin/utilsLibrary
utilslibrary/src/main/java/com/devin/util/SoftKeyBoardUtils.java
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // }
import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.view.View; import android.view.ViewTreeObserver; import android.view.inputmethod.InputMethodManager; import com.devin.UtilManager;
package com.devin.util; /** * <p>Description: 软键盘工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/26. */ public class SoftKeyBoardUtils { /** * 打开软键盘 * * @param view 为接受软键盘输入的视图 */ public static void openKeybord(View view) {
// Path: utilslibrary/src/main/java/com/devin/UtilManager.java // public class UtilManager { // // private static Context mContext; // // /** // * 初始化工具类集合 // * @param context context // */ // public static void init(Context context) { // mContext = context.getApplicationContext(); // } // // public static Context getContext() { // return mContext; // } // } // Path: utilslibrary/src/main/java/com/devin/util/SoftKeyBoardUtils.java import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.view.View; import android.view.ViewTreeObserver; import android.view.inputmethod.InputMethodManager; import com.devin.UtilManager; package com.devin.util; /** * <p>Description: 软键盘工具类 * <p>Company: * <p>Email:bjxm2013@163.com * <p>Created by Devin Sun on 2017/4/26. */ public class SoftKeyBoardUtils { /** * 打开软键盘 * * @param view 为接受软键盘输入的视图 */ public static void openKeybord(View view) {
InputMethodManager imm = (InputMethodManager) UtilManager.getContext()
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/SentenceCollection.java
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/CollectionType.java // public enum CollectionType { // // TATOEBA("https://tatoeba.org", new CollectionTypeInfo() { // @Override // public String getSentenceUrl(String sentenceId) { // return null; // } // }), // // EU_CORPUS("http://www.statmt.org/europarl/", new CollectionTypeInfo() { // @Override // public String getSentenceUrl(String sentenceId) { // return "http://www.statmt.org/europarl/"; // } // }), // // OPUS_OPENSUBTITLES("http://opus.nlpl.eu", new CollectionTypeInfo() { // @Override // public String getSentenceUrl(String sentenceId) { // return "http://opus.nlpl.eu"; // } // }), // // ; // // @Getter // private final String url; // private final CollectionTypeInfo info; // // CollectionType(String url, CollectionTypeInfo info) { // this.url = url; // this.info = info; // } // // public interface CollectionTypeInfo { // String getSentenceUrl(String sentenceId); // } // // public String getSentenceUrl(String sentenceId) { // return info.getSentenceUrl(sentenceId); // } // // }
import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import java.text.NumberFormat; import java.util.Locale; import info.puzz.a10000sentences.apimodels.CollectionType;
package info.puzz.a10000sentences.models; @Table(name = "sentence_collection") public class SentenceCollection extends Model { private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(Locale.US); public static final int MAX_SENTENCES = 10_000; @Column(name = "collection_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) public String collectionID; @Column(name = "known_lang") public String knownLanguage; @Column(name = "target_lang") public String targetLanguage; @Column(name = "filename") public String filename; @Column(name = "count") public int count; @Column(name = "todo_count") public int todoCount; @Column(name = "repeat_count") public int repeatCount; @Column(name = "done_count") public int doneCount; @Column(name = "ignore_count") public int ignoreCount; @Column(name = "skipped_count") public int skippedCount; @Column(name = "annotation_count") public int annotationCount; @Column(name="type")
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/CollectionType.java // public enum CollectionType { // // TATOEBA("https://tatoeba.org", new CollectionTypeInfo() { // @Override // public String getSentenceUrl(String sentenceId) { // return null; // } // }), // // EU_CORPUS("http://www.statmt.org/europarl/", new CollectionTypeInfo() { // @Override // public String getSentenceUrl(String sentenceId) { // return "http://www.statmt.org/europarl/"; // } // }), // // OPUS_OPENSUBTITLES("http://opus.nlpl.eu", new CollectionTypeInfo() { // @Override // public String getSentenceUrl(String sentenceId) { // return "http://opus.nlpl.eu"; // } // }), // // ; // // @Getter // private final String url; // private final CollectionTypeInfo info; // // CollectionType(String url, CollectionTypeInfo info) { // this.url = url; // this.info = info; // } // // public interface CollectionTypeInfo { // String getSentenceUrl(String sentenceId); // } // // public String getSentenceUrl(String sentenceId) { // return info.getSentenceUrl(sentenceId); // } // // } // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/SentenceCollection.java import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import java.text.NumberFormat; import java.util.Locale; import info.puzz.a10000sentences.apimodels.CollectionType; package info.puzz.a10000sentences.models; @Table(name = "sentence_collection") public class SentenceCollection extends Model { private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(Locale.US); public static final int MAX_SENTENCES = 10_000; @Column(name = "collection_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) public String collectionID; @Column(name = "known_lang") public String knownLanguage; @Column(name = "target_lang") public String targetLanguage; @Column(name = "filename") public String filename; @Column(name = "count") public int count; @Column(name = "todo_count") public int todoCount; @Column(name = "repeat_count") public int repeatCount; @Column(name = "done_count") public int doneCount; @Column(name = "ignore_count") public int ignoreCount; @Column(name = "skipped_count") public int skippedCount; @Column(name = "annotation_count") public int annotationCount; @Column(name="type")
public CollectionType type;
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/logic/StatsService.java
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/SentenceHistory.java // @Data // @Accessors(chain = true) // @ToString // @Table(name = "sentence_history") // public class SentenceHistory extends Model { // // @Column(name = "sentence_id", index = true) // public String sentenceId; // // @Column(name = "collection_id") // public String collectionId; // // /** New status */ // @Column(name = "status") // public int status; // // @Column(name = "previous_status") // public int previousStatus; // // /** // * Time spend on this quiz // */ // @Column(name = "time") // public int time; // // @Column(name = "todo_count") // public int todoCount; // // @Column(name = "repeat_count") // public int repeatCount; // // @Column(name = "done_count") // public int doneCount; // // @Column(name = "ignore_count") // public int ignoreCount; // // @Column(name = "created", index = true) // public long created; // }
import com.activeandroid.query.Select; import com.jjoe64.graphview.series.DataPointInterface; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import info.puzz.a10000sentences.models.SentenceHistory;
Iterator<List<DataPoint>> i = donePerDay.values().iterator(); while (i.hasNext()) { List<DataPoint> values = i.next(); double minValue = Double.MAX_VALUE; for (DataPoint value : values) { if (value.y < minValue) { minValue = value.y; } } if (minValue == Double.MAX_VALUE) { minValue = 0; } for (DataPoint value : values) { value.y -= minValue; } } return donePerDay; } } public StatsService() { } public Stats getStats(int daysAgo) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -daysAgo); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0);
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/SentenceHistory.java // @Data // @Accessors(chain = true) // @ToString // @Table(name = "sentence_history") // public class SentenceHistory extends Model { // // @Column(name = "sentence_id", index = true) // public String sentenceId; // // @Column(name = "collection_id") // public String collectionId; // // /** New status */ // @Column(name = "status") // public int status; // // @Column(name = "previous_status") // public int previousStatus; // // /** // * Time spend on this quiz // */ // @Column(name = "time") // public int time; // // @Column(name = "todo_count") // public int todoCount; // // @Column(name = "repeat_count") // public int repeatCount; // // @Column(name = "done_count") // public int doneCount; // // @Column(name = "ignore_count") // public int ignoreCount; // // @Column(name = "created", index = true) // public long created; // } // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/logic/StatsService.java import com.activeandroid.query.Select; import com.jjoe64.graphview.series.DataPointInterface; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import info.puzz.a10000sentences.models.SentenceHistory; Iterator<List<DataPoint>> i = donePerDay.values().iterator(); while (i.hasNext()) { List<DataPoint> values = i.next(); double minValue = Double.MAX_VALUE; for (DataPoint value : values) { if (value.y < minValue) { minValue = value.y; } } if (minValue == Double.MAX_VALUE) { minValue = 0; } for (DataPoint value : values) { value.y -= minValue; } } return donePerDay; } } public StatsService() { } public Stats getStats(int daysAgo) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -daysAgo); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0);
List<SentenceHistory> history = new Select()
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/api/SentencesService.java
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/InfoVO.java // @Data // @Accessors(chain = true) // @ToString // public class InfoVO { // List<LanguageVO> languages; // List<SentenceCollectionVO> sentenceCollections; // // public InfoVO() { // super(); // } // // public InfoVO addSentencesCollection(SentenceCollectionVO sentenceCollection) { // if (this.sentenceCollections == null) { // this.sentenceCollections = new ArrayList<>(); // } // this.sentenceCollections.add(sentenceCollection); // return this; // } // // // public List<LanguageVO> getLanguages() { // return languages; // } // // public InfoVO setLanguages(List<LanguageVO> languages) { // this.languages = languages; // return this; // } // // public List<SentenceCollectionVO> getSentenceCollections() { // return sentenceCollections; // } // // public InfoVO setSentenceCollections(List<SentenceCollectionVO> sentenceCollections) { // this.sentenceCollections = sentenceCollections; // return this; // } // }
import info.puzz.a10000sentences.apimodels.InfoVO; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query;
package info.puzz.a10000sentences.api; public interface SentencesService { @GET("info.json")
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/InfoVO.java // @Data // @Accessors(chain = true) // @ToString // public class InfoVO { // List<LanguageVO> languages; // List<SentenceCollectionVO> sentenceCollections; // // public InfoVO() { // super(); // } // // public InfoVO addSentencesCollection(SentenceCollectionVO sentenceCollection) { // if (this.sentenceCollections == null) { // this.sentenceCollections = new ArrayList<>(); // } // this.sentenceCollections.add(sentenceCollection); // return this; // } // // // public List<LanguageVO> getLanguages() { // return languages; // } // // public InfoVO setLanguages(List<LanguageVO> languages) { // this.languages = languages; // return this; // } // // public List<SentenceCollectionVO> getSentenceCollections() { // return sentenceCollections; // } // // public InfoVO setSentenceCollections(List<SentenceCollectionVO> sentenceCollections) { // this.sentenceCollections = sentenceCollections; // return this; // } // } // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/api/SentencesService.java import info.puzz.a10000sentences.apimodels.InfoVO; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; package info.puzz.a10000sentences.api; public interface SentencesService { @GET("info.json")
Call<InfoVO> info(@Query("random") int random);
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/Preferences.java
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/utils/NumberUtils.java // public class NumberUtils { // private NumberUtils() throws Exception { // throw new Exception(); // } // // public static int parseInt(String s, int def) { // try { // return Integer.parseInt(s); // } catch (Exception e) { // return def; // } // } // }
import android.content.Context; import android.preference.PreferenceManager; import info.puzz.a10000sentences.utils.NumberUtils;
package info.puzz.a10000sentences; public final class Preferences { public static final String USE_TTS = "use_tts"; public static final String MAX_REPEAT = "max_repeat"; public static final String MIN_CORRECT_WORDS = "min_correct_words"; public static boolean isUseTTS(Context context) { return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(USE_TTS, true); } public static int getMaxRepeat(Context context) { int dflt = 10;
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/utils/NumberUtils.java // public class NumberUtils { // private NumberUtils() throws Exception { // throw new Exception(); // } // // public static int parseInt(String s, int def) { // try { // return Integer.parseInt(s); // } catch (Exception e) { // return def; // } // } // } // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/Preferences.java import android.content.Context; import android.preference.PreferenceManager; import info.puzz.a10000sentences.utils.NumberUtils; package info.puzz.a10000sentences; public final class Preferences { public static final String USE_TTS = "use_tts"; public static final String MAX_REPEAT = "max_repeat"; public static final String MIN_CORRECT_WORDS = "min_correct_words"; public static boolean isUseTTS(Context context) { return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(USE_TTS, true); } public static int getMaxRepeat(Context context) { int dflt = 10;
int repeat = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MAX_REPEAT, String.valueOf(dflt)), dflt);
tkrajina/10000sentences
tatoebaimporter/src/main/java/info/puzz/a10000sentences/importer/importers/SentenceWriter.java
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/SentenceVO.java // @Data // @Accessors(chain = true) // @ToString // public class SentenceVO { // String sentenceId; // /** // * This field is not sent to the client, it is used only for ordering when exporting sentences. // * This field cannot be unique, because the same sentenceId can be part of multiple collections. // * @see #sentenceId // */ // int targetSentenceId; // String knownSentence; // String targetSentence; // // /** // * Calculated based on sentence length and words frequency. // */ // float complexity; // // public String getSentenceId() { // return sentenceId; // } // // public SentenceVO setSentenceId(String sentenceId) { // this.sentenceId = sentenceId; // return this; // } // // public int getTargetSentenceId() { // return targetSentenceId; // } // // public SentenceVO setTargetSentenceId(int targetSentenceId) { // this.targetSentenceId = targetSentenceId; // return this; // } // // public String getKnownSentence() { // return knownSentence; // } // // public SentenceVO setKnownSentence(String knownSentence) { // this.knownSentence = knownSentence; // return this; // } // // public String getTargetSentence() { // return targetSentence; // } // // public SentenceVO setTargetSentence(String targetSentence) { // this.targetSentence = targetSentence; // return this; // } // // public float getComplexity() { // return complexity; // } // // public SentenceVO setComplexity(float complexity) { // this.complexity = complexity; // return this; // } // }
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import info.puzz.a10000sentences.apimodels.SentenceVO;
package info.puzz.a10000sentences.importer.importers; public class SentenceWriter { FileOutputStream out; final String filename; int counter = 0; public SentenceWriter(String filename) throws FileNotFoundException { this.filename = filename; out = new FileOutputStream(filename); }
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/SentenceVO.java // @Data // @Accessors(chain = true) // @ToString // public class SentenceVO { // String sentenceId; // /** // * This field is not sent to the client, it is used only for ordering when exporting sentences. // * This field cannot be unique, because the same sentenceId can be part of multiple collections. // * @see #sentenceId // */ // int targetSentenceId; // String knownSentence; // String targetSentence; // // /** // * Calculated based on sentence length and words frequency. // */ // float complexity; // // public String getSentenceId() { // return sentenceId; // } // // public SentenceVO setSentenceId(String sentenceId) { // this.sentenceId = sentenceId; // return this; // } // // public int getTargetSentenceId() { // return targetSentenceId; // } // // public SentenceVO setTargetSentenceId(int targetSentenceId) { // this.targetSentenceId = targetSentenceId; // return this; // } // // public String getKnownSentence() { // return knownSentence; // } // // public SentenceVO setKnownSentence(String knownSentence) { // this.knownSentence = knownSentence; // return this; // } // // public String getTargetSentence() { // return targetSentence; // } // // public SentenceVO setTargetSentence(String targetSentence) { // this.targetSentence = targetSentence; // return this; // } // // public float getComplexity() { // return complexity; // } // // public SentenceVO setComplexity(float complexity) { // this.complexity = complexity; // return this; // } // } // Path: tatoebaimporter/src/main/java/info/puzz/a10000sentences/importer/importers/SentenceWriter.java import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import info.puzz.a10000sentences.apimodels.SentenceVO; package info.puzz.a10000sentences.importer.importers; public class SentenceWriter { FileOutputStream out; final String filename; int counter = 0; public SentenceWriter(String filename) throws FileNotFoundException { this.filename = filename; out = new FileOutputStream(filename); }
public void writeSentence(SentenceVO sentence) throws Exception {
tkrajina/10000sentences
tatoebaimporter/src/main/java/info/puzz/a10000sentences/importer/WordCounter.java
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/LanguageVO.java // @Data // @Accessors(chain = true) // @ToString // public class LanguageVO { // String abbrev; // String abbrev3; // String family; // String name; // String nativeName; // boolean rightToLeft; // // public String getAbbrev() { // return abbrev; // } // // public LanguageVO setAbbrev(String abbrev) { // this.abbrev = abbrev; // return this; // } // // public String getAbbrev3() { // return abbrev3; // } // // public LanguageVO setAbbrev3(String abbrev3) { // this.abbrev3 = abbrev3; // return this; // } // // public String getFamily() { // return family; // } // // public LanguageVO setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public LanguageVO setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public LanguageVO setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public LanguageVO setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // } // // Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/SentenceVO.java // @Data // @Accessors(chain = true) // @ToString // public class SentenceVO { // String sentenceId; // /** // * This field is not sent to the client, it is used only for ordering when exporting sentences. // * This field cannot be unique, because the same sentenceId can be part of multiple collections. // * @see #sentenceId // */ // int targetSentenceId; // String knownSentence; // String targetSentence; // // /** // * Calculated based on sentence length and words frequency. // */ // float complexity; // // public String getSentenceId() { // return sentenceId; // } // // public SentenceVO setSentenceId(String sentenceId) { // this.sentenceId = sentenceId; // return this; // } // // public int getTargetSentenceId() { // return targetSentenceId; // } // // public SentenceVO setTargetSentenceId(int targetSentenceId) { // this.targetSentenceId = targetSentenceId; // return this; // } // // public String getKnownSentence() { // return knownSentence; // } // // public SentenceVO setKnownSentence(String knownSentence) { // this.knownSentence = knownSentence; // return this; // } // // public String getTargetSentence() { // return targetSentence; // } // // public SentenceVO setTargetSentence(String targetSentence) { // this.targetSentence = targetSentence; // return this; // } // // public float getComplexity() { // return complexity; // } // // public SentenceVO setComplexity(float complexity) { // this.complexity = complexity; // return this; // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import info.puzz.a10000sentences.apimodels.LanguageVO; import info.puzz.a10000sentences.apimodels.SentenceVO; import lombok.Getter;
package info.puzz.a10000sentences.importer; /** * Helper for counting words (frequencies) in a collection. */ public class WordCounter { @Getter AtomicInteger count = new AtomicInteger(0); final Map<String, AtomicInteger> wordCounter = new HashMap<>(); public WordCounter() { }
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/LanguageVO.java // @Data // @Accessors(chain = true) // @ToString // public class LanguageVO { // String abbrev; // String abbrev3; // String family; // String name; // String nativeName; // boolean rightToLeft; // // public String getAbbrev() { // return abbrev; // } // // public LanguageVO setAbbrev(String abbrev) { // this.abbrev = abbrev; // return this; // } // // public String getAbbrev3() { // return abbrev3; // } // // public LanguageVO setAbbrev3(String abbrev3) { // this.abbrev3 = abbrev3; // return this; // } // // public String getFamily() { // return family; // } // // public LanguageVO setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public LanguageVO setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public LanguageVO setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public LanguageVO setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // } // // Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/SentenceVO.java // @Data // @Accessors(chain = true) // @ToString // public class SentenceVO { // String sentenceId; // /** // * This field is not sent to the client, it is used only for ordering when exporting sentences. // * This field cannot be unique, because the same sentenceId can be part of multiple collections. // * @see #sentenceId // */ // int targetSentenceId; // String knownSentence; // String targetSentence; // // /** // * Calculated based on sentence length and words frequency. // */ // float complexity; // // public String getSentenceId() { // return sentenceId; // } // // public SentenceVO setSentenceId(String sentenceId) { // this.sentenceId = sentenceId; // return this; // } // // public int getTargetSentenceId() { // return targetSentenceId; // } // // public SentenceVO setTargetSentenceId(int targetSentenceId) { // this.targetSentenceId = targetSentenceId; // return this; // } // // public String getKnownSentence() { // return knownSentence; // } // // public SentenceVO setKnownSentence(String knownSentence) { // this.knownSentence = knownSentence; // return this; // } // // public String getTargetSentence() { // return targetSentence; // } // // public SentenceVO setTargetSentence(String targetSentence) { // this.targetSentence = targetSentence; // return this; // } // // public float getComplexity() { // return complexity; // } // // public SentenceVO setComplexity(float complexity) { // this.complexity = complexity; // return this; // } // } // Path: tatoebaimporter/src/main/java/info/puzz/a10000sentences/importer/WordCounter.java import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import info.puzz.a10000sentences.apimodels.LanguageVO; import info.puzz.a10000sentences.apimodels.SentenceVO; import lombok.Getter; package info.puzz.a10000sentences.importer; /** * Helper for counting words (frequencies) in a collection. */ public class WordCounter { @Getter AtomicInteger count = new AtomicInteger(0); final Map<String, AtomicInteger> wordCounter = new HashMap<>(); public WordCounter() { }
public void countWordsInSentence(SentenceVO sentence, LanguageVO knownLang, LanguageVO targetLang) {
tkrajina/10000sentences
tatoebaimporter/src/main/java/info/puzz/a10000sentences/importer/WordCounter.java
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/LanguageVO.java // @Data // @Accessors(chain = true) // @ToString // public class LanguageVO { // String abbrev; // String abbrev3; // String family; // String name; // String nativeName; // boolean rightToLeft; // // public String getAbbrev() { // return abbrev; // } // // public LanguageVO setAbbrev(String abbrev) { // this.abbrev = abbrev; // return this; // } // // public String getAbbrev3() { // return abbrev3; // } // // public LanguageVO setAbbrev3(String abbrev3) { // this.abbrev3 = abbrev3; // return this; // } // // public String getFamily() { // return family; // } // // public LanguageVO setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public LanguageVO setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public LanguageVO setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public LanguageVO setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // } // // Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/SentenceVO.java // @Data // @Accessors(chain = true) // @ToString // public class SentenceVO { // String sentenceId; // /** // * This field is not sent to the client, it is used only for ordering when exporting sentences. // * This field cannot be unique, because the same sentenceId can be part of multiple collections. // * @see #sentenceId // */ // int targetSentenceId; // String knownSentence; // String targetSentence; // // /** // * Calculated based on sentence length and words frequency. // */ // float complexity; // // public String getSentenceId() { // return sentenceId; // } // // public SentenceVO setSentenceId(String sentenceId) { // this.sentenceId = sentenceId; // return this; // } // // public int getTargetSentenceId() { // return targetSentenceId; // } // // public SentenceVO setTargetSentenceId(int targetSentenceId) { // this.targetSentenceId = targetSentenceId; // return this; // } // // public String getKnownSentence() { // return knownSentence; // } // // public SentenceVO setKnownSentence(String knownSentence) { // this.knownSentence = knownSentence; // return this; // } // // public String getTargetSentence() { // return targetSentence; // } // // public SentenceVO setTargetSentence(String targetSentence) { // this.targetSentence = targetSentence; // return this; // } // // public float getComplexity() { // return complexity; // } // // public SentenceVO setComplexity(float complexity) { // this.complexity = complexity; // return this; // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import info.puzz.a10000sentences.apimodels.LanguageVO; import info.puzz.a10000sentences.apimodels.SentenceVO; import lombok.Getter;
package info.puzz.a10000sentences.importer; /** * Helper for counting words (frequencies) in a collection. */ public class WordCounter { @Getter AtomicInteger count = new AtomicInteger(0); final Map<String, AtomicInteger> wordCounter = new HashMap<>(); public WordCounter() { }
// Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/LanguageVO.java // @Data // @Accessors(chain = true) // @ToString // public class LanguageVO { // String abbrev; // String abbrev3; // String family; // String name; // String nativeName; // boolean rightToLeft; // // public String getAbbrev() { // return abbrev; // } // // public LanguageVO setAbbrev(String abbrev) { // this.abbrev = abbrev; // return this; // } // // public String getAbbrev3() { // return abbrev3; // } // // public LanguageVO setAbbrev3(String abbrev3) { // this.abbrev3 = abbrev3; // return this; // } // // public String getFamily() { // return family; // } // // public LanguageVO setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public LanguageVO setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public LanguageVO setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public LanguageVO setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // } // // Path: apimodels/src/main/java/info/puzz/a10000sentences/apimodels/SentenceVO.java // @Data // @Accessors(chain = true) // @ToString // public class SentenceVO { // String sentenceId; // /** // * This field is not sent to the client, it is used only for ordering when exporting sentences. // * This field cannot be unique, because the same sentenceId can be part of multiple collections. // * @see #sentenceId // */ // int targetSentenceId; // String knownSentence; // String targetSentence; // // /** // * Calculated based on sentence length and words frequency. // */ // float complexity; // // public String getSentenceId() { // return sentenceId; // } // // public SentenceVO setSentenceId(String sentenceId) { // this.sentenceId = sentenceId; // return this; // } // // public int getTargetSentenceId() { // return targetSentenceId; // } // // public SentenceVO setTargetSentenceId(int targetSentenceId) { // this.targetSentenceId = targetSentenceId; // return this; // } // // public String getKnownSentence() { // return knownSentence; // } // // public SentenceVO setKnownSentence(String knownSentence) { // this.knownSentence = knownSentence; // return this; // } // // public String getTargetSentence() { // return targetSentence; // } // // public SentenceVO setTargetSentence(String targetSentence) { // this.targetSentence = targetSentence; // return this; // } // // public float getComplexity() { // return complexity; // } // // public SentenceVO setComplexity(float complexity) { // this.complexity = complexity; // return this; // } // } // Path: tatoebaimporter/src/main/java/info/puzz/a10000sentences/importer/WordCounter.java import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import info.puzz.a10000sentences.apimodels.LanguageVO; import info.puzz.a10000sentences.apimodels.SentenceVO; import lombok.Getter; package info.puzz.a10000sentences.importer; /** * Helper for counting words (frequencies) in a collection. */ public class WordCounter { @Getter AtomicInteger count = new AtomicInteger(0); final Map<String, AtomicInteger> wordCounter = new HashMap<>(); public WordCounter() { }
public void countWordsInSentence(SentenceVO sentence, LanguageVO knownLang, LanguageVO targetLang) {
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/utils/Speech.java
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/Preferences.java // public final class Preferences { // public static final String USE_TTS = "use_tts"; // public static final String MAX_REPEAT = "max_repeat"; // public static final String MIN_CORRECT_WORDS = "min_correct_words"; // // public static boolean isUseTTS(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(USE_TTS, true); // } // // public static int getMaxRepeat(Context context) { // int dflt = 10; // int repeat = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MAX_REPEAT, String.valueOf(dflt)), dflt); // if (repeat < 1) { // return 3; // } // return repeat; // } // // public static int getMinCorrectWords(Context context) { // int dflt = 90; // int mcw = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MIN_CORRECT_WORDS, String.valueOf(dflt)), dflt); // if (mcw < 0) { // return 0; // } // if (mcw > 100) { // return 100; // } // return mcw; // } // } // // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/Language.java // @Table(name = "language") // public class Language extends Model { // @Column(name = "language_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) // public String languageId; // // @Column(name = "family") // public String family; // // @Column(name = "name") // public String name; // // @Column(name = "native_name") // public String nativeName; // // @Column(name = "rtl") // boolean rightToLeft; // // public String formatNativeName(String delimiter) { // String[] parts; // if (nativeName.contains(",")) { // parts = StringUtils.capitalize(nativeName.split(",")[0]).split("\\s+"); // } else { // parts = StringUtils.capitalize(nativeName).split("\\s+"); // } // return StringUtils.join(parts, delimiter); // } // // public String formatNameAndNativeName() { // if (StringUtils.equals(name, nativeName)) { // return name; // } // return name + " / " + nativeName; // } // // public String getLanguageId() { // return languageId; // } // // public Language setLanguageId(String languageId) { // this.languageId = languageId; // return this; // } // // public String getFamily() { // return family; // } // // public Language setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public Language setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public Language setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public Language setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // }
import android.content.Context; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.widget.Toast; import org.apache.commons.lang3.*; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Set; import info.puzz.a10000sentences.Preferences; import info.puzz.a10000sentences.R; import info.puzz.a10000sentences.models.Language; import lombok.Getter;
package info.puzz.a10000sentences.utils; public class Speech { private static final String TAG = Speech.class.getSimpleName(); private TextToSpeech tts; private final Context context; private final Locale locale; private final boolean languageFound; private final boolean enabled; private final Set<Integer> toastMessagesShown = new HashSet<>(); @Getter private boolean initialized = false;
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/Preferences.java // public final class Preferences { // public static final String USE_TTS = "use_tts"; // public static final String MAX_REPEAT = "max_repeat"; // public static final String MIN_CORRECT_WORDS = "min_correct_words"; // // public static boolean isUseTTS(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(USE_TTS, true); // } // // public static int getMaxRepeat(Context context) { // int dflt = 10; // int repeat = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MAX_REPEAT, String.valueOf(dflt)), dflt); // if (repeat < 1) { // return 3; // } // return repeat; // } // // public static int getMinCorrectWords(Context context) { // int dflt = 90; // int mcw = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MIN_CORRECT_WORDS, String.valueOf(dflt)), dflt); // if (mcw < 0) { // return 0; // } // if (mcw > 100) { // return 100; // } // return mcw; // } // } // // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/Language.java // @Table(name = "language") // public class Language extends Model { // @Column(name = "language_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) // public String languageId; // // @Column(name = "family") // public String family; // // @Column(name = "name") // public String name; // // @Column(name = "native_name") // public String nativeName; // // @Column(name = "rtl") // boolean rightToLeft; // // public String formatNativeName(String delimiter) { // String[] parts; // if (nativeName.contains(",")) { // parts = StringUtils.capitalize(nativeName.split(",")[0]).split("\\s+"); // } else { // parts = StringUtils.capitalize(nativeName).split("\\s+"); // } // return StringUtils.join(parts, delimiter); // } // // public String formatNameAndNativeName() { // if (StringUtils.equals(name, nativeName)) { // return name; // } // return name + " / " + nativeName; // } // // public String getLanguageId() { // return languageId; // } // // public Language setLanguageId(String languageId) { // this.languageId = languageId; // return this; // } // // public String getFamily() { // return family; // } // // public Language setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public Language setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public Language setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public Language setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // } // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/utils/Speech.java import android.content.Context; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.widget.Toast; import org.apache.commons.lang3.*; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Set; import info.puzz.a10000sentences.Preferences; import info.puzz.a10000sentences.R; import info.puzz.a10000sentences.models.Language; import lombok.Getter; package info.puzz.a10000sentences.utils; public class Speech { private static final String TAG = Speech.class.getSimpleName(); private TextToSpeech tts; private final Context context; private final Locale locale; private final boolean languageFound; private final boolean enabled; private final Set<Integer> toastMessagesShown = new HashSet<>(); @Getter private boolean initialized = false;
public Speech(Context context, Language language) {
tkrajina/10000sentences
10000sentencesapp/src/main/java/info/puzz/a10000sentences/utils/Speech.java
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/Preferences.java // public final class Preferences { // public static final String USE_TTS = "use_tts"; // public static final String MAX_REPEAT = "max_repeat"; // public static final String MIN_CORRECT_WORDS = "min_correct_words"; // // public static boolean isUseTTS(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(USE_TTS, true); // } // // public static int getMaxRepeat(Context context) { // int dflt = 10; // int repeat = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MAX_REPEAT, String.valueOf(dflt)), dflt); // if (repeat < 1) { // return 3; // } // return repeat; // } // // public static int getMinCorrectWords(Context context) { // int dflt = 90; // int mcw = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MIN_CORRECT_WORDS, String.valueOf(dflt)), dflt); // if (mcw < 0) { // return 0; // } // if (mcw > 100) { // return 100; // } // return mcw; // } // } // // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/Language.java // @Table(name = "language") // public class Language extends Model { // @Column(name = "language_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) // public String languageId; // // @Column(name = "family") // public String family; // // @Column(name = "name") // public String name; // // @Column(name = "native_name") // public String nativeName; // // @Column(name = "rtl") // boolean rightToLeft; // // public String formatNativeName(String delimiter) { // String[] parts; // if (nativeName.contains(",")) { // parts = StringUtils.capitalize(nativeName.split(",")[0]).split("\\s+"); // } else { // parts = StringUtils.capitalize(nativeName).split("\\s+"); // } // return StringUtils.join(parts, delimiter); // } // // public String formatNameAndNativeName() { // if (StringUtils.equals(name, nativeName)) { // return name; // } // return name + " / " + nativeName; // } // // public String getLanguageId() { // return languageId; // } // // public Language setLanguageId(String languageId) { // this.languageId = languageId; // return this; // } // // public String getFamily() { // return family; // } // // public Language setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public Language setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public Language setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public Language setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // }
import android.content.Context; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.widget.Toast; import org.apache.commons.lang3.*; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Set; import info.puzz.a10000sentences.Preferences; import info.puzz.a10000sentences.R; import info.puzz.a10000sentences.models.Language; import lombok.Getter;
package info.puzz.a10000sentences.utils; public class Speech { private static final String TAG = Speech.class.getSimpleName(); private TextToSpeech tts; private final Context context; private final Locale locale; private final boolean languageFound; private final boolean enabled; private final Set<Integer> toastMessagesShown = new HashSet<>(); @Getter private boolean initialized = false; public Speech(Context context, Language language) { this.context = context; this.locale = findLocale(language); this.languageFound = locale != null;
// Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/Preferences.java // public final class Preferences { // public static final String USE_TTS = "use_tts"; // public static final String MAX_REPEAT = "max_repeat"; // public static final String MIN_CORRECT_WORDS = "min_correct_words"; // // public static boolean isUseTTS(Context context) { // return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(USE_TTS, true); // } // // public static int getMaxRepeat(Context context) { // int dflt = 10; // int repeat = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MAX_REPEAT, String.valueOf(dflt)), dflt); // if (repeat < 1) { // return 3; // } // return repeat; // } // // public static int getMinCorrectWords(Context context) { // int dflt = 90; // int mcw = NumberUtils.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString(MIN_CORRECT_WORDS, String.valueOf(dflt)), dflt); // if (mcw < 0) { // return 0; // } // if (mcw > 100) { // return 100; // } // return mcw; // } // } // // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/models/Language.java // @Table(name = "language") // public class Language extends Model { // @Column(name = "language_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) // public String languageId; // // @Column(name = "family") // public String family; // // @Column(name = "name") // public String name; // // @Column(name = "native_name") // public String nativeName; // // @Column(name = "rtl") // boolean rightToLeft; // // public String formatNativeName(String delimiter) { // String[] parts; // if (nativeName.contains(",")) { // parts = StringUtils.capitalize(nativeName.split(",")[0]).split("\\s+"); // } else { // parts = StringUtils.capitalize(nativeName).split("\\s+"); // } // return StringUtils.join(parts, delimiter); // } // // public String formatNameAndNativeName() { // if (StringUtils.equals(name, nativeName)) { // return name; // } // return name + " / " + nativeName; // } // // public String getLanguageId() { // return languageId; // } // // public Language setLanguageId(String languageId) { // this.languageId = languageId; // return this; // } // // public String getFamily() { // return family; // } // // public Language setFamily(String family) { // this.family = family; // return this; // } // // public String getName() { // return name; // } // // public Language setName(String name) { // this.name = name; // return this; // } // // public String getNativeName() { // return nativeName; // } // // public Language setNativeName(String nativeName) { // this.nativeName = nativeName; // return this; // } // // public boolean isRightToLeft() { // return rightToLeft; // } // // public Language setRightToLeft(boolean rightToLeft) { // this.rightToLeft = rightToLeft; // return this; // } // } // Path: 10000sentencesapp/src/main/java/info/puzz/a10000sentences/utils/Speech.java import android.content.Context; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.widget.Toast; import org.apache.commons.lang3.*; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Set; import info.puzz.a10000sentences.Preferences; import info.puzz.a10000sentences.R; import info.puzz.a10000sentences.models.Language; import lombok.Getter; package info.puzz.a10000sentences.utils; public class Speech { private static final String TAG = Speech.class.getSimpleName(); private TextToSpeech tts; private final Context context; private final Locale locale; private final boolean languageFound; private final boolean enabled; private final Set<Integer> toastMessagesShown = new HashSet<>(); @Getter private boolean initialized = false; public Speech(Context context, Language language) { this.context = context; this.locale = findLocale(language); this.languageFound = locale != null;
this.enabled = Preferences.isUseTTS(context);
oasisfeng/deagle
library/src/main/java/com/oasisfeng/android/content/pm/PackageManagerCompat.java
// Path: library/src/main/java/com/oasisfeng/android/os/UserHandles.java // public class UserHandles { // // public static final UserHandle MY_USER_HANDLE = Process.myUserHandle(); // public static final int MY_USER_ID = getIdentifier(Process.myUserHandle()); // // @VisibleForTesting static Pair<Integer, UserHandle> sCache = null; // Must before SYSTEM. TODO: Support multiple profiles. // // /** // * Enable multi-user related side effects. Set this to false if // * there are problems with single user use-cases. // */ // private static final boolean MU_ENABLED = true; // // /** // * Range of uids allocated for a user. // */ // private static final int PER_USER_RANGE = 100000; // // /** A user id constant to indicate the "system" user of the device */ // public static final @UserIdInt int USER_SYSTEM = 0; // // /** A user handle to indicate the "system" user of the device */ // public static final UserHandle SYSTEM = from(USER_SYSTEM); // // public static UserHandle getUserHandleForUid(final int uid) { // return SDK_INT >= N ? UserHandle.getUserHandleForUid(uid) : of(getUserId(uid)); // } // // public static UserHandle of(final @UserIdInt int user_id) { // if (user_id == USER_SYSTEM) return SYSTEM; // final Pair<Integer, UserHandle> cache = sCache; // if (cache != null && cache.first == user_id) return cache.second; // final UserHandle user = from(user_id); // sCache = new Pair<>(user_id, user); // return user; // } // // private static UserHandle from(final @UserIdInt int user_id) { // if (MY_USER_HANDLE.hashCode() == user_id) return MY_USER_HANDLE; // final Parcel parcel = Parcel.obtain(); // try { // final int begin = parcel.dataPosition(); // parcel.writeInt(user_id); // parcel.setDataPosition(begin); // return UserHandle.CREATOR.createFromParcel(parcel); // } finally { // parcel.recycle(); // } // } // // /** // * Returns the user id for a given uid. // */ // public static @UserIdInt int getUserId(final int uid) { // if (MU_ENABLED) { // return uid / PER_USER_RANGE; // } else { // return USER_SYSTEM; // } // } // // /** // * Returns the app id (or base uid) for a given uid, stripping out the user id from it. // */ // public static @AppIdInt int getAppId(final int uid) { // return uid % PER_USER_RANGE; // } // // /** // * Returns the uid that is composed from the userId and the appId. // */ // public static int getUid(final @UserIdInt int userId, final @AppIdInt int appId) { // if (MU_ENABLED) { // return userId * PER_USER_RANGE + (appId % PER_USER_RANGE); // } else { // return appId; // } // } // // /** // * Returns the userId stored in this UserHandle. (same as UserHandle.getIdentifier()) // */ // public static @UserIdInt int getIdentifier(final UserHandle handle) { // return handle.hashCode(); // So far so good // } // }
import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.os.Process; import com.oasisfeng.android.os.UserHandles; import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.N;
package com.oasisfeng.android.content.pm; /** * Created by Oasis on 2019-2-12. */ public class PackageManagerCompat { @SuppressLint("NewApi") public int getPackageUid(final String pkg) throws PackageManager.NameNotFoundException { if (SDK_INT >= N) return mPackageManager.getPackageUid(pkg, MATCH_UNINSTALLED_PACKAGES | MATCH_DISABLED_COMPONENTS); // API 18 - 23: public int getPackageUid(String packageName, int userHandle)
// Path: library/src/main/java/com/oasisfeng/android/os/UserHandles.java // public class UserHandles { // // public static final UserHandle MY_USER_HANDLE = Process.myUserHandle(); // public static final int MY_USER_ID = getIdentifier(Process.myUserHandle()); // // @VisibleForTesting static Pair<Integer, UserHandle> sCache = null; // Must before SYSTEM. TODO: Support multiple profiles. // // /** // * Enable multi-user related side effects. Set this to false if // * there are problems with single user use-cases. // */ // private static final boolean MU_ENABLED = true; // // /** // * Range of uids allocated for a user. // */ // private static final int PER_USER_RANGE = 100000; // // /** A user id constant to indicate the "system" user of the device */ // public static final @UserIdInt int USER_SYSTEM = 0; // // /** A user handle to indicate the "system" user of the device */ // public static final UserHandle SYSTEM = from(USER_SYSTEM); // // public static UserHandle getUserHandleForUid(final int uid) { // return SDK_INT >= N ? UserHandle.getUserHandleForUid(uid) : of(getUserId(uid)); // } // // public static UserHandle of(final @UserIdInt int user_id) { // if (user_id == USER_SYSTEM) return SYSTEM; // final Pair<Integer, UserHandle> cache = sCache; // if (cache != null && cache.first == user_id) return cache.second; // final UserHandle user = from(user_id); // sCache = new Pair<>(user_id, user); // return user; // } // // private static UserHandle from(final @UserIdInt int user_id) { // if (MY_USER_HANDLE.hashCode() == user_id) return MY_USER_HANDLE; // final Parcel parcel = Parcel.obtain(); // try { // final int begin = parcel.dataPosition(); // parcel.writeInt(user_id); // parcel.setDataPosition(begin); // return UserHandle.CREATOR.createFromParcel(parcel); // } finally { // parcel.recycle(); // } // } // // /** // * Returns the user id for a given uid. // */ // public static @UserIdInt int getUserId(final int uid) { // if (MU_ENABLED) { // return uid / PER_USER_RANGE; // } else { // return USER_SYSTEM; // } // } // // /** // * Returns the app id (or base uid) for a given uid, stripping out the user id from it. // */ // public static @AppIdInt int getAppId(final int uid) { // return uid % PER_USER_RANGE; // } // // /** // * Returns the uid that is composed from the userId and the appId. // */ // public static int getUid(final @UserIdInt int userId, final @AppIdInt int appId) { // if (MU_ENABLED) { // return userId * PER_USER_RANGE + (appId % PER_USER_RANGE); // } else { // return appId; // } // } // // /** // * Returns the userId stored in this UserHandle. (same as UserHandle.getIdentifier()) // */ // public static @UserIdInt int getIdentifier(final UserHandle handle) { // return handle.hashCode(); // So far so good // } // } // Path: library/src/main/java/com/oasisfeng/android/content/pm/PackageManagerCompat.java import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.os.Process; import com.oasisfeng.android.os.UserHandles; import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.N; package com.oasisfeng.android.content.pm; /** * Created by Oasis on 2019-2-12. */ public class PackageManagerCompat { @SuppressLint("NewApi") public int getPackageUid(final String pkg) throws PackageManager.NameNotFoundException { if (SDK_INT >= N) return mPackageManager.getPackageUid(pkg, MATCH_UNINSTALLED_PACKAGES | MATCH_DISABLED_COMPONENTS); // API 18 - 23: public int getPackageUid(String packageName, int userHandle)
return mPackageManager.getPackageUid(pkg, UserHandles.getIdentifier(Process.myUserHandle()));
oasisfeng/deagle
library/src/test/java/com/oasisfeng/hack/HackTest.java
// Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public class Unchecked extends RuntimeException {} // // Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public static Class<?> ANY_TYPE = $.class; private static class $ {}
import com.oasisfeng.hack.Hack.Unchecked; import org.junit.Before; import org.junit.Test; import java.io.FileNotFoundException; import java.io.IOException; import static com.oasisfeng.hack.Hack.ANY_TYPE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail;
package com.oasisfeng.hack; /** * Test cases for {@link Hack} * * Created by Oasis on 2015/8/24. */ public class HackTest { @Test public void testBasicMethodAndConstructor() throws IOException {
// Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public class Unchecked extends RuntimeException {} // // Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public static Class<?> ANY_TYPE = $.class; private static class $ {} // Path: library/src/test/java/com/oasisfeng/hack/HackTest.java import com.oasisfeng.hack.Hack.Unchecked; import org.junit.Before; import org.junit.Test; import java.io.FileNotFoundException; import java.io.IOException; import static com.oasisfeng.hack.Hack.ANY_TYPE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; package com.oasisfeng.hack; /** * Test cases for {@link Hack} * * Created by Oasis on 2015/8/24. */ public class HackTest { @Test public void testBasicMethodAndConstructor() throws IOException {
final Hack.HackedMethod1<Simple, Void, IOException, Unchecked, Unchecked, Integer> constructor
oasisfeng/deagle
library/src/test/java/com/oasisfeng/hack/HackTest.java
// Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public class Unchecked extends RuntimeException {} // // Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public static Class<?> ANY_TYPE = $.class; private static class $ {}
import com.oasisfeng.hack.Hack.Unchecked; import org.junit.Before; import org.junit.Test; import java.io.FileNotFoundException; import java.io.IOException; import static com.oasisfeng.hack.Hack.ANY_TYPE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail;
final Hack.HackedMethod0<Integer, Simple, Unchecked, Unchecked, Unchecked> foo = Hack.into(Simple.class).method("foo").returning(int.class).withoutParams(); assertNotNull(foo); assertEquals(7, (int) foo.invoke().on(simple)); final Hack.HackedMethod0<Integer, Simple, RuntimeException, Unchecked, Unchecked> foo_rt_ex = Hack.into(Simple.class).method("foo").returning(int.class).throwing(RuntimeException.class).withoutParams(); assertNotNull(foo_rt_ex); assertEquals(7, (int) foo_rt_ex.invoke().on(simple)); final Hack.HackedMethod0<Integer, Simple, IOException, Unchecked, Unchecked> foo_ex = Hack.into(Simple.class).method("foo").returning(int.class).throwing(IOException.class).withoutParams(); assertNotNull(foo_ex); assertEquals(7, (int) foo_ex.invoke().on(simple)); final Hack.HackedMethod3<Void, Void, IOException, Unchecked, Unchecked, Integer, String, Simple> bar = Hack.into(Simple.class).staticMethod("bar").throwing(IOException.class).withParams(int.class, String.class, Simple.class); assertNotNull(bar); bar.invoke(-1, "xyz", simple).statically(); assertFail(null, Hack.into(Simple.class).method("bar").throwing(UnsupportedOperationException.class, FileNotFoundException.class).withParams(int.class, String.class, Simple.class)); assertFail(NoSuchMethodException.class, Hack.into(Simple.class).method("notExist").withoutParams()); assertFail(NoSuchMethodException.class, Hack.into(Simple.class).method("foo").withParam(int.class)); assertFail(null, Hack.into(Simple.class).staticMethod("foo").withoutParams()); assertFail(null, Hack.into(Simple.class).method("foo").returning(Void.class).withoutParams()); } @Test public void testMethodReturningAnyType() throws IOException { final Hack.HackedMethod0<?, Simple, Unchecked, Unchecked, Unchecked> foo
// Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public class Unchecked extends RuntimeException {} // // Path: library/src/main/java/com/oasisfeng/hack/Hack.java // public static Class<?> ANY_TYPE = $.class; private static class $ {} // Path: library/src/test/java/com/oasisfeng/hack/HackTest.java import com.oasisfeng.hack.Hack.Unchecked; import org.junit.Before; import org.junit.Test; import java.io.FileNotFoundException; import java.io.IOException; import static com.oasisfeng.hack.Hack.ANY_TYPE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; final Hack.HackedMethod0<Integer, Simple, Unchecked, Unchecked, Unchecked> foo = Hack.into(Simple.class).method("foo").returning(int.class).withoutParams(); assertNotNull(foo); assertEquals(7, (int) foo.invoke().on(simple)); final Hack.HackedMethod0<Integer, Simple, RuntimeException, Unchecked, Unchecked> foo_rt_ex = Hack.into(Simple.class).method("foo").returning(int.class).throwing(RuntimeException.class).withoutParams(); assertNotNull(foo_rt_ex); assertEquals(7, (int) foo_rt_ex.invoke().on(simple)); final Hack.HackedMethod0<Integer, Simple, IOException, Unchecked, Unchecked> foo_ex = Hack.into(Simple.class).method("foo").returning(int.class).throwing(IOException.class).withoutParams(); assertNotNull(foo_ex); assertEquals(7, (int) foo_ex.invoke().on(simple)); final Hack.HackedMethod3<Void, Void, IOException, Unchecked, Unchecked, Integer, String, Simple> bar = Hack.into(Simple.class).staticMethod("bar").throwing(IOException.class).withParams(int.class, String.class, Simple.class); assertNotNull(bar); bar.invoke(-1, "xyz", simple).statically(); assertFail(null, Hack.into(Simple.class).method("bar").throwing(UnsupportedOperationException.class, FileNotFoundException.class).withParams(int.class, String.class, Simple.class)); assertFail(NoSuchMethodException.class, Hack.into(Simple.class).method("notExist").withoutParams()); assertFail(NoSuchMethodException.class, Hack.into(Simple.class).method("foo").withParam(int.class)); assertFail(null, Hack.into(Simple.class).staticMethod("foo").withoutParams()); assertFail(null, Hack.into(Simple.class).method("foo").returning(Void.class).withoutParams()); } @Test public void testMethodReturningAnyType() throws IOException { final Hack.HackedMethod0<?, Simple, Unchecked, Unchecked, Unchecked> foo
= Hack.into(Simple.class).method("foo").returning(ANY_TYPE).withoutParams();
oasisfeng/deagle
library/src/main/java/com/oasisfeng/android/os/SimpleAsyncTask.java
// Path: library/src/main/java/com/oasisfeng/android/util/Consumer.java // public interface Consumer<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t); // } // // Path: library/src/main/java/com/oasisfeng/android/util/Supplier.java // public interface Supplier<T> { // // /** // * Gets a result. // * // * @return a result // */ // T get(); // }
import android.os.AsyncTask; import com.oasisfeng.android.util.Consumer; import com.oasisfeng.android.util.Supplier; import java.util.concurrent.Callable; import androidx.annotation.MainThread; import androidx.annotation.WorkerThread;
package com.oasisfeng.android.os; /** * Simplify the basic usage of {@link AsyncTask}. * * Created by Oasis on 2016/11/6. */ public abstract class SimpleAsyncTask extends AsyncTask<Void, Void, Void> { @MainThread public static void execute(final Runnable do_in_background, final Runnable on_post_execute) { new SimpleAsyncTask() { @Override protected void doInBackground() { do_in_background.run(); } @Override protected void onPostExecute() { on_post_execute.run(); } }.execute(); } /** Execute background task and deal with the result in post-execute procedure */
// Path: library/src/main/java/com/oasisfeng/android/util/Consumer.java // public interface Consumer<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t); // } // // Path: library/src/main/java/com/oasisfeng/android/util/Supplier.java // public interface Supplier<T> { // // /** // * Gets a result. // * // * @return a result // */ // T get(); // } // Path: library/src/main/java/com/oasisfeng/android/os/SimpleAsyncTask.java import android.os.AsyncTask; import com.oasisfeng.android.util.Consumer; import com.oasisfeng.android.util.Supplier; import java.util.concurrent.Callable; import androidx.annotation.MainThread; import androidx.annotation.WorkerThread; package com.oasisfeng.android.os; /** * Simplify the basic usage of {@link AsyncTask}. * * Created by Oasis on 2016/11/6. */ public abstract class SimpleAsyncTask extends AsyncTask<Void, Void, Void> { @MainThread public static void execute(final Runnable do_in_background, final Runnable on_post_execute) { new SimpleAsyncTask() { @Override protected void doInBackground() { do_in_background.run(); } @Override protected void onPostExecute() { on_post_execute.run(); } }.execute(); } /** Execute background task and deal with the result in post-execute procedure */
@MainThread public static <T> void execute(final Supplier<T> do_in_background, final Consumer<T> on_post_execute) {
oasisfeng/deagle
library/src/main/java/com/oasisfeng/android/os/SimpleAsyncTask.java
// Path: library/src/main/java/com/oasisfeng/android/util/Consumer.java // public interface Consumer<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t); // } // // Path: library/src/main/java/com/oasisfeng/android/util/Supplier.java // public interface Supplier<T> { // // /** // * Gets a result. // * // * @return a result // */ // T get(); // }
import android.os.AsyncTask; import com.oasisfeng.android.util.Consumer; import com.oasisfeng.android.util.Supplier; import java.util.concurrent.Callable; import androidx.annotation.MainThread; import androidx.annotation.WorkerThread;
package com.oasisfeng.android.os; /** * Simplify the basic usage of {@link AsyncTask}. * * Created by Oasis on 2016/11/6. */ public abstract class SimpleAsyncTask extends AsyncTask<Void, Void, Void> { @MainThread public static void execute(final Runnable do_in_background, final Runnable on_post_execute) { new SimpleAsyncTask() { @Override protected void doInBackground() { do_in_background.run(); } @Override protected void onPostExecute() { on_post_execute.run(); } }.execute(); } /** Execute background task and deal with the result in post-execute procedure */
// Path: library/src/main/java/com/oasisfeng/android/util/Consumer.java // public interface Consumer<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t); // } // // Path: library/src/main/java/com/oasisfeng/android/util/Supplier.java // public interface Supplier<T> { // // /** // * Gets a result. // * // * @return a result // */ // T get(); // } // Path: library/src/main/java/com/oasisfeng/android/os/SimpleAsyncTask.java import android.os.AsyncTask; import com.oasisfeng.android.util.Consumer; import com.oasisfeng.android.util.Supplier; import java.util.concurrent.Callable; import androidx.annotation.MainThread; import androidx.annotation.WorkerThread; package com.oasisfeng.android.os; /** * Simplify the basic usage of {@link AsyncTask}. * * Created by Oasis on 2016/11/6. */ public abstract class SimpleAsyncTask extends AsyncTask<Void, Void, Void> { @MainThread public static void execute(final Runnable do_in_background, final Runnable on_post_execute) { new SimpleAsyncTask() { @Override protected void doInBackground() { do_in_background.run(); } @Override protected void onPostExecute() { on_post_execute.run(); } }.execute(); } /** Execute background task and deal with the result in post-execute procedure */
@MainThread public static <T> void execute(final Supplier<T> do_in_background, final Consumer<T> on_post_execute) {
oasisfeng/deagle
library/src/main/java/com/oasisfeng/android/ui/AboutActivity.java
// Path: library/src/main/java/com/oasisfeng/android/google/GooglePlayStore.java // public class GooglePlayStore { // // public static final String PACKAGE_NAME = "com.android.vending"; // private static final String APP_URL_PREFIX = "https://play.google.com/store/apps/details?id="; // // public static void showApp(final Context context, final String pkg) { // final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_URL_PREFIX + pkg)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // updatePlayUrlIntent(context, intent); // try { // context.startActivity(intent); // } catch(final ActivityNotFoundException e) { /* In case of Google Play malfunction */ } // } // // public static void updatePreferenceIntent(final Context context, final Preference preference) { // final Intent intent = preference.getIntent(); // updatePlayUrlIntent(context, intent); // } // // /** Modify intent to launch Google Play Store directly if possible (without activity chooser) */ // private static void updatePlayUrlIntent(final Context context, final Intent intent) { // if (intent == null || intent.getPackage() != null) return; // Skip intent with explicit target package // final Uri uri = intent.getData(); // if (uri == null) return; // intent.setPackage(PACKAGE_NAME); // final ComponentName component = intent.resolveActivity(context.getPackageManager()); // if (component != null) intent.setComponent(component); // else intent.setPackage(null); // } // } // // Path: library/src/main/java/com/oasisfeng/android/i18n/Locales.java // public class Locales { // // public static Locale getFrom(final Context context) { // return context.getResources().getConfiguration().locale; // } // // /** // * Switch the locale of current app to explicitly specified or default one // * // * @param locale null for default // */ // public static boolean switchTo(final Context context, final Locale locale) { // final Resources resources = context.getResources(); // final Configuration configuration = resources.getConfiguration(); // if (match(locale, configuration.locale)) return false; // setConfigurationLocale(configuration, locale); // resources.updateConfiguration(configuration, null); // return true; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) // private static void setConfigurationLocale(final Configuration configuration, final Locale locale) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) // configuration.locale = locale; // else configuration.setLocale(locale); // } // // private static boolean match(final Locale locale1, final Locale locale2) { // return match(locale1.getLanguage(), locale2.getLanguage()) // && match(locale1.getCountry(), locale2.getCountry()) // && match(locale1.getVariant(), locale2.getVariant()); // } // // private static boolean match(final String value1, final String value2) { // return (value1 == null && value2 == null) || "".equals(value1) || "".equals(value2) // || (value1 != null && value1.equals(value2)); // } // }
import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import com.oasisfeng.android.google.GooglePlayStore; import com.oasisfeng.android.i18n.Locales; import java.util.Locale; import javax.annotation.ParametersAreNonnullByDefault; import androidx.annotation.Nullable;
package com.oasisfeng.android.ui; /** * A helper class to simply build an "About" dialog. * * <p>Declare the activity in AndroidManifest.xml: * <pre> &lt;activity android:name="com.oasisfeng.ui.About" android:theme="@android:style/Theme.Holo.DialogWhenLarge.NoActionBar" /&gt; </pre> Show the dialog in code: <pre>AboutActivity.show(context, R.xml.about);</pre> * @author Oasis */ @ParametersAreNonnullByDefault public class AboutActivity extends PreferenceActivity { private static final String EXTRA_XML_RESOURCE_ID = "xml"; /** Override to provide your own fragment implementation */ @SuppressWarnings("MethodMayBeStatic") protected Fragment createAboutFragment() { return new AboutFragment(); } public static void show(final Context context, final int xml_res) { show(context, xml_res, AboutActivity.class); } /** Show about activity of your own implementation */ public static void show(final Context context, final int xml_res, final Class<? extends Activity> activity) { context.startActivity(new Intent(context, activity).putExtra(EXTRA_XML_RESOURCE_ID, xml_res)); } @Override protected void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, createAboutFragment()).commit(); } public static class AboutFragment extends PreferenceFragment { @Override public void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(getActivity().getIntent().getIntExtra(EXTRA_XML_RESOURCE_ID, 0)); final Preference version_pref = getPreferenceScreen().findPreference("version"); if (version_pref != null) try { final PackageInfo package_info = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version_pref.setTitle(version_pref.getTitle() + " " + package_info.versionName); } catch (final NameNotFoundException ignored) {} } @Override public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen, final Preference preference) { if ("translation".equals(preference.getKey())) { final Locale default_locale = Locale.getDefault();
// Path: library/src/main/java/com/oasisfeng/android/google/GooglePlayStore.java // public class GooglePlayStore { // // public static final String PACKAGE_NAME = "com.android.vending"; // private static final String APP_URL_PREFIX = "https://play.google.com/store/apps/details?id="; // // public static void showApp(final Context context, final String pkg) { // final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_URL_PREFIX + pkg)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // updatePlayUrlIntent(context, intent); // try { // context.startActivity(intent); // } catch(final ActivityNotFoundException e) { /* In case of Google Play malfunction */ } // } // // public static void updatePreferenceIntent(final Context context, final Preference preference) { // final Intent intent = preference.getIntent(); // updatePlayUrlIntent(context, intent); // } // // /** Modify intent to launch Google Play Store directly if possible (without activity chooser) */ // private static void updatePlayUrlIntent(final Context context, final Intent intent) { // if (intent == null || intent.getPackage() != null) return; // Skip intent with explicit target package // final Uri uri = intent.getData(); // if (uri == null) return; // intent.setPackage(PACKAGE_NAME); // final ComponentName component = intent.resolveActivity(context.getPackageManager()); // if (component != null) intent.setComponent(component); // else intent.setPackage(null); // } // } // // Path: library/src/main/java/com/oasisfeng/android/i18n/Locales.java // public class Locales { // // public static Locale getFrom(final Context context) { // return context.getResources().getConfiguration().locale; // } // // /** // * Switch the locale of current app to explicitly specified or default one // * // * @param locale null for default // */ // public static boolean switchTo(final Context context, final Locale locale) { // final Resources resources = context.getResources(); // final Configuration configuration = resources.getConfiguration(); // if (match(locale, configuration.locale)) return false; // setConfigurationLocale(configuration, locale); // resources.updateConfiguration(configuration, null); // return true; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) // private static void setConfigurationLocale(final Configuration configuration, final Locale locale) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) // configuration.locale = locale; // else configuration.setLocale(locale); // } // // private static boolean match(final Locale locale1, final Locale locale2) { // return match(locale1.getLanguage(), locale2.getLanguage()) // && match(locale1.getCountry(), locale2.getCountry()) // && match(locale1.getVariant(), locale2.getVariant()); // } // // private static boolean match(final String value1, final String value2) { // return (value1 == null && value2 == null) || "".equals(value1) || "".equals(value2) // || (value1 != null && value1.equals(value2)); // } // } // Path: library/src/main/java/com/oasisfeng/android/ui/AboutActivity.java import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import com.oasisfeng.android.google.GooglePlayStore; import com.oasisfeng.android.i18n.Locales; import java.util.Locale; import javax.annotation.ParametersAreNonnullByDefault; import androidx.annotation.Nullable; package com.oasisfeng.android.ui; /** * A helper class to simply build an "About" dialog. * * <p>Declare the activity in AndroidManifest.xml: * <pre> &lt;activity android:name="com.oasisfeng.ui.About" android:theme="@android:style/Theme.Holo.DialogWhenLarge.NoActionBar" /&gt; </pre> Show the dialog in code: <pre>AboutActivity.show(context, R.xml.about);</pre> * @author Oasis */ @ParametersAreNonnullByDefault public class AboutActivity extends PreferenceActivity { private static final String EXTRA_XML_RESOURCE_ID = "xml"; /** Override to provide your own fragment implementation */ @SuppressWarnings("MethodMayBeStatic") protected Fragment createAboutFragment() { return new AboutFragment(); } public static void show(final Context context, final int xml_res) { show(context, xml_res, AboutActivity.class); } /** Show about activity of your own implementation */ public static void show(final Context context, final int xml_res, final Class<? extends Activity> activity) { context.startActivity(new Intent(context, activity).putExtra(EXTRA_XML_RESOURCE_ID, xml_res)); } @Override protected void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, createAboutFragment()).commit(); } public static class AboutFragment extends PreferenceFragment { @Override public void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(getActivity().getIntent().getIntExtra(EXTRA_XML_RESOURCE_ID, 0)); final Preference version_pref = getPreferenceScreen().findPreference("version"); if (version_pref != null) try { final PackageInfo package_info = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version_pref.setTitle(version_pref.getTitle() + " " + package_info.versionName); } catch (final NameNotFoundException ignored) {} } @Override public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen, final Preference preference) { if ("translation".equals(preference.getKey())) { final Locale default_locale = Locale.getDefault();
final Locale locale = Locales.getFrom(getActivity());
oasisfeng/deagle
library/src/main/java/com/oasisfeng/android/ui/AboutActivity.java
// Path: library/src/main/java/com/oasisfeng/android/google/GooglePlayStore.java // public class GooglePlayStore { // // public static final String PACKAGE_NAME = "com.android.vending"; // private static final String APP_URL_PREFIX = "https://play.google.com/store/apps/details?id="; // // public static void showApp(final Context context, final String pkg) { // final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_URL_PREFIX + pkg)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // updatePlayUrlIntent(context, intent); // try { // context.startActivity(intent); // } catch(final ActivityNotFoundException e) { /* In case of Google Play malfunction */ } // } // // public static void updatePreferenceIntent(final Context context, final Preference preference) { // final Intent intent = preference.getIntent(); // updatePlayUrlIntent(context, intent); // } // // /** Modify intent to launch Google Play Store directly if possible (without activity chooser) */ // private static void updatePlayUrlIntent(final Context context, final Intent intent) { // if (intent == null || intent.getPackage() != null) return; // Skip intent with explicit target package // final Uri uri = intent.getData(); // if (uri == null) return; // intent.setPackage(PACKAGE_NAME); // final ComponentName component = intent.resolveActivity(context.getPackageManager()); // if (component != null) intent.setComponent(component); // else intent.setPackage(null); // } // } // // Path: library/src/main/java/com/oasisfeng/android/i18n/Locales.java // public class Locales { // // public static Locale getFrom(final Context context) { // return context.getResources().getConfiguration().locale; // } // // /** // * Switch the locale of current app to explicitly specified or default one // * // * @param locale null for default // */ // public static boolean switchTo(final Context context, final Locale locale) { // final Resources resources = context.getResources(); // final Configuration configuration = resources.getConfiguration(); // if (match(locale, configuration.locale)) return false; // setConfigurationLocale(configuration, locale); // resources.updateConfiguration(configuration, null); // return true; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) // private static void setConfigurationLocale(final Configuration configuration, final Locale locale) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) // configuration.locale = locale; // else configuration.setLocale(locale); // } // // private static boolean match(final Locale locale1, final Locale locale2) { // return match(locale1.getLanguage(), locale2.getLanguage()) // && match(locale1.getCountry(), locale2.getCountry()) // && match(locale1.getVariant(), locale2.getVariant()); // } // // private static boolean match(final String value1, final String value2) { // return (value1 == null && value2 == null) || "".equals(value1) || "".equals(value2) // || (value1 != null && value1.equals(value2)); // } // }
import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import com.oasisfeng.android.google.GooglePlayStore; import com.oasisfeng.android.i18n.Locales; import java.util.Locale; import javax.annotation.ParametersAreNonnullByDefault; import androidx.annotation.Nullable;
package com.oasisfeng.android.ui; /** * A helper class to simply build an "About" dialog. * * <p>Declare the activity in AndroidManifest.xml: * <pre> &lt;activity android:name="com.oasisfeng.ui.About" android:theme="@android:style/Theme.Holo.DialogWhenLarge.NoActionBar" /&gt; </pre> Show the dialog in code: <pre>AboutActivity.show(context, R.xml.about);</pre> * @author Oasis */ @ParametersAreNonnullByDefault public class AboutActivity extends PreferenceActivity { private static final String EXTRA_XML_RESOURCE_ID = "xml"; /** Override to provide your own fragment implementation */ @SuppressWarnings("MethodMayBeStatic") protected Fragment createAboutFragment() { return new AboutFragment(); } public static void show(final Context context, final int xml_res) { show(context, xml_res, AboutActivity.class); } /** Show about activity of your own implementation */ public static void show(final Context context, final int xml_res, final Class<? extends Activity> activity) { context.startActivity(new Intent(context, activity).putExtra(EXTRA_XML_RESOURCE_ID, xml_res)); } @Override protected void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, createAboutFragment()).commit(); } public static class AboutFragment extends PreferenceFragment { @Override public void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(getActivity().getIntent().getIntExtra(EXTRA_XML_RESOURCE_ID, 0)); final Preference version_pref = getPreferenceScreen().findPreference("version"); if (version_pref != null) try { final PackageInfo package_info = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version_pref.setTitle(version_pref.getTitle() + " " + package_info.versionName); } catch (final NameNotFoundException ignored) {} } @Override public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen, final Preference preference) { if ("translation".equals(preference.getKey())) { final Locale default_locale = Locale.getDefault(); final Locale locale = Locales.getFrom(getActivity()); if (Locales.switchTo(getActivity(), locale == null || default_locale.equals(locale) ? new Locale("en") : default_locale)) getActivity().recreate(); return true; } else if (preference.getIntent() != null)
// Path: library/src/main/java/com/oasisfeng/android/google/GooglePlayStore.java // public class GooglePlayStore { // // public static final String PACKAGE_NAME = "com.android.vending"; // private static final String APP_URL_PREFIX = "https://play.google.com/store/apps/details?id="; // // public static void showApp(final Context context, final String pkg) { // final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(APP_URL_PREFIX + pkg)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // updatePlayUrlIntent(context, intent); // try { // context.startActivity(intent); // } catch(final ActivityNotFoundException e) { /* In case of Google Play malfunction */ } // } // // public static void updatePreferenceIntent(final Context context, final Preference preference) { // final Intent intent = preference.getIntent(); // updatePlayUrlIntent(context, intent); // } // // /** Modify intent to launch Google Play Store directly if possible (without activity chooser) */ // private static void updatePlayUrlIntent(final Context context, final Intent intent) { // if (intent == null || intent.getPackage() != null) return; // Skip intent with explicit target package // final Uri uri = intent.getData(); // if (uri == null) return; // intent.setPackage(PACKAGE_NAME); // final ComponentName component = intent.resolveActivity(context.getPackageManager()); // if (component != null) intent.setComponent(component); // else intent.setPackage(null); // } // } // // Path: library/src/main/java/com/oasisfeng/android/i18n/Locales.java // public class Locales { // // public static Locale getFrom(final Context context) { // return context.getResources().getConfiguration().locale; // } // // /** // * Switch the locale of current app to explicitly specified or default one // * // * @param locale null for default // */ // public static boolean switchTo(final Context context, final Locale locale) { // final Resources resources = context.getResources(); // final Configuration configuration = resources.getConfiguration(); // if (match(locale, configuration.locale)) return false; // setConfigurationLocale(configuration, locale); // resources.updateConfiguration(configuration, null); // return true; // } // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) // private static void setConfigurationLocale(final Configuration configuration, final Locale locale) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) // configuration.locale = locale; // else configuration.setLocale(locale); // } // // private static boolean match(final Locale locale1, final Locale locale2) { // return match(locale1.getLanguage(), locale2.getLanguage()) // && match(locale1.getCountry(), locale2.getCountry()) // && match(locale1.getVariant(), locale2.getVariant()); // } // // private static boolean match(final String value1, final String value2) { // return (value1 == null && value2 == null) || "".equals(value1) || "".equals(value2) // || (value1 != null && value1.equals(value2)); // } // } // Path: library/src/main/java/com/oasisfeng/android/ui/AboutActivity.java import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import com.oasisfeng.android.google.GooglePlayStore; import com.oasisfeng.android.i18n.Locales; import java.util.Locale; import javax.annotation.ParametersAreNonnullByDefault; import androidx.annotation.Nullable; package com.oasisfeng.android.ui; /** * A helper class to simply build an "About" dialog. * * <p>Declare the activity in AndroidManifest.xml: * <pre> &lt;activity android:name="com.oasisfeng.ui.About" android:theme="@android:style/Theme.Holo.DialogWhenLarge.NoActionBar" /&gt; </pre> Show the dialog in code: <pre>AboutActivity.show(context, R.xml.about);</pre> * @author Oasis */ @ParametersAreNonnullByDefault public class AboutActivity extends PreferenceActivity { private static final String EXTRA_XML_RESOURCE_ID = "xml"; /** Override to provide your own fragment implementation */ @SuppressWarnings("MethodMayBeStatic") protected Fragment createAboutFragment() { return new AboutFragment(); } public static void show(final Context context, final int xml_res) { show(context, xml_res, AboutActivity.class); } /** Show about activity of your own implementation */ public static void show(final Context context, final int xml_res, final Class<? extends Activity> activity) { context.startActivity(new Intent(context, activity).putExtra(EXTRA_XML_RESOURCE_ID, xml_res)); } @Override protected void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, createAboutFragment()).commit(); } public static class AboutFragment extends PreferenceFragment { @Override public void onCreate(final @Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(getActivity().getIntent().getIntExtra(EXTRA_XML_RESOURCE_ID, 0)); final Preference version_pref = getPreferenceScreen().findPreference("version"); if (version_pref != null) try { final PackageInfo package_info = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); version_pref.setTitle(version_pref.getTitle() + " " + package_info.versionName); } catch (final NameNotFoundException ignored) {} } @Override public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen, final Preference preference) { if ("translation".equals(preference.getKey())) { final Locale default_locale = Locale.getDefault(); final Locale locale = Locales.getFrom(getActivity()); if (Locales.switchTo(getActivity(), locale == null || default_locale.equals(locale) ? new Locale("en") : default_locale)) getActivity().recreate(); return true; } else if (preference.getIntent() != null)
GooglePlayStore.updatePreferenceIntent(getActivity(), preference);
oasisfeng/deagle
library/src/main/java/com/oasisfeng/android/service/LocalAidlServices.java
// Path: library/src/main/java/com/oasisfeng/android/util/MultiCatchROECompat.java // public class MultiCatchROECompat extends RuntimeException {}
import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentCallbacks; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Debug; import android.os.IBinder; import android.os.IInterface; import android.util.Log; import com.oasisfeng.android.util.MultiCatchROECompat; import java.io.Closeable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable;
} catch (final IllegalAccessException e) { Log.e(TAG, "Unexpected exception when attaching service.", e); } catch (final InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } } private static Application getApplication(final Context context) { if (context instanceof Activity) return ((Activity) context).getApplication(); if (context instanceof Service) return ((Service) context).getApplication(); final Context app_context = context.getApplicationContext(); if (app_context instanceof Application) return (Application) app_context; Log.w(TAG, "Cannot discover application from context " + context); return null; } private static final Map<Class<? extends IInterface>, ServiceRecord> sServices = Collections.synchronizedMap(new HashMap<Class<? extends IInterface>, ServiceRecord>()); private static final BroadcastReceiver sDummyReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) {}}; private static final String TAG = "LocalSvc"; // Method signature: (useless parameters for AIDL service - thread, token, activityManager) // public final void attach(Context context, ActivityThread thread, String className, IBinder token, Application application, Object activityManager) private static final Method Service_attach; static { Method method = null; try { final Class<?> ActivityThread = Class.forName("android.app.ActivityThread"); method = Service.class.getDeclaredMethod("attach", Context.class, ActivityThread, String.class, IBinder.class, Application.class, Object.class); method.setAccessible(true);
// Path: library/src/main/java/com/oasisfeng/android/util/MultiCatchROECompat.java // public class MultiCatchROECompat extends RuntimeException {} // Path: library/src/main/java/com/oasisfeng/android/service/LocalAidlServices.java import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentCallbacks; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Debug; import android.os.IBinder; import android.os.IInterface; import android.util.Log; import com.oasisfeng.android.util.MultiCatchROECompat; import java.io.Closeable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; } catch (final IllegalAccessException e) { Log.e(TAG, "Unexpected exception when attaching service.", e); } catch (final InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } } private static Application getApplication(final Context context) { if (context instanceof Activity) return ((Activity) context).getApplication(); if (context instanceof Service) return ((Service) context).getApplication(); final Context app_context = context.getApplicationContext(); if (app_context instanceof Application) return (Application) app_context; Log.w(TAG, "Cannot discover application from context " + context); return null; } private static final Map<Class<? extends IInterface>, ServiceRecord> sServices = Collections.synchronizedMap(new HashMap<Class<? extends IInterface>, ServiceRecord>()); private static final BroadcastReceiver sDummyReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) {}}; private static final String TAG = "LocalSvc"; // Method signature: (useless parameters for AIDL service - thread, token, activityManager) // public final void attach(Context context, ActivityThread thread, String className, IBinder token, Application application, Object activityManager) private static final Method Service_attach; static { Method method = null; try { final Class<?> ActivityThread = Class.forName("android.app.ActivityThread"); method = Service.class.getDeclaredMethod("attach", Context.class, ActivityThread, String.class, IBinder.class, Application.class, Object.class); method.setAccessible(true);
} catch (final ClassNotFoundException | NoSuchMethodException | MultiCatchROECompat e) {
oasisfeng/deagle
library/src/main/java/com/oasisfeng/androidx/lifecycle/ViewModelProviders.java
// Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelActivity.java // public class LifecycleViewModelActivity extends LifecycleActivity implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if (getApplication() == null) { // throw new IllegalStateException("Your activity is not yet attached to the " // + "Application instance. You can't request ViewModel before onCreate call."); // } // if (mViewModelStore == null) { // mViewModelStore = new ViewModelStore(); // } // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // } // // Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelFragment.java // public class LifecycleViewModelFragment extends LifecycleFragment implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if ((SDK_INT >= M ? getContext() : getActivity()) == null) throw new IllegalStateException("Can't access ViewModels from detached fragment"); // if (mViewModelStore == null) mViewModelStore = new ViewModelStore(); // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // TODO: Retain across configuration changes // }
import androidx.lifecycle.ViewModelStoreOwner; import android.app.Activity; import android.app.Application; import android.app.Fragment; import com.oasisfeng.android.app.LifecycleViewModelActivity; import com.oasisfeng.android.app.LifecycleViewModelFragment; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStore;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oasisfeng.androidx.lifecycle; /** * Utilities methods for {@link ViewModelStore} class. */ public class ViewModelProviders { private static Application checkApplication(Activity activity) { Application application = activity.getApplication(); if (application == null) { throw new IllegalStateException("Your activity/fragment is not yet attached to " + "Application. You can't request ViewModel before onCreate call."); } return application; } private static Activity checkActivity(Fragment fragment) { Activity activity = fragment.getActivity(); if (activity == null) { throw new IllegalStateException("Can't create ViewModelProvider for detached fragment"); } return activity; } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given * {@code fragment} is alive. More detailed explanation is in {@link ViewModel}. * <p> * It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param fragment a fragment, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread
// Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelActivity.java // public class LifecycleViewModelActivity extends LifecycleActivity implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if (getApplication() == null) { // throw new IllegalStateException("Your activity is not yet attached to the " // + "Application instance. You can't request ViewModel before onCreate call."); // } // if (mViewModelStore == null) { // mViewModelStore = new ViewModelStore(); // } // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // } // // Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelFragment.java // public class LifecycleViewModelFragment extends LifecycleFragment implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if ((SDK_INT >= M ? getContext() : getActivity()) == null) throw new IllegalStateException("Can't access ViewModels from detached fragment"); // if (mViewModelStore == null) mViewModelStore = new ViewModelStore(); // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // TODO: Retain across configuration changes // } // Path: library/src/main/java/com/oasisfeng/androidx/lifecycle/ViewModelProviders.java import androidx.lifecycle.ViewModelStoreOwner; import android.app.Activity; import android.app.Application; import android.app.Fragment; import com.oasisfeng.android.app.LifecycleViewModelActivity; import com.oasisfeng.android.app.LifecycleViewModelFragment; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStore; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oasisfeng.androidx.lifecycle; /** * Utilities methods for {@link ViewModelStore} class. */ public class ViewModelProviders { private static Application checkApplication(Activity activity) { Application application = activity.getApplication(); if (application == null) { throw new IllegalStateException("Your activity/fragment is not yet attached to " + "Application. You can't request ViewModel before onCreate call."); } return application; } private static Activity checkActivity(Fragment fragment) { Activity activity = fragment.getActivity(); if (activity == null) { throw new IllegalStateException("Can't create ViewModelProvider for detached fragment"); } return activity; } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given * {@code fragment} is alive. More detailed explanation is in {@link ViewModel}. * <p> * It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param fragment a fragment, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread
public static ViewModelProvider of(@NonNull LifecycleViewModelFragment fragment) {
oasisfeng/deagle
library/src/main/java/com/oasisfeng/androidx/lifecycle/ViewModelProviders.java
// Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelActivity.java // public class LifecycleViewModelActivity extends LifecycleActivity implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if (getApplication() == null) { // throw new IllegalStateException("Your activity is not yet attached to the " // + "Application instance. You can't request ViewModel before onCreate call."); // } // if (mViewModelStore == null) { // mViewModelStore = new ViewModelStore(); // } // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // } // // Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelFragment.java // public class LifecycleViewModelFragment extends LifecycleFragment implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if ((SDK_INT >= M ? getContext() : getActivity()) == null) throw new IllegalStateException("Can't access ViewModels from detached fragment"); // if (mViewModelStore == null) mViewModelStore = new ViewModelStore(); // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // TODO: Retain across configuration changes // }
import androidx.lifecycle.ViewModelStoreOwner; import android.app.Activity; import android.app.Application; import android.app.Fragment; import com.oasisfeng.android.app.LifecycleViewModelActivity; import com.oasisfeng.android.app.LifecycleViewModelFragment; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStore;
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oasisfeng.androidx.lifecycle; /** * Utilities methods for {@link ViewModelStore} class. */ public class ViewModelProviders { private static Application checkApplication(Activity activity) { Application application = activity.getApplication(); if (application == null) { throw new IllegalStateException("Your activity/fragment is not yet attached to " + "Application. You can't request ViewModel before onCreate call."); } return application; } private static Activity checkActivity(Fragment fragment) { Activity activity = fragment.getActivity(); if (activity == null) { throw new IllegalStateException("Can't create ViewModelProvider for detached fragment"); } return activity; } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given * {@code fragment} is alive. More detailed explanation is in {@link ViewModel}. * <p> * It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param fragment a fragment, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread public static ViewModelProvider of(@NonNull LifecycleViewModelFragment fragment) { return of(fragment, null); } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity * is alive. More detailed explanation is in {@link ViewModel}. * <p> * It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param activity an activity, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread
// Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelActivity.java // public class LifecycleViewModelActivity extends LifecycleActivity implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if (getApplication() == null) { // throw new IllegalStateException("Your activity is not yet attached to the " // + "Application instance. You can't request ViewModel before onCreate call."); // } // if (mViewModelStore == null) { // mViewModelStore = new ViewModelStore(); // } // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // } // // Path: library/src/main/java/com/oasisfeng/android/app/LifecycleViewModelFragment.java // public class LifecycleViewModelFragment extends LifecycleFragment implements ViewModelStoreOwner { // // @Override public @NonNull ViewModelStore getViewModelStore() { // if ((SDK_INT >= M ? getContext() : getActivity()) == null) throw new IllegalStateException("Can't access ViewModels from detached fragment"); // if (mViewModelStore == null) mViewModelStore = new ViewModelStore(); // return mViewModelStore; // } // // private ViewModelStore mViewModelStore; // TODO: Retain across configuration changes // } // Path: library/src/main/java/com/oasisfeng/androidx/lifecycle/ViewModelProviders.java import androidx.lifecycle.ViewModelStoreOwner; import android.app.Activity; import android.app.Application; import android.app.Fragment; import com.oasisfeng.android.app.LifecycleViewModelActivity; import com.oasisfeng.android.app.LifecycleViewModelFragment; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelStore; /* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.oasisfeng.androidx.lifecycle; /** * Utilities methods for {@link ViewModelStore} class. */ public class ViewModelProviders { private static Application checkApplication(Activity activity) { Application application = activity.getApplication(); if (application == null) { throw new IllegalStateException("Your activity/fragment is not yet attached to " + "Application. You can't request ViewModel before onCreate call."); } return application; } private static Activity checkActivity(Fragment fragment) { Activity activity = fragment.getActivity(); if (activity == null) { throw new IllegalStateException("Can't create ViewModelProvider for detached fragment"); } return activity; } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given * {@code fragment} is alive. More detailed explanation is in {@link ViewModel}. * <p> * It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param fragment a fragment, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread public static ViewModelProvider of(@NonNull LifecycleViewModelFragment fragment) { return of(fragment, null); } /** * Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity * is alive. More detailed explanation is in {@link ViewModel}. * <p> * It uses {@link ViewModelProvider.AndroidViewModelFactory} to instantiate new ViewModels. * * @param activity an activity, in whose scope ViewModels should be retained * @return a ViewModelProvider instance */ @NonNull @MainThread
public static ViewModelProvider of(@NonNull LifecycleViewModelActivity activity) {
oasisfeng/deagle
library/src/main/java/com/oasisfeng/android/content/pm/Permissions.java
// Path: library/src/main/java/com/oasisfeng/android/util/Consumer.java // public interface Consumer<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t); // }
import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Process; import com.oasisfeng.android.util.Consumer; import javax.annotation.ParametersAreNonnullByDefault; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import static android.os.Build.VERSION_CODES.M;
package com.oasisfeng.android.content.pm; /** * Permission-related helpers * * Created by Oasis on 2016/9/27. */ @ParametersAreNonnullByDefault public class Permissions { public static final String INTERACT_ACROSS_USERS = "android.permission.INTERACT_ACROSS_USERS"; public static boolean has(final Context context, final String permission) { return context.checkPermission(permission, Process.myPid(), Process.myUid()) == PackageManager.PERMISSION_GRANTED; } /** @param callback will be called if request is not canceled, with either {@link PackageManager#PERMISSION_GRANTED} or {@link PackageManager#PERMISSION_DENIED} */
// Path: library/src/main/java/com/oasisfeng/android/util/Consumer.java // public interface Consumer<T> { // // /** // * Performs this operation on the given argument. // * // * @param t the input argument // */ // void accept(T t); // } // Path: library/src/main/java/com/oasisfeng/android/content/pm/Permissions.java import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Process; import com.oasisfeng.android.util.Consumer; import javax.annotation.ParametersAreNonnullByDefault; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import static android.os.Build.VERSION_CODES.M; package com.oasisfeng.android.content.pm; /** * Permission-related helpers * * Created by Oasis on 2016/9/27. */ @ParametersAreNonnullByDefault public class Permissions { public static final String INTERACT_ACROSS_USERS = "android.permission.INTERACT_ACROSS_USERS"; public static boolean has(final Context context, final String permission) { return context.checkPermission(permission, Process.myPid(), Process.myUid()) == PackageManager.PERMISSION_GRANTED; } /** @param callback will be called if request is not canceled, with either {@link PackageManager#PERMISSION_GRANTED} or {@link PackageManager#PERMISSION_DENIED} */
@RequiresApi(M) public static void request(final Activity activity, final String permission, final Consumer<Integer> callback) {
graphql-java/java-dataloader
src/main/java/org/dataloader/CacheMap.java
// Path: src/main/java/org/dataloader/impl/DefaultCacheMap.java // @Internal // public class DefaultCacheMap<K, V> implements CacheMap<K, V> { // // private final Map<K, CompletableFuture<V>> cache; // // /** // * Default constructor // */ // public DefaultCacheMap() { // cache = new HashMap<>(); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean containsKey(K key) { // return cache.containsKey(key); // } // // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<V> get(K key) { // return cache.get(key); // } // // /** // * {@inheritDoc} // */ // @Override // public CacheMap<K, V> set(K key, CompletableFuture<V> value) { // cache.put(key, value); // return this; // } // // /** // * {@inheritDoc} // */ // @Override // public CacheMap<K, V> delete(K key) { // cache.remove(key); // return this; // } // // /** // * {@inheritDoc} // */ // @Override // public CacheMap<K, V> clear() { // cache.clear(); // return this; // } // }
import org.dataloader.annotations.PublicSpi; import org.dataloader.impl.DefaultCacheMap; import java.util.concurrent.CompletableFuture;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * CacheMap is used by data loaders that use caching promises to values aka {@link CompletableFuture}&lt;V&gt;. A better name for this * class might have been FutureCache but that is history now. * <p> * The default implementation used by the data loader is based on a {@link java.util.LinkedHashMap}. * <p> * This is really a cache of completed {@link CompletableFuture}&lt;V&gt; values in memory. It is used, when caching is enabled, to * give back the same future to any code that may call it. If you need a cache of the underlying values that is possible external to the JVM * then you will want to use {{@link ValueCache}} which is designed for external cache access. * * @param <K> type parameter indicating the type of the cache keys * @param <V> type parameter indicating the type of the data that is cached * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> * @author <a href="https://github.com/bbakerman/">Brad Baker</a> */ @PublicSpi public interface CacheMap<K, V> { /** * Creates a new cache map, using the default implementation that is based on a {@link java.util.LinkedHashMap}. * * @param <K> type parameter indicating the type of the cache keys * @param <V> type parameter indicating the type of the data that is cached * * @return the cache map */ static <K, V> CacheMap<K, V> simpleMap() {
// Path: src/main/java/org/dataloader/impl/DefaultCacheMap.java // @Internal // public class DefaultCacheMap<K, V> implements CacheMap<K, V> { // // private final Map<K, CompletableFuture<V>> cache; // // /** // * Default constructor // */ // public DefaultCacheMap() { // cache = new HashMap<>(); // } // // /** // * {@inheritDoc} // */ // @Override // public boolean containsKey(K key) { // return cache.containsKey(key); // } // // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<V> get(K key) { // return cache.get(key); // } // // /** // * {@inheritDoc} // */ // @Override // public CacheMap<K, V> set(K key, CompletableFuture<V> value) { // cache.put(key, value); // return this; // } // // /** // * {@inheritDoc} // */ // @Override // public CacheMap<K, V> delete(K key) { // cache.remove(key); // return this; // } // // /** // * {@inheritDoc} // */ // @Override // public CacheMap<K, V> clear() { // cache.clear(); // return this; // } // } // Path: src/main/java/org/dataloader/CacheMap.java import org.dataloader.annotations.PublicSpi; import org.dataloader.impl.DefaultCacheMap; import java.util.concurrent.CompletableFuture; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * CacheMap is used by data loaders that use caching promises to values aka {@link CompletableFuture}&lt;V&gt;. A better name for this * class might have been FutureCache but that is history now. * <p> * The default implementation used by the data loader is based on a {@link java.util.LinkedHashMap}. * <p> * This is really a cache of completed {@link CompletableFuture}&lt;V&gt; values in memory. It is used, when caching is enabled, to * give back the same future to any code that may call it. If you need a cache of the underlying values that is possible external to the JVM * then you will want to use {{@link ValueCache}} which is designed for external cache access. * * @param <K> type parameter indicating the type of the cache keys * @param <V> type parameter indicating the type of the data that is cached * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> * @author <a href="https://github.com/bbakerman/">Brad Baker</a> */ @PublicSpi public interface CacheMap<K, V> { /** * Creates a new cache map, using the default implementation that is based on a {@link java.util.LinkedHashMap}. * * @param <K> type parameter indicating the type of the cache keys * @param <V> type parameter indicating the type of the data that is cached * * @return the cache map */ static <K, V> CacheMap<K, V> simpleMap() {
return new DefaultCacheMap<>();
graphql-java/java-dataloader
src/main/java/org/dataloader/ValueCache.java
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/impl/NoOpValueCache.java // @Internal // public class NoOpValueCache<K, V> implements ValueCache<K, V> { // // /** // * a no op value cache instance // */ // public static final NoOpValueCache<?, ?> NOOP = new NoOpValueCache<>(); // // // avoid object allocation by using a final field // private final ValueCachingNotSupported NOT_SUPPORTED = new ValueCachingNotSupported(); // private final CompletableFuture<V> NOT_SUPPORTED_CF = CompletableFutureKit.failedFuture(NOT_SUPPORTED); // private final CompletableFuture<Void> NOT_SUPPORTED_VOID_CF = CompletableFuture.completedFuture(null); // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<V> get(K key) { // return NOT_SUPPORTED_CF; // } // // @Override // public CompletableFuture<List<Try<V>>> getValues(List<K> keys) throws ValueCachingNotSupported { // throw NOT_SUPPORTED; // } // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<V> set(K key, V value) { // return NOT_SUPPORTED_CF; // } // // @Override // public CompletableFuture<List<V>> setValues(List<K> keys, List<V> values) throws ValueCachingNotSupported { // throw NOT_SUPPORTED; // } // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<Void> delete(K key) { // return NOT_SUPPORTED_VOID_CF; // } // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<Void> clear() { // return NOT_SUPPORTED_VOID_CF; // } // }
import org.dataloader.annotations.PublicSpi; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.impl.NoOpValueCache; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture;
package org.dataloader; /** * The {@link ValueCache} is used by data loaders that use caching and want a long-lived or external cache * of values. The {@link ValueCache} is used as a place to cache values when they come back from an async * cache store. * <p> * It differs from {@link CacheMap} which is in fact a cache of promised values aka {@link CompletableFuture}&lt;V&gt;'s. * <p> * {@link ValueCache} is more suited to be a wrapper of a long-lived or externallly cached values. {@link CompletableFuture}s cant * be easily placed in an external cache outside the JVM say, hence the need for the {@link ValueCache}. * <p> * {@link DataLoader}s use a two stage cache strategy if caching is enabled. If the {@link CacheMap} already has the promise to a value * that is used. If not then the {@link ValueCache} is asked for a value, if it has one then that is returned (and cached as a promise in the {@link CacheMap}. * <p> * If there is no value then the key is queued and loaded via the {@link BatchLoader} calls. The returned values will then be stored in * the {@link ValueCache} and the promises to those values are also stored in the {@link CacheMap}. * <p> * The default implementation is a no-op store which replies with the key always missing and doesn't * store any actual results. This is to avoid duplicating the stored data between the {@link CacheMap} * out of the box. * <p> * The API signature uses {@link CompletableFuture}s because the backing implementation MAY be a remote external cache * and hence exceptions may happen in retrieving values and they may take time to complete. * * @param <K> the type of cache keys * @param <V> the type of cache values * * @author <a href="https://github.com/craig-day">Craig Day</a> * @author <a href="https://github.com/bbakerman/">Brad Baker</a> */ @PublicSpi public interface ValueCache<K, V> { /** * Creates a new value cache, using the default no-op implementation. * * @param <K> the type of cache keys * @param <V> the type of cache values * * @return the cache store */ static <K, V> ValueCache<K, V> defaultValueCache() { //noinspection unchecked
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/impl/NoOpValueCache.java // @Internal // public class NoOpValueCache<K, V> implements ValueCache<K, V> { // // /** // * a no op value cache instance // */ // public static final NoOpValueCache<?, ?> NOOP = new NoOpValueCache<>(); // // // avoid object allocation by using a final field // private final ValueCachingNotSupported NOT_SUPPORTED = new ValueCachingNotSupported(); // private final CompletableFuture<V> NOT_SUPPORTED_CF = CompletableFutureKit.failedFuture(NOT_SUPPORTED); // private final CompletableFuture<Void> NOT_SUPPORTED_VOID_CF = CompletableFuture.completedFuture(null); // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<V> get(K key) { // return NOT_SUPPORTED_CF; // } // // @Override // public CompletableFuture<List<Try<V>>> getValues(List<K> keys) throws ValueCachingNotSupported { // throw NOT_SUPPORTED; // } // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<V> set(K key, V value) { // return NOT_SUPPORTED_CF; // } // // @Override // public CompletableFuture<List<V>> setValues(List<K> keys, List<V> values) throws ValueCachingNotSupported { // throw NOT_SUPPORTED; // } // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<Void> delete(K key) { // return NOT_SUPPORTED_VOID_CF; // } // // /** // * {@inheritDoc} // */ // @Override // public CompletableFuture<Void> clear() { // return NOT_SUPPORTED_VOID_CF; // } // } // Path: src/main/java/org/dataloader/ValueCache.java import org.dataloader.annotations.PublicSpi; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.impl.NoOpValueCache; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; package org.dataloader; /** * The {@link ValueCache} is used by data loaders that use caching and want a long-lived or external cache * of values. The {@link ValueCache} is used as a place to cache values when they come back from an async * cache store. * <p> * It differs from {@link CacheMap} which is in fact a cache of promised values aka {@link CompletableFuture}&lt;V&gt;'s. * <p> * {@link ValueCache} is more suited to be a wrapper of a long-lived or externallly cached values. {@link CompletableFuture}s cant * be easily placed in an external cache outside the JVM say, hence the need for the {@link ValueCache}. * <p> * {@link DataLoader}s use a two stage cache strategy if caching is enabled. If the {@link CacheMap} already has the promise to a value * that is used. If not then the {@link ValueCache} is asked for a value, if it has one then that is returned (and cached as a promise in the {@link CacheMap}. * <p> * If there is no value then the key is queued and loaded via the {@link BatchLoader} calls. The returned values will then be stored in * the {@link ValueCache} and the promises to those values are also stored in the {@link CacheMap}. * <p> * The default implementation is a no-op store which replies with the key always missing and doesn't * store any actual results. This is to avoid duplicating the stored data between the {@link CacheMap} * out of the box. * <p> * The API signature uses {@link CompletableFuture}s because the backing implementation MAY be a remote external cache * and hence exceptions may happen in retrieving values and they may take time to complete. * * @param <K> the type of cache keys * @param <V> the type of cache values * * @author <a href="https://github.com/craig-day">Craig Day</a> * @author <a href="https://github.com/bbakerman/">Brad Baker</a> */ @PublicSpi public interface ValueCache<K, V> { /** * Creates a new value cache, using the default no-op implementation. * * @param <K> the type of cache keys * @param <V> the type of cache values * * @return the cache store */ static <K, V> ValueCache<K, V> defaultValueCache() { //noinspection unchecked
return (ValueCache<K, V>) NoOpValueCache.NOOP;
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package org.dataloader; /** * Much of the tests that related to {@link MappedBatchLoader} also related to * {@link org.dataloader.BatchLoader}. This is white box testing somewhat because we could have repeated * ALL the tests in {@link org.dataloader.DataLoaderTest} here as well but chose not to because we KNOW that * DataLoader differs only a little in how it handles the 2 types of loader functions. We choose to grab some * common functionality for repeat testing and otherwise rely on the very complete other tests. */ public class DataLoaderMapBatchLoaderTest { MappedBatchLoader<String, String> evensOnlyMappedBatchLoader = (keys) -> { Map<String, String> mapOfResults = new HashMap<>(); AtomicInteger index = new AtomicInteger(); keys.forEach(k -> { int i = index.getAndIncrement(); if (i % 2 == 0) { mapOfResults.put(k, k); } }); return CompletableFuture.completedFuture(mapOfResults); }; private static <K, V> DataLoader<K, V> idMapLoader(DataLoaderOptions options, List<Collection<K>> loadCalls) { MappedBatchLoader<K, V> kvBatchLoader = (keys) -> { loadCalls.add(new ArrayList<>(keys)); Map<K, V> map = new HashMap<>(); //noinspection unchecked keys.forEach(k -> map.put(k, (V) k)); return CompletableFuture.completedFuture(map); }; return DataLoaderFactory.newMappedDataLoader(kvBatchLoader, options); } private static <K, V> DataLoader<K, V> idMapLoaderBlowsUps( DataLoaderOptions options, List<Collection<K>> loadCalls) {
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // Path: src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package org.dataloader; /** * Much of the tests that related to {@link MappedBatchLoader} also related to * {@link org.dataloader.BatchLoader}. This is white box testing somewhat because we could have repeated * ALL the tests in {@link org.dataloader.DataLoaderTest} here as well but chose not to because we KNOW that * DataLoader differs only a little in how it handles the 2 types of loader functions. We choose to grab some * common functionality for repeat testing and otherwise rely on the very complete other tests. */ public class DataLoaderMapBatchLoaderTest { MappedBatchLoader<String, String> evensOnlyMappedBatchLoader = (keys) -> { Map<String, String> mapOfResults = new HashMap<>(); AtomicInteger index = new AtomicInteger(); keys.forEach(k -> { int i = index.getAndIncrement(); if (i % 2 == 0) { mapOfResults.put(k, k); } }); return CompletableFuture.completedFuture(mapOfResults); }; private static <K, V> DataLoader<K, V> idMapLoader(DataLoaderOptions options, List<Collection<K>> loadCalls) { MappedBatchLoader<K, V> kvBatchLoader = (keys) -> { loadCalls.add(new ArrayList<>(keys)); Map<K, V> map = new HashMap<>(); //noinspection unchecked keys.forEach(k -> map.put(k, (V) k)); return CompletableFuture.completedFuture(map); }; return DataLoaderFactory.newMappedDataLoader(kvBatchLoader, options); } private static <K, V> DataLoader<K, V> idMapLoaderBlowsUps( DataLoaderOptions options, List<Collection<K>> loadCalls) {
return newDataLoader((keys) -> {
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package org.dataloader; /** * Much of the tests that related to {@link MappedBatchLoader} also related to * {@link org.dataloader.BatchLoader}. This is white box testing somewhat because we could have repeated * ALL the tests in {@link org.dataloader.DataLoaderTest} here as well but chose not to because we KNOW that * DataLoader differs only a little in how it handles the 2 types of loader functions. We choose to grab some * common functionality for repeat testing and otherwise rely on the very complete other tests. */ public class DataLoaderMapBatchLoaderTest { MappedBatchLoader<String, String> evensOnlyMappedBatchLoader = (keys) -> { Map<String, String> mapOfResults = new HashMap<>(); AtomicInteger index = new AtomicInteger(); keys.forEach(k -> { int i = index.getAndIncrement(); if (i % 2 == 0) { mapOfResults.put(k, k); } }); return CompletableFuture.completedFuture(mapOfResults); }; private static <K, V> DataLoader<K, V> idMapLoader(DataLoaderOptions options, List<Collection<K>> loadCalls) { MappedBatchLoader<K, V> kvBatchLoader = (keys) -> { loadCalls.add(new ArrayList<>(keys)); Map<K, V> map = new HashMap<>(); //noinspection unchecked keys.forEach(k -> map.put(k, (V) k)); return CompletableFuture.completedFuture(map); }; return DataLoaderFactory.newMappedDataLoader(kvBatchLoader, options); } private static <K, V> DataLoader<K, V> idMapLoaderBlowsUps( DataLoaderOptions options, List<Collection<K>> loadCalls) { return newDataLoader((keys) -> { loadCalls.add(new ArrayList<>(keys));
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // Path: src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package org.dataloader; /** * Much of the tests that related to {@link MappedBatchLoader} also related to * {@link org.dataloader.BatchLoader}. This is white box testing somewhat because we could have repeated * ALL the tests in {@link org.dataloader.DataLoaderTest} here as well but chose not to because we KNOW that * DataLoader differs only a little in how it handles the 2 types of loader functions. We choose to grab some * common functionality for repeat testing and otherwise rely on the very complete other tests. */ public class DataLoaderMapBatchLoaderTest { MappedBatchLoader<String, String> evensOnlyMappedBatchLoader = (keys) -> { Map<String, String> mapOfResults = new HashMap<>(); AtomicInteger index = new AtomicInteger(); keys.forEach(k -> { int i = index.getAndIncrement(); if (i % 2 == 0) { mapOfResults.put(k, k); } }); return CompletableFuture.completedFuture(mapOfResults); }; private static <K, V> DataLoader<K, V> idMapLoader(DataLoaderOptions options, List<Collection<K>> loadCalls) { MappedBatchLoader<K, V> kvBatchLoader = (keys) -> { loadCalls.add(new ArrayList<>(keys)); Map<K, V> map = new HashMap<>(); //noinspection unchecked keys.forEach(k -> map.put(k, (V) k)); return CompletableFuture.completedFuture(map); }; return DataLoaderFactory.newMappedDataLoader(kvBatchLoader, options); } private static <K, V> DataLoader<K, V> idMapLoaderBlowsUps( DataLoaderOptions options, List<Collection<K>> loadCalls) { return newDataLoader((keys) -> { loadCalls.add(new ArrayList<>(keys));
return futureError();
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
loader.load("A"); loader.load("B"); loader.loadMany(asList("C", "D")); List<String> results = loader.dispatchAndJoin(); assertThat(results.size(), equalTo(4)); assertThat(results, equalTo(asList("A", null, "C", null))); } @Test public void should_map_Batch_multiple_requests() throws ExecutionException, InterruptedException { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idMapLoader(new DataLoaderOptions(), loadCalls); CompletableFuture<Integer> future1 = identityLoader.load(1); CompletableFuture<Integer> future2 = identityLoader.load(2); identityLoader.dispatch(); await().until(() -> future1.isDone() && future2.isDone()); assertThat(future1.get(), equalTo(1)); assertThat(future2.get(), equalTo(2)); assertThat(loadCalls, equalTo(singletonList(asList(1, 2)))); } @Test public void can_split_max_batch_sizes_correctly() { List<Collection<Integer>> loadCalls = new ArrayList<>();
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // Path: src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; loader.load("A"); loader.load("B"); loader.loadMany(asList("C", "D")); List<String> results = loader.dispatchAndJoin(); assertThat(results.size(), equalTo(4)); assertThat(results, equalTo(asList("A", null, "C", null))); } @Test public void should_map_Batch_multiple_requests() throws ExecutionException, InterruptedException { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idMapLoader(new DataLoaderOptions(), loadCalls); CompletableFuture<Integer> future1 = identityLoader.load(1); CompletableFuture<Integer> future2 = identityLoader.load(2); identityLoader.dispatch(); await().until(() -> future1.isDone() && future2.isDone()); assertThat(future1.get(), equalTo(1)); assertThat(future2.get(), equalTo(2)); assertThat(loadCalls, equalTo(singletonList(asList(1, 2)))); } @Test public void can_split_max_batch_sizes_correctly() { List<Collection<Integer>> loadCalls = new ArrayList<>();
DataLoader<Integer, Integer> identityLoader = idMapLoader(newOptions().setMaxBatchSize(5), loadCalls);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
assertThat(results.size(), equalTo(4)); assertThat(results, equalTo(asList("A", null, "C", null))); } @Test public void should_map_Batch_multiple_requests() throws ExecutionException, InterruptedException { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idMapLoader(new DataLoaderOptions(), loadCalls); CompletableFuture<Integer> future1 = identityLoader.load(1); CompletableFuture<Integer> future2 = identityLoader.load(2); identityLoader.dispatch(); await().until(() -> future1.isDone() && future2.isDone()); assertThat(future1.get(), equalTo(1)); assertThat(future2.get(), equalTo(2)); assertThat(loadCalls, equalTo(singletonList(asList(1, 2)))); } @Test public void can_split_max_batch_sizes_correctly() { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idMapLoader(newOptions().setMaxBatchSize(5), loadCalls); for (int i = 0; i < 21; i++) { identityLoader.load(i); } List<Collection<Integer>> expectedCalls = new ArrayList<>();
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // Path: src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; assertThat(results.size(), equalTo(4)); assertThat(results, equalTo(asList("A", null, "C", null))); } @Test public void should_map_Batch_multiple_requests() throws ExecutionException, InterruptedException { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idMapLoader(new DataLoaderOptions(), loadCalls); CompletableFuture<Integer> future1 = identityLoader.load(1); CompletableFuture<Integer> future2 = identityLoader.load(2); identityLoader.dispatch(); await().until(() -> future1.isDone() && future2.isDone()); assertThat(future1.get(), equalTo(1)); assertThat(future2.get(), equalTo(2)); assertThat(loadCalls, equalTo(singletonList(asList(1, 2)))); } @Test public void can_split_max_batch_sizes_correctly() { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> identityLoader = idMapLoader(newOptions().setMaxBatchSize(5), loadCalls); for (int i = 0; i < 21; i++) { identityLoader.load(i); } List<Collection<Integer>> expectedCalls = new ArrayList<>();
expectedCalls.add(listFrom(0, 5));
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
DataLoader<Integer, Integer> identityLoader = idMapLoader(newOptions().setMaxBatchSize(5), loadCalls); for (int i = 0; i < 21; i++) { identityLoader.load(i); } List<Collection<Integer>> expectedCalls = new ArrayList<>(); expectedCalls.add(listFrom(0, 5)); expectedCalls.add(listFrom(5, 10)); expectedCalls.add(listFrom(10, 15)); expectedCalls.add(listFrom(15, 20)); expectedCalls.add(listFrom(20, 21)); List<Integer> result = identityLoader.dispatch().join(); assertThat(result, equalTo(listFrom(0, 21))); assertThat(loadCalls, equalTo(expectedCalls)); } @Test public void should_Propagate_error_to_all_loads() { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> errorLoader = idMapLoaderBlowsUps(new DataLoaderOptions(), loadCalls); CompletableFuture<Integer> future1 = errorLoader.load(1); CompletableFuture<Integer> future2 = errorLoader.load(2); errorLoader.dispatch(); await().until(future1::isDone); assertThat(future1.isCompletedExceptionally(), is(true));
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <V> CompletableFuture<V> futureError() { // return failedFuture(new IllegalStateException("Error")); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static Collection<Integer> listFrom(int i, int max) { // List<Integer> ints = new ArrayList<>(); // for (int j = i; j < max; j++) { // ints.add(j); // } // return ints; // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // Path: src/test/java/org/dataloader/DataLoaderMapBatchLoaderTest.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.futureError; import static org.dataloader.fixtures.TestKit.listFrom; import static org.dataloader.impl.CompletableFutureKit.cause; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; DataLoader<Integer, Integer> identityLoader = idMapLoader(newOptions().setMaxBatchSize(5), loadCalls); for (int i = 0; i < 21; i++) { identityLoader.load(i); } List<Collection<Integer>> expectedCalls = new ArrayList<>(); expectedCalls.add(listFrom(0, 5)); expectedCalls.add(listFrom(5, 10)); expectedCalls.add(listFrom(10, 15)); expectedCalls.add(listFrom(15, 20)); expectedCalls.add(listFrom(20, 21)); List<Integer> result = identityLoader.dispatch().join(); assertThat(result, equalTo(listFrom(0, 21))); assertThat(loadCalls, equalTo(expectedCalls)); } @Test public void should_Propagate_error_to_all_loads() { List<Collection<Integer>> loadCalls = new ArrayList<>(); DataLoader<Integer, Integer> errorLoader = idMapLoaderBlowsUps(new DataLoaderOptions(), loadCalls); CompletableFuture<Integer> future1 = errorLoader.load(1); CompletableFuture<Integer> future2 = errorLoader.load(2); errorLoader.dispatch(); await().until(future1::isDone); assertThat(future1.isCompletedExceptionally(), is(true));
Throwable cause = cause(future1);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderRegistryTest.java
// Path: src/main/java/org/dataloader/stats/Statistics.java // @PublicApi // public class Statistics { // // private final long loadCount; // private final long loadErrorCount; // private final long batchInvokeCount; // private final long batchLoadCount; // private final long batchLoadExceptionCount; // private final long cacheHitCount; // // /** // * Zero statistics // */ // public Statistics() { // this(0, 0, 0, 0, 0, 0); // } // // public Statistics(long loadCount, long loadErrorCount, long batchInvokeCount, long batchLoadCount, long batchLoadExceptionCount, long cacheHitCount) { // this.loadCount = loadCount; // this.batchInvokeCount = batchInvokeCount; // this.batchLoadCount = batchLoadCount; // this.cacheHitCount = cacheHitCount; // this.batchLoadExceptionCount = batchLoadExceptionCount; // this.loadErrorCount = loadErrorCount; // } // // /** // * A helper to divide two numbers and handle zero // * // * @param numerator the top bit // * @param denominator the bottom bit // * // * @return numerator / denominator returning zero when denominator is zero // */ // public double ratio(long numerator, long denominator) { // return denominator == 0 ? 0f : ((double) numerator) / ((double) denominator); // } // // /** // * @return the number of objects {@link org.dataloader.DataLoader#load(Object)} has been asked to load // */ // public long getLoadCount() { // return loadCount; // } // // /** // * @return the number of times the {@link org.dataloader.DataLoader} batch loader function return an specific object that was in error // */ // public long getLoadErrorCount() { // return loadErrorCount; // } // // /** // * @return loadErrorCount / loadCount // */ // public double getLoadErrorRatio() { // return ratio(loadErrorCount, loadCount); // } // // /** // * @return the number of times the {@link org.dataloader.DataLoader} batch loader function has been called // */ // public long getBatchInvokeCount() { // return batchInvokeCount; // } // // /** // * @return the number of objects that the {@link org.dataloader.DataLoader} batch loader function has been asked to load // */ // public long getBatchLoadCount() { // return batchLoadCount; // } // // /** // * @return batchLoadCount / loadCount // */ // public double getBatchLoadRatio() { // return ratio(batchLoadCount, loadCount); // } // // /** // * @return the number of times the {@link org.dataloader.DataLoader} batch loader function throw an exception when trying to get any values // */ // public long getBatchLoadExceptionCount() { // return batchLoadExceptionCount; // } // // /** // * @return batchLoadExceptionCount / loadCount // */ // public double getBatchLoadExceptionRatio() { // return ratio(batchLoadExceptionCount, loadCount); // } // // /** // * @return the number of times {@link org.dataloader.DataLoader#load(Object)} resulted in a cache hit // */ // public long getCacheHitCount() { // return cacheHitCount; // } // // /** // * @return then number of times we missed the cache during {@link org.dataloader.DataLoader#load(Object)} // */ // public long getCacheMissCount() { // return loadCount - cacheHitCount; // } // // /** // * @return cacheHits / loadCount // */ // public double getCacheHitRatio() { // return ratio(cacheHitCount, loadCount); // } // // // /** // * This will combine this set of statistics with another set of statistics so that they become the combined count of each // * // * @param other the other statistics to combine // * // * @return a new statistics object of the combined counts // */ // public Statistics combine(Statistics other) { // return new Statistics( // this.loadCount + other.getLoadCount(), // this.loadErrorCount + other.getLoadErrorCount(), // this.batchInvokeCount + other.getBatchInvokeCount(), // this.batchLoadCount + other.getBatchLoadCount(), // this.batchLoadExceptionCount + other.getBatchLoadExceptionCount(), // this.cacheHitCount + other.getCacheHitCount() // ); // } // // /** // * @return a map representation of the statistics, perhaps to send over JSON or some such // */ // public Map<String, Number> toMap() { // Map<String, Number> stats = new LinkedHashMap<>(); // stats.put("loadCount", getLoadCount()); // stats.put("loadErrorCount", getLoadErrorCount()); // stats.put("loadErrorRatio", getLoadErrorRatio()); // // stats.put("batchInvokeCount", getBatchInvokeCount()); // stats.put("batchLoadCount", getBatchLoadCount()); // stats.put("batchLoadRatio", getBatchLoadRatio()); // stats.put("batchLoadExceptionCount", getBatchLoadExceptionCount()); // stats.put("batchLoadExceptionRatio", getBatchLoadExceptionRatio()); // // stats.put("cacheHitCount", getCacheHitCount()); // stats.put("cacheHitRatio", getCacheHitRatio()); // return stats; // } // // @Override // public String toString() { // return "Statistics{" + // "loadCount=" + loadCount + // ", loadErrorCount=" + loadErrorCount + // ", batchLoadCount=" + batchLoadCount + // ", batchLoadExceptionCount=" + batchLoadExceptionCount + // ", cacheHitCount=" + cacheHitCount + // '}'; // } // } // // Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // }
import org.dataloader.stats.Statistics; import org.junit.Test; import java.util.concurrent.CompletableFuture; import static java.util.Arrays.asList; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat;
package org.dataloader; public class DataLoaderRegistryTest { final BatchLoader<Object, Object> identityBatchLoader = CompletableFuture::completedFuture; @Test public void registration_works() {
// Path: src/main/java/org/dataloader/stats/Statistics.java // @PublicApi // public class Statistics { // // private final long loadCount; // private final long loadErrorCount; // private final long batchInvokeCount; // private final long batchLoadCount; // private final long batchLoadExceptionCount; // private final long cacheHitCount; // // /** // * Zero statistics // */ // public Statistics() { // this(0, 0, 0, 0, 0, 0); // } // // public Statistics(long loadCount, long loadErrorCount, long batchInvokeCount, long batchLoadCount, long batchLoadExceptionCount, long cacheHitCount) { // this.loadCount = loadCount; // this.batchInvokeCount = batchInvokeCount; // this.batchLoadCount = batchLoadCount; // this.cacheHitCount = cacheHitCount; // this.batchLoadExceptionCount = batchLoadExceptionCount; // this.loadErrorCount = loadErrorCount; // } // // /** // * A helper to divide two numbers and handle zero // * // * @param numerator the top bit // * @param denominator the bottom bit // * // * @return numerator / denominator returning zero when denominator is zero // */ // public double ratio(long numerator, long denominator) { // return denominator == 0 ? 0f : ((double) numerator) / ((double) denominator); // } // // /** // * @return the number of objects {@link org.dataloader.DataLoader#load(Object)} has been asked to load // */ // public long getLoadCount() { // return loadCount; // } // // /** // * @return the number of times the {@link org.dataloader.DataLoader} batch loader function return an specific object that was in error // */ // public long getLoadErrorCount() { // return loadErrorCount; // } // // /** // * @return loadErrorCount / loadCount // */ // public double getLoadErrorRatio() { // return ratio(loadErrorCount, loadCount); // } // // /** // * @return the number of times the {@link org.dataloader.DataLoader} batch loader function has been called // */ // public long getBatchInvokeCount() { // return batchInvokeCount; // } // // /** // * @return the number of objects that the {@link org.dataloader.DataLoader} batch loader function has been asked to load // */ // public long getBatchLoadCount() { // return batchLoadCount; // } // // /** // * @return batchLoadCount / loadCount // */ // public double getBatchLoadRatio() { // return ratio(batchLoadCount, loadCount); // } // // /** // * @return the number of times the {@link org.dataloader.DataLoader} batch loader function throw an exception when trying to get any values // */ // public long getBatchLoadExceptionCount() { // return batchLoadExceptionCount; // } // // /** // * @return batchLoadExceptionCount / loadCount // */ // public double getBatchLoadExceptionRatio() { // return ratio(batchLoadExceptionCount, loadCount); // } // // /** // * @return the number of times {@link org.dataloader.DataLoader#load(Object)} resulted in a cache hit // */ // public long getCacheHitCount() { // return cacheHitCount; // } // // /** // * @return then number of times we missed the cache during {@link org.dataloader.DataLoader#load(Object)} // */ // public long getCacheMissCount() { // return loadCount - cacheHitCount; // } // // /** // * @return cacheHits / loadCount // */ // public double getCacheHitRatio() { // return ratio(cacheHitCount, loadCount); // } // // // /** // * This will combine this set of statistics with another set of statistics so that they become the combined count of each // * // * @param other the other statistics to combine // * // * @return a new statistics object of the combined counts // */ // public Statistics combine(Statistics other) { // return new Statistics( // this.loadCount + other.getLoadCount(), // this.loadErrorCount + other.getLoadErrorCount(), // this.batchInvokeCount + other.getBatchInvokeCount(), // this.batchLoadCount + other.getBatchLoadCount(), // this.batchLoadExceptionCount + other.getBatchLoadExceptionCount(), // this.cacheHitCount + other.getCacheHitCount() // ); // } // // /** // * @return a map representation of the statistics, perhaps to send over JSON or some such // */ // public Map<String, Number> toMap() { // Map<String, Number> stats = new LinkedHashMap<>(); // stats.put("loadCount", getLoadCount()); // stats.put("loadErrorCount", getLoadErrorCount()); // stats.put("loadErrorRatio", getLoadErrorRatio()); // // stats.put("batchInvokeCount", getBatchInvokeCount()); // stats.put("batchLoadCount", getBatchLoadCount()); // stats.put("batchLoadRatio", getBatchLoadRatio()); // stats.put("batchLoadExceptionCount", getBatchLoadExceptionCount()); // stats.put("batchLoadExceptionRatio", getBatchLoadExceptionRatio()); // // stats.put("cacheHitCount", getCacheHitCount()); // stats.put("cacheHitRatio", getCacheHitRatio()); // return stats; // } // // @Override // public String toString() { // return "Statistics{" + // "loadCount=" + loadCount + // ", loadErrorCount=" + loadErrorCount + // ", batchLoadCount=" + batchLoadCount + // ", batchLoadExceptionCount=" + batchLoadExceptionCount + // ", cacheHitCount=" + cacheHitCount + // '}'; // } // } // // Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // Path: src/test/java/org/dataloader/DataLoaderRegistryTest.java import org.dataloader.stats.Statistics; import org.junit.Test; import java.util.concurrent.CompletableFuture; import static java.util.Arrays.asList; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; package org.dataloader; public class DataLoaderRegistryTest { final BatchLoader<Object, Object> identityBatchLoader = CompletableFuture::completedFuture; @Test public void registration_works() {
DataLoader<Object, Object> dlA = newDataLoader(identityBatchLoader);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderBatchLoaderEnvironmentTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoader<K, V> batchLoadFunction) { // return newMappedDataLoader(batchLoadFunction, null); // }
import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderFactory.newMappedDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package org.dataloader; /** * Tests related to context. DataLoaderTest is getting to big and needs refactoring */ public class DataLoaderBatchLoaderEnvironmentTest { private BatchLoaderWithContext<String, String> contextBatchLoader() { return (keys, environment) -> { AtomicInteger index = new AtomicInteger(0); List<String> list = keys.stream().map(k -> { int i = index.getAndIncrement(); Object context = environment.getContext(); Object keyContextM = environment.getKeyContexts().get(k); Object keyContextL = environment.getKeyContextsList().get(i); return k + "-" + context + "-m:" + keyContextM + "-l:" + keyContextL; }).collect(Collectors.toList()); return CompletableFuture.completedFuture(list); }; } @Test public void context_is_passed_to_batch_loader_function() { BatchLoaderWithContext<String, String> batchLoader = (keys, environment) -> { List<String> list = keys.stream().map(k -> k + "-" + environment.getContext()).collect(Collectors.toList()); return CompletableFuture.completedFuture(list); }; DataLoaderOptions options = DataLoaderOptions.newOptions() .setBatchLoaderContextProvider(() -> "ctx");
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoader<K, V> batchLoadFunction) { // return newMappedDataLoader(batchLoadFunction, null); // } // Path: src/test/java/org/dataloader/DataLoaderBatchLoaderEnvironmentTest.java import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderFactory.newMappedDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package org.dataloader; /** * Tests related to context. DataLoaderTest is getting to big and needs refactoring */ public class DataLoaderBatchLoaderEnvironmentTest { private BatchLoaderWithContext<String, String> contextBatchLoader() { return (keys, environment) -> { AtomicInteger index = new AtomicInteger(0); List<String> list = keys.stream().map(k -> { int i = index.getAndIncrement(); Object context = environment.getContext(); Object keyContextM = environment.getKeyContexts().get(k); Object keyContextL = environment.getKeyContextsList().get(i); return k + "-" + context + "-m:" + keyContextM + "-l:" + keyContextL; }).collect(Collectors.toList()); return CompletableFuture.completedFuture(list); }; } @Test public void context_is_passed_to_batch_loader_function() { BatchLoaderWithContext<String, String> batchLoader = (keys, environment) -> { List<String> list = keys.stream().map(k -> k + "-" + environment.getContext()).collect(Collectors.toList()); return CompletableFuture.completedFuture(list); }; DataLoaderOptions options = DataLoaderOptions.newOptions() .setBatchLoaderContextProvider(() -> "ctx");
DataLoader<String, String> loader = newDataLoader(batchLoader, options);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderBatchLoaderEnvironmentTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoader<K, V> batchLoadFunction) { // return newMappedDataLoader(batchLoadFunction, null); // }
import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderFactory.newMappedDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
@Test public void missing_key_contexts_are_passed_to_batch_loader_function() { BatchLoaderWithContext<String, String> batchLoader = contextBatchLoader(); DataLoaderOptions options = DataLoaderOptions.newOptions() .setBatchLoaderContextProvider(() -> "ctx"); DataLoader<String, String> loader = newDataLoader(batchLoader, options); loader.load("A", "aCtx"); loader.load("B"); loader.loadMany(asList("C", "D"), singletonList("cCtx")); List<String> results = loader.dispatchAndJoin(); assertThat(results, equalTo(asList("A-ctx-m:aCtx-l:aCtx", "B-ctx-m:null-l:null", "C-ctx-m:cCtx-l:cCtx", "D-ctx-m:null-l:null"))); } @Test public void context_is_passed_to_map_batch_loader_function() { MappedBatchLoaderWithContext<String, String> mapBatchLoader = (keys, environment) -> { Map<String, String> map = new HashMap<>(); keys.forEach(k -> { Object context = environment.getContext(); Object keyContext = environment.getKeyContexts().get(k); map.put(k, k + "-" + context + "-" + keyContext); }); return CompletableFuture.completedFuture(map); }; DataLoaderOptions options = DataLoaderOptions.newOptions() .setBatchLoaderContextProvider(() -> "ctx");
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // // Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newMappedDataLoader(MappedBatchLoader<K, V> batchLoadFunction) { // return newMappedDataLoader(batchLoadFunction, null); // } // Path: src/test/java/org/dataloader/DataLoaderBatchLoaderEnvironmentTest.java import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.dataloader.DataLoaderFactory.newMappedDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @Test public void missing_key_contexts_are_passed_to_batch_loader_function() { BatchLoaderWithContext<String, String> batchLoader = contextBatchLoader(); DataLoaderOptions options = DataLoaderOptions.newOptions() .setBatchLoaderContextProvider(() -> "ctx"); DataLoader<String, String> loader = newDataLoader(batchLoader, options); loader.load("A", "aCtx"); loader.load("B"); loader.loadMany(asList("C", "D"), singletonList("cCtx")); List<String> results = loader.dispatchAndJoin(); assertThat(results, equalTo(asList("A-ctx-m:aCtx-l:aCtx", "B-ctx-m:null-l:null", "C-ctx-m:cCtx-l:cCtx", "D-ctx-m:null-l:null"))); } @Test public void context_is_passed_to_map_batch_loader_function() { MappedBatchLoaderWithContext<String, String> mapBatchLoader = (keys, environment) -> { Map<String, String> map = new HashMap<>(); keys.forEach(k -> { Object context = environment.getContext(); Object keyContext = environment.getKeyContexts().get(k); map.put(k, k + "-" + context + "-" + keyContext); }); return CompletableFuture.completedFuture(map); }; DataLoaderOptions options = DataLoaderOptions.newOptions() .setBatchLoaderContextProvider(() -> "ctx");
DataLoader<String, String> loader = newMappedDataLoader(mapBatchLoader, options);
graphql-java/java-dataloader
src/main/java/org/dataloader/BatchLoaderEnvironment.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // }
import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
/** * Each call to {@link org.dataloader.DataLoader#load(Object, Object)} or * {@link org.dataloader.DataLoader#loadMany(java.util.List, java.util.List)} can be given * a context object when it is invoked. A list of them is present by this method. * * @return a list of key context objects in the order they where encountered */ public List<Object> getKeyContextsList() { return keyContextsList; } public static Builder newBatchLoaderEnvironment() { return new Builder(); } public static class Builder { private Object context; private Map<Object, Object> keyContexts = Collections.emptyMap(); private List<Object> keyContextsList = Collections.emptyList(); private Builder() { } public Builder context(Object context) { this.context = context; return this; } public <K> Builder keyContexts(List<K> keys, List<Object> keyContexts) {
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // Path: src/main/java/org/dataloader/BatchLoaderEnvironment.java import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Each call to {@link org.dataloader.DataLoader#load(Object, Object)} or * {@link org.dataloader.DataLoader#loadMany(java.util.List, java.util.List)} can be given * a context object when it is invoked. A list of them is present by this method. * * @return a list of key context objects in the order they where encountered */ public List<Object> getKeyContextsList() { return keyContextsList; } public static Builder newBatchLoaderEnvironment() { return new Builder(); } public static class Builder { private Object context; private Map<Object, Object> keyContexts = Collections.emptyMap(); private List<Object> keyContextsList = Collections.emptyList(); private Builder() { } public Builder context(Object context) { this.context = context; return this; } public <K> Builder keyContexts(List<K> keys, List<Object> keyContexts) {
Assertions.nonNull(keys);
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderHelper.java
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull;
package org.dataloader; /** * This helps break up the large DataLoader class functionality and it contains the logic to dispatch the * promises on behalf of its peer dataloader * * @param <K> the type of keys * @param <V> the type of values */ @Internal class DataLoaderHelper<K, V> { static class LoaderQueueEntry<K, V> { final K key; final V value; final Object callContext; public LoaderQueueEntry(K key, V value, Object callContext) { this.key = key; this.value = value; this.callContext = callContext; } K getKey() { return key; } V getValue() { return value; } Object getCallContext() { return callContext; } } private final DataLoader<K, V> dataLoader; private final Object batchLoadFunction; private final DataLoaderOptions loaderOptions; private final CacheMap<Object, V> futureCache; private final ValueCache<K, V> valueCache; private final List<LoaderQueueEntry<K, CompletableFuture<V>>> loaderQueue;
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderHelper.java import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull; package org.dataloader; /** * This helps break up the large DataLoader class functionality and it contains the logic to dispatch the * promises on behalf of its peer dataloader * * @param <K> the type of keys * @param <V> the type of values */ @Internal class DataLoaderHelper<K, V> { static class LoaderQueueEntry<K, V> { final K key; final V value; final Object callContext; public LoaderQueueEntry(K key, V value, Object callContext) { this.key = key; this.value = value; this.callContext = callContext; } K getKey() { return key; } V getValue() { return value; } Object getCallContext() { return callContext; } } private final DataLoader<K, V> dataLoader; private final Object batchLoadFunction; private final DataLoaderOptions loaderOptions; private final CacheMap<Object, V> futureCache; private final ValueCache<K, V> valueCache; private final List<LoaderQueueEntry<K, CompletableFuture<V>>> loaderQueue;
private final StatisticsCollector stats;
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderHelper.java
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull;
Object batchLoadFunction, DataLoaderOptions loaderOptions, CacheMap<Object, V> futureCache, ValueCache<K, V> valueCache, StatisticsCollector stats, Clock clock) { this.dataLoader = dataLoader; this.batchLoadFunction = batchLoadFunction; this.loaderOptions = loaderOptions; this.futureCache = futureCache; this.valueCache = valueCache; this.loaderQueue = new ArrayList<>(); this.stats = stats; this.clock = clock; this.lastDispatchTime = new AtomicReference<>(); this.lastDispatchTime.set(now()); } Instant now() { return clock.instant(); } public Instant getLastDispatchTime() { return lastDispatchTime.get(); } Optional<CompletableFuture<V>> getIfPresent(K key) { synchronized (dataLoader) { boolean cachingEnabled = loaderOptions.cachingEnabled(); if (cachingEnabled) {
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderHelper.java import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull; Object batchLoadFunction, DataLoaderOptions loaderOptions, CacheMap<Object, V> futureCache, ValueCache<K, V> valueCache, StatisticsCollector stats, Clock clock) { this.dataLoader = dataLoader; this.batchLoadFunction = batchLoadFunction; this.loaderOptions = loaderOptions; this.futureCache = futureCache; this.valueCache = valueCache; this.loaderQueue = new ArrayList<>(); this.stats = stats; this.clock = clock; this.lastDispatchTime = new AtomicReference<>(); this.lastDispatchTime.set(now()); } Instant now() { return clock.instant(); } public Instant getLastDispatchTime() { return lastDispatchTime.get(); } Optional<CompletableFuture<V>> getIfPresent(K key) { synchronized (dataLoader) { boolean cachingEnabled = loaderOptions.cachingEnabled(); if (cachingEnabled) {
Object cacheKey = getCacheKey(nonNull(key));
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderHelper.java
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull;
future.complete(tryValue.get()); } else { stats.incrementLoadErrorCount(); future.completeExceptionally(tryValue.getThrowable()); clearCacheKeys.add(keys.get(idx)); } } else { future.complete(value); } } possiblyClearCacheEntriesOnExceptions(clearCacheKeys); return values; }).exceptionally(ex -> { stats.incrementBatchLoadExceptionCount(); if (ex instanceof CompletionException) { ex = ex.getCause(); } for (int idx = 0; idx < queuedFutures.size(); idx++) { K key = keys.get(idx); CompletableFuture<V> future = queuedFutures.get(idx); future.completeExceptionally(ex); // clear any cached view of this key because they all failed dataLoader.clear(key); } return emptyList(); }); } private void assertResultSize(List<K> keys, List<V> values) {
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderHelper.java import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull; future.complete(tryValue.get()); } else { stats.incrementLoadErrorCount(); future.completeExceptionally(tryValue.getThrowable()); clearCacheKeys.add(keys.get(idx)); } } else { future.complete(value); } } possiblyClearCacheEntriesOnExceptions(clearCacheKeys); return values; }).exceptionally(ex -> { stats.incrementBatchLoadExceptionCount(); if (ex instanceof CompletionException) { ex = ex.getCause(); } for (int idx = 0; idx < queuedFutures.size(); idx++) { K key = keys.get(idx); CompletableFuture<V> future = queuedFutures.get(idx); future.completeExceptionally(ex); // clear any cached view of this key because they all failed dataLoader.clear(key); } return emptyList(); }); } private void assertResultSize(List<K> keys, List<V> values) {
assertState(keys.size() == values.size(), () -> "The size of the promised values MUST be the same size as the key list");
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderHelper.java
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull;
assertResultSize(missedKeys, missedValues); for (int i = 0; i < missedValues.size(); i++) { V v = missedValues.get(i); Integer listIndex = missedKeyIndexes.get(i); valuesInKeyOrder.set(listIndex, Try.succeeded(v)); } List<V> assembledValues = valuesInKeyOrder.stream().map(Try::get).collect(toList()); // // fire off a call to the ValueCache to allow it to set values into the // cache now that we have them return setToValueCache(assembledValues, missedKeys, missedValues); }); } }); } CompletableFuture<List<V>> invokeLoader(List<K> keys, List<Object> keyContexts) { CompletableFuture<List<V>> batchLoad; try { Object context = loaderOptions.getBatchLoaderContextProvider().getContext(); BatchLoaderEnvironment environment = BatchLoaderEnvironment.newBatchLoaderEnvironment() .context(context).keyContexts(keys, keyContexts).build(); if (isMapLoader()) { batchLoad = invokeMapBatchLoader(keys, environment); } else { batchLoad = invokeListBatchLoader(keys, environment); } } catch (Exception e) {
// Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // @Internal // public class CompletableFutureKit { // // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // // public static <V> Throwable cause(CompletableFuture<V> completableFuture) { // if (!completableFuture.isCompletedExceptionally()) { // return null; // } // try { // completableFuture.get(); // return null; // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // return e; // } catch (ExecutionException e) { // Throwable cause = e.getCause(); // if (cause != null) { // return cause; // } // return e; // } // } // // public static <V> boolean succeeded(CompletableFuture<V> future) { // return future.isDone() && !future.isCompletedExceptionally(); // } // // public static <V> boolean failed(CompletableFuture<V> future) { // return future.isDone() && future.isCompletedExceptionally(); // } // // public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) { // return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0])) // .thenApply(v -> cfs.stream() // .map(CompletableFuture::join) // .collect(toList()) // ); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderHelper.java import org.dataloader.annotations.GuardedBy; import org.dataloader.annotations.Internal; import org.dataloader.impl.CompletableFutureKit; import org.dataloader.stats.StatisticsCollector; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicReference; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.concurrent.CompletableFuture.allOf; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.stream.Collectors.toList; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull; assertResultSize(missedKeys, missedValues); for (int i = 0; i < missedValues.size(); i++) { V v = missedValues.get(i); Integer listIndex = missedKeyIndexes.get(i); valuesInKeyOrder.set(listIndex, Try.succeeded(v)); } List<V> assembledValues = valuesInKeyOrder.stream().map(Try::get).collect(toList()); // // fire off a call to the ValueCache to allow it to set values into the // cache now that we have them return setToValueCache(assembledValues, missedKeys, missedValues); }); } }); } CompletableFuture<List<V>> invokeLoader(List<K> keys, List<Object> keyContexts) { CompletableFuture<List<V>> batchLoad; try { Object context = loaderOptions.getBatchLoaderContextProvider().getContext(); BatchLoaderEnvironment environment = BatchLoaderEnvironment.newBatchLoaderEnvironment() .context(context).keyContexts(keys, keyContexts).build(); if (isMapLoader()) { batchLoad = invokeMapBatchLoader(keys, environment); } else { batchLoad = invokeListBatchLoader(keys, environment); } } catch (Exception e) {
batchLoad = CompletableFutureKit.failedFuture(e);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderValueCacheTest.java
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // }
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
package org.dataloader; public class DataLoaderValueCacheTest { @Test public void test_by_default_we_have_no_value_caching() { List<List<String>> loadCalls = new ArrayList<>();
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // Path: src/test/java/org/dataloader/DataLoaderValueCacheTest.java import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; package org.dataloader; public class DataLoaderValueCacheTest { @Test public void test_by_default_we_have_no_value_caching() { List<List<String>> loadCalls = new ArrayList<>();
DataLoaderOptions options = newOptions();
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderValueCacheTest.java
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // }
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
package org.dataloader; public class DataLoaderValueCacheTest { @Test public void test_by_default_we_have_no_value_caching() { List<List<String>> loadCalls = new ArrayList<>(); DataLoaderOptions options = newOptions();
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // Path: src/test/java/org/dataloader/DataLoaderValueCacheTest.java import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; package org.dataloader; public class DataLoaderValueCacheTest { @Test public void test_by_default_we_have_no_value_caching() { List<List<String>> loadCalls = new ArrayList<>(); DataLoaderOptions options = newOptions();
DataLoader<String, String> identityLoader = idLoader(options, loadCalls);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderValueCacheTest.java
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // }
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
assertThat(loadCalls, equalTo(asList(asList("a", "b"), singletonList("c")))); assertArrayEquals(customValueCache.store.keySet().toArray(), asList("a", "b", "c").toArray()); // Supports clear CompletableFuture<Void> fC = new CompletableFuture<>(); identityLoader.clear("b", (v, e) -> fC.complete(v)); await().until(fC::isDone); assertArrayEquals(customValueCache.store.keySet().toArray(), asList("a", "c").toArray()); // Supports clear all CompletableFuture<Void> fCa = new CompletableFuture<>(); identityLoader.clearAll((v, e) -> fCa.complete(v)); await().until(fCa::isDone); assertArrayEquals(customValueCache.store.keySet().toArray(), emptyList().toArray()); } @Test public void can_use_caffeine_for_caching() { // // Mostly to prove that some other CACHE library could be used // as the backing value cache. Not really Caffeine specific. // Cache<String, Object> caffeineCache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(100) .build();
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // Path: src/test/java/org/dataloader/DataLoaderValueCacheTest.java import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; assertThat(loadCalls, equalTo(asList(asList("a", "b"), singletonList("c")))); assertArrayEquals(customValueCache.store.keySet().toArray(), asList("a", "b", "c").toArray()); // Supports clear CompletableFuture<Void> fC = new CompletableFuture<>(); identityLoader.clear("b", (v, e) -> fC.complete(v)); await().until(fC::isDone); assertArrayEquals(customValueCache.store.keySet().toArray(), asList("a", "c").toArray()); // Supports clear all CompletableFuture<Void> fCa = new CompletableFuture<>(); identityLoader.clearAll((v, e) -> fCa.complete(v)); await().until(fCa::isDone); assertArrayEquals(customValueCache.store.keySet().toArray(), emptyList().toArray()); } @Test public void can_use_caffeine_for_caching() { // // Mostly to prove that some other CACHE library could be used // as the backing value cache. Not really Caffeine specific. // Cache<String, Object> caffeineCache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .maximumSize(100) .build();
ValueCache<String, Object> caffeineValueCache = new CaffeineValueCache(caffeineCache);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderValueCacheTest.java
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // }
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
return failedFuture(new IllegalStateException("no A")); } return super.set(key, value); } }; List<List<String>> loadCalls = new ArrayList<>(); DataLoaderOptions options = newOptions().setValueCache(customValueCache); DataLoader<String, String> identityLoader = idLoader(options, loadCalls); CompletableFuture<String> fA = identityLoader.load("a"); CompletableFuture<String> fB = identityLoader.load("b"); await().until(identityLoader.dispatch()::isDone); assertThat(fA.join(), equalTo("a")); assertThat(fB.join(), equalTo("b")); // a was not in cache (according to get) and hence needed to be loaded assertThat(loadCalls, equalTo(singletonList(asList("a", "b")))); assertArrayEquals(customValueCache.store.keySet().toArray(), singletonList("b").toArray()); } @Test public void caching_can_take_some_time_complete() { CustomValueCache customValueCache = new CustomValueCache() { @Override public CompletableFuture<Object> get(String key) { if (key.startsWith("miss")) { return CompletableFuture.supplyAsync(() -> {
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // Path: src/test/java/org/dataloader/DataLoaderValueCacheTest.java import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; return failedFuture(new IllegalStateException("no A")); } return super.set(key, value); } }; List<List<String>> loadCalls = new ArrayList<>(); DataLoaderOptions options = newOptions().setValueCache(customValueCache); DataLoader<String, String> identityLoader = idLoader(options, loadCalls); CompletableFuture<String> fA = identityLoader.load("a"); CompletableFuture<String> fB = identityLoader.load("b"); await().until(identityLoader.dispatch()::isDone); assertThat(fA.join(), equalTo("a")); assertThat(fB.join(), equalTo("b")); // a was not in cache (according to get) and hence needed to be loaded assertThat(loadCalls, equalTo(singletonList(asList("a", "b")))); assertArrayEquals(customValueCache.store.keySet().toArray(), singletonList("b").toArray()); } @Test public void caching_can_take_some_time_complete() { CustomValueCache customValueCache = new CustomValueCache() { @Override public CompletableFuture<Object> get(String key) { if (key.startsWith("miss")) { return CompletableFuture.supplyAsync(() -> {
snooze(1000);
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderValueCacheTest.java
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // }
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue;
if (key.startsWith("miss")) { cacheCalls.add(Try.alwaysFailed()); } else { cacheCalls.add(Try.succeeded(key)); } } List<Try<Object>> renegOnContract = cacheCalls.subList(1, cacheCalls.size() - 1); return CompletableFuture.completedFuture(renegOnContract); } }; List<List<String>> loadCalls = new ArrayList<>(); DataLoaderOptions options = newOptions().setValueCache(customValueCache); DataLoader<String, String> identityLoader = idLoader(options, loadCalls); CompletableFuture<String> fA = identityLoader.load("a"); CompletableFuture<String> fB = identityLoader.load("b"); CompletableFuture<String> fC = identityLoader.load("missC"); CompletableFuture<String> fD = identityLoader.load("missD"); await().until(identityLoader.dispatch()::isDone); assertTrue(isAssertionException(fA)); assertTrue(isAssertionException(fB)); assertTrue(isAssertionException(fC)); assertTrue(isAssertionException(fD)); } private boolean isAssertionException(CompletableFuture<String> fA) { Throwable throwable = Try.tryFuture(fA).join().getThrowable();
// Path: src/test/java/org/dataloader/fixtures/CaffeineValueCache.java // public class CaffeineValueCache implements ValueCache<String, Object> { // // public final Cache<String, Object> cache; // // public CaffeineValueCache(Cache<String, Object> cache) { // this.cache = cache; // } // // @Override // public CompletableFuture<Object> get(String key) { // Object value = cache.getIfPresent(key); // if (value == null) { // // we use get exceptions here to indicate not in cache // return CompletableFutureKit.failedFuture(new RuntimeException(key + " not present")); // } // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // cache.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // cache.invalidate(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // cache.invalidateAll(); // return CompletableFuture.completedFuture(null); // } // } // // Path: src/test/java/org/dataloader/fixtures/CustomValueCache.java // public class CustomValueCache implements ValueCache<String, Object> { // // public final Map<String, Object> store = new ConcurrentHashMap<>(); // // @Override // public CompletableFuture<Object> get(String key) { // if (!store.containsKey(key)) { // return CompletableFutureKit.failedFuture(new RuntimeException("The key is missing")); // } // return CompletableFuture.completedFuture(store.get(key)); // } // // @Override // public CompletableFuture<Object> set(String key, Object value) { // store.put(key, value); // return CompletableFuture.completedFuture(value); // } // // @Override // public CompletableFuture<Void> delete(String key) { // store.remove(key); // return CompletableFuture.completedFuture(null); // } // // @Override // public CompletableFuture<Void> clear() { // store.clear(); // return CompletableFuture.completedFuture(null); // } // // public Map<String, Object> asMap() { // return store; // } // } // // Path: src/main/java/org/dataloader/impl/DataLoaderAssertionException.java // public class DataLoaderAssertionException extends IllegalStateException { // public DataLoaderAssertionException(String message) { // super(message); // } // } // // Path: src/main/java/org/dataloader/DataLoaderOptions.java // public static DataLoaderOptions newOptions() { // return new DataLoaderOptions(); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <K, V> DataLoader<K, V> idLoader() { // return idLoader(null, new ArrayList<>()); // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static void snooze(int millis) { // try { // Thread.sleep(millis); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> List<T> sort(Collection<? extends T> collection) { // return collection.stream().sorted().collect(toList()); // } // // Path: src/main/java/org/dataloader/impl/CompletableFutureKit.java // public static <V> CompletableFuture<V> failedFuture(Exception e) { // CompletableFuture<V> future = new CompletableFuture<>(); // future.completeExceptionally(e); // return future; // } // Path: src/test/java/org/dataloader/DataLoaderValueCacheTest.java import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.dataloader.fixtures.CaffeineValueCache; import org.dataloader.fixtures.CustomValueCache; import org.dataloader.impl.DataLoaderAssertionException; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.awaitility.Awaitility.await; import static org.dataloader.DataLoaderOptions.newOptions; import static org.dataloader.fixtures.TestKit.idLoader; import static org.dataloader.fixtures.TestKit.snooze; import static org.dataloader.fixtures.TestKit.sort; import static org.dataloader.impl.CompletableFutureKit.failedFuture; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; if (key.startsWith("miss")) { cacheCalls.add(Try.alwaysFailed()); } else { cacheCalls.add(Try.succeeded(key)); } } List<Try<Object>> renegOnContract = cacheCalls.subList(1, cacheCalls.size() - 1); return CompletableFuture.completedFuture(renegOnContract); } }; List<List<String>> loadCalls = new ArrayList<>(); DataLoaderOptions options = newOptions().setValueCache(customValueCache); DataLoader<String, String> identityLoader = idLoader(options, loadCalls); CompletableFuture<String> fA = identityLoader.load("a"); CompletableFuture<String> fB = identityLoader.load("b"); CompletableFuture<String> fC = identityLoader.load("missC"); CompletableFuture<String> fD = identityLoader.load("missD"); await().until(identityLoader.dispatch()::isDone); assertTrue(isAssertionException(fA)); assertTrue(isAssertionException(fB)); assertTrue(isAssertionException(fC)); assertTrue(isAssertionException(fD)); } private boolean isAssertionException(CompletableFuture<String> fA) { Throwable throwable = Try.tryFuture(fA).join().getThrowable();
return throwable instanceof DataLoaderAssertionException;
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderIfPresentTest.java
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // }
import org.junit.Test; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat;
package org.dataloader; /** * Tests for IfPresent and IfCompleted functionality. */ public class DataLoaderIfPresentTest { private <T> BatchLoader<T, T> keysAsValues() { return CompletableFuture::completedFuture; } @Test public void should_detect_if_present_cf() {
// Path: src/main/java/org/dataloader/DataLoaderFactory.java // public static <K, V> DataLoader<K, V> newDataLoader(BatchLoader<K, V> batchLoadFunction) { // return newDataLoader(batchLoadFunction, null); // } // Path: src/test/java/org/dataloader/DataLoaderIfPresentTest.java import org.junit.Test; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static org.dataloader.DataLoaderFactory.newDataLoader; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; package org.dataloader; /** * Tests for IfPresent and IfCompleted functionality. */ public class DataLoaderIfPresentTest { private <T> BatchLoader<T, T> keysAsValues() { return CompletableFuture::completedFuture; } @Test public void should_detect_if_present_cf() {
DataLoader<Integer, Integer> dataLoader = newDataLoader(keysAsValues());
graphql-java/java-dataloader
src/main/java/org/dataloader/Try.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.PublicApi; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull;
package org.dataloader; /** * Try is class that allows you to hold the result of computation or the throwable it produced. * * This class is useful in {@link org.dataloader.BatchLoader}s so you can mix a batch of calls where some of * the calls succeeded and some of them failed. You would make your batch loader declaration like : * * <pre> * {@code BatchLoader<K,Try<V> batchLoader = new BatchLoader() { ... } } * </pre> * * {@link org.dataloader.DataLoader} understands the use of Try and will take the exceptional path and complete * the value promise with that exception value. */ @PublicApi public class Try<V> { private final static Object NIL = new Object() { }; private final static Throwable NIL_THROWABLE = new RuntimeException() { @Override public String getMessage() { return "failure"; } @Override public synchronized Throwable fillInStackTrace() { return this; } }; private final Throwable throwable; private final V value; @SuppressWarnings("unchecked") private Try(Throwable throwable) {
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/Try.java import org.dataloader.annotations.PublicApi; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull; package org.dataloader; /** * Try is class that allows you to hold the result of computation or the throwable it produced. * * This class is useful in {@link org.dataloader.BatchLoader}s so you can mix a batch of calls where some of * the calls succeeded and some of them failed. You would make your batch loader declaration like : * * <pre> * {@code BatchLoader<K,Try<V> batchLoader = new BatchLoader() { ... } } * </pre> * * {@link org.dataloader.DataLoader} understands the use of Try and will take the exceptional path and complete * the value promise with that exception value. */ @PublicApi public class Try<V> { private final static Object NIL = new Object() { }; private final static Throwable NIL_THROWABLE = new RuntimeException() { @Override public String getMessage() { return "failure"; } @Override public synchronized Throwable fillInStackTrace() { return this; } }; private final Throwable throwable; private final V value; @SuppressWarnings("unchecked") private Try(Throwable throwable) {
this.throwable = nonNull(throwable);
graphql-java/java-dataloader
src/main/java/org/dataloader/impl/PromisedValuesImpl.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.Internal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.stream.Collectors; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull;
package org.dataloader.impl; @Internal public class PromisedValuesImpl<T> implements PromisedValues<T> { private final List<? extends CompletionStage<T>> futures; private final CompletionStage<Void> controller; private final AtomicReference<Throwable> cause; private PromisedValuesImpl(List<? extends CompletionStage<T>> cs) {
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/impl/PromisedValuesImpl.java import org.dataloader.annotations.Internal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.stream.Collectors; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull; package org.dataloader.impl; @Internal public class PromisedValuesImpl<T> implements PromisedValues<T> { private final List<? extends CompletionStage<T>> futures; private final CompletionStage<Void> controller; private final AtomicReference<Throwable> cause; private PromisedValuesImpl(List<? extends CompletionStage<T>> cs) {
this.futures = nonNull(cs);
graphql-java/java-dataloader
src/main/java/org/dataloader/impl/PromisedValuesImpl.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.Internal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.stream.Collectors; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull;
return isDone() && cause.get() == null; } @Override public boolean failed() { return isDone() && cause.get() != null; } @Override public boolean isDone() { return controller.toCompletableFuture().isDone(); } @Override public Throwable cause() { return cause.get(); } @Override public boolean succeeded(int index) { return CompletableFutureKit.succeeded(futures.get(index).toCompletableFuture()); } @Override public Throwable cause(int index) { return CompletableFutureKit.cause(futures.get(index).toCompletableFuture()); } @Override public T get(int index) {
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/impl/PromisedValuesImpl.java import org.dataloader.annotations.Internal; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.stream.Collectors; import static org.dataloader.impl.Assertions.assertState; import static org.dataloader.impl.Assertions.nonNull; return isDone() && cause.get() == null; } @Override public boolean failed() { return isDone() && cause.get() != null; } @Override public boolean isDone() { return controller.toCompletableFuture().isDone(); } @Override public Throwable cause() { return cause.get(); } @Override public boolean succeeded(int index) { return CompletableFutureKit.succeeded(futures.get(index).toCompletableFuture()); } @Override public Throwable cause(int index) { return CompletableFutureKit.cause(futures.get(index).toCompletableFuture()); } @Override public T get(int index) {
assertState(isDone(), () -> "The PromisedValues MUST be complete before calling the get() method");
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderTimeTest.java
// Path: src/test/java/org/dataloader/fixtures/TestingClock.java // public class TestingClock extends Clock { // // private Clock clock; // // public TestingClock() { // clock = Clock.fixed(Instant.ofEpochMilli(0), ZoneId.systemDefault()); // } // // public Clock jump(int millisDelta) { // clock = Clock.offset(clock, Duration.ofMillis(millisDelta)); // return clock; // } // // @Override // public ZoneId getZone() { // return clock.getZone(); // } // // @Override // public Clock withZone(ZoneId zone) { // return clock.withZone(zone); // } // // @Override // public Instant instant() { // return clock.instant(); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> BatchLoader<T, T> keysAsValues() { // return CompletableFuture::completedFuture; // }
import org.dataloader.fixtures.TestingClock; import org.junit.Test; import java.time.Instant; import static org.dataloader.fixtures.TestKit.keysAsValues; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package org.dataloader; @SuppressWarnings("UnusedReturnValue") public class DataLoaderTimeTest { @Test public void should_set_and_instant_if_dispatched() {
// Path: src/test/java/org/dataloader/fixtures/TestingClock.java // public class TestingClock extends Clock { // // private Clock clock; // // public TestingClock() { // clock = Clock.fixed(Instant.ofEpochMilli(0), ZoneId.systemDefault()); // } // // public Clock jump(int millisDelta) { // clock = Clock.offset(clock, Duration.ofMillis(millisDelta)); // return clock; // } // // @Override // public ZoneId getZone() { // return clock.getZone(); // } // // @Override // public Clock withZone(ZoneId zone) { // return clock.withZone(zone); // } // // @Override // public Instant instant() { // return clock.instant(); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> BatchLoader<T, T> keysAsValues() { // return CompletableFuture::completedFuture; // } // Path: src/test/java/org/dataloader/DataLoaderTimeTest.java import org.dataloader.fixtures.TestingClock; import org.junit.Test; import java.time.Instant; import static org.dataloader.fixtures.TestKit.keysAsValues; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package org.dataloader; @SuppressWarnings("UnusedReturnValue") public class DataLoaderTimeTest { @Test public void should_set_and_instant_if_dispatched() {
TestingClock clock = new TestingClock();
graphql-java/java-dataloader
src/test/java/org/dataloader/DataLoaderTimeTest.java
// Path: src/test/java/org/dataloader/fixtures/TestingClock.java // public class TestingClock extends Clock { // // private Clock clock; // // public TestingClock() { // clock = Clock.fixed(Instant.ofEpochMilli(0), ZoneId.systemDefault()); // } // // public Clock jump(int millisDelta) { // clock = Clock.offset(clock, Duration.ofMillis(millisDelta)); // return clock; // } // // @Override // public ZoneId getZone() { // return clock.getZone(); // } // // @Override // public Clock withZone(ZoneId zone) { // return clock.withZone(zone); // } // // @Override // public Instant instant() { // return clock.instant(); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> BatchLoader<T, T> keysAsValues() { // return CompletableFuture::completedFuture; // }
import org.dataloader.fixtures.TestingClock; import org.junit.Test; import java.time.Instant; import static org.dataloader.fixtures.TestKit.keysAsValues; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package org.dataloader; @SuppressWarnings("UnusedReturnValue") public class DataLoaderTimeTest { @Test public void should_set_and_instant_if_dispatched() { TestingClock clock = new TestingClock();
// Path: src/test/java/org/dataloader/fixtures/TestingClock.java // public class TestingClock extends Clock { // // private Clock clock; // // public TestingClock() { // clock = Clock.fixed(Instant.ofEpochMilli(0), ZoneId.systemDefault()); // } // // public Clock jump(int millisDelta) { // clock = Clock.offset(clock, Duration.ofMillis(millisDelta)); // return clock; // } // // @Override // public ZoneId getZone() { // return clock.getZone(); // } // // @Override // public Clock withZone(ZoneId zone) { // return clock.withZone(zone); // } // // @Override // public Instant instant() { // return clock.instant(); // } // } // // Path: src/test/java/org/dataloader/fixtures/TestKit.java // public static <T> BatchLoader<T, T> keysAsValues() { // return CompletableFuture::completedFuture; // } // Path: src/test/java/org/dataloader/DataLoaderTimeTest.java import org.dataloader.fixtures.TestingClock; import org.junit.Test; import java.time.Instant; import static org.dataloader.fixtures.TestKit.keysAsValues; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package org.dataloader; @SuppressWarnings("UnusedReturnValue") public class DataLoaderTimeTest { @Test public void should_set_and_instant_if_dispatched() { TestingClock clock = new TestingClock();
DataLoader<Integer, Integer> dataLoader = new ClockDataLoader<>(keysAsValues(), clock);
graphql-java/java-dataloader
src/main/java/org/dataloader/stats/DelegatingStatisticsCollector.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import static org.dataloader.impl.Assertions.nonNull;
package org.dataloader.stats; /** * This statistics collector keeps dataloader statistics AND also calls the delegate * collector at the same time. This allows you to keep a specific set of statistics * and also delegate the calls onto another collector. */ public class DelegatingStatisticsCollector implements StatisticsCollector { private final StatisticsCollector collector = new SimpleStatisticsCollector(); private final StatisticsCollector delegateCollector; /** * @param delegateCollector a non null delegate collector */ public DelegatingStatisticsCollector(StatisticsCollector delegateCollector) {
// Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/stats/DelegatingStatisticsCollector.java import static org.dataloader.impl.Assertions.nonNull; package org.dataloader.stats; /** * This statistics collector keeps dataloader statistics AND also calls the delegate * collector at the same time. This allows you to keep a specific set of statistics * and also delegate the calls onto another collector. */ public class DelegatingStatisticsCollector implements StatisticsCollector { private final StatisticsCollector collector = new SimpleStatisticsCollector(); private final StatisticsCollector delegateCollector; /** * @param delegateCollector a non null delegate collector */ public DelegatingStatisticsCollector(StatisticsCollector delegateCollector) {
this.delegateCollector = nonNull(delegateCollector);
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderOptions.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * Configuration options for {@link DataLoader} instances. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @PublicApi public class DataLoaderOptions { private static final BatchLoaderContextProvider NULL_PROVIDER = () -> null; private boolean batchingEnabled; private boolean cachingEnabled; private boolean cachingExceptionsEnabled; private CacheKey<?> cacheKeyFunction; private CacheMap<?, ?> cacheMap; private ValueCache<?, ?> valueCache; private int maxBatchSize;
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderOptions.java import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * Configuration options for {@link DataLoader} instances. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @PublicApi public class DataLoaderOptions { private static final BatchLoaderContextProvider NULL_PROVIDER = () -> null; private boolean batchingEnabled; private boolean cachingEnabled; private boolean cachingExceptionsEnabled; private CacheKey<?> cacheKeyFunction; private CacheMap<?, ?> cacheMap; private ValueCache<?, ?> valueCache; private int maxBatchSize;
private Supplier<StatisticsCollector> statisticsCollector;
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderOptions.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * Configuration options for {@link DataLoader} instances. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @PublicApi public class DataLoaderOptions { private static final BatchLoaderContextProvider NULL_PROVIDER = () -> null; private boolean batchingEnabled; private boolean cachingEnabled; private boolean cachingExceptionsEnabled; private CacheKey<?> cacheKeyFunction; private CacheMap<?, ?> cacheMap; private ValueCache<?, ?> valueCache; private int maxBatchSize; private Supplier<StatisticsCollector> statisticsCollector; private BatchLoaderContextProvider environmentProvider; private ValueCacheOptions valueCacheOptions; /** * Creates a new data loader options with default settings. */ public DataLoaderOptions() { batchingEnabled = true; cachingEnabled = true; cachingExceptionsEnabled = true; maxBatchSize = -1;
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderOptions.java import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * Configuration options for {@link DataLoader} instances. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @PublicApi public class DataLoaderOptions { private static final BatchLoaderContextProvider NULL_PROVIDER = () -> null; private boolean batchingEnabled; private boolean cachingEnabled; private boolean cachingExceptionsEnabled; private CacheKey<?> cacheKeyFunction; private CacheMap<?, ?> cacheMap; private ValueCache<?, ?> valueCache; private int maxBatchSize; private Supplier<StatisticsCollector> statisticsCollector; private BatchLoaderContextProvider environmentProvider; private ValueCacheOptions valueCacheOptions; /** * Creates a new data loader options with default settings. */ public DataLoaderOptions() { batchingEnabled = true; cachingEnabled = true; cachingExceptionsEnabled = true; maxBatchSize = -1;
statisticsCollector = SimpleStatisticsCollector::new;
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderOptions.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull;
/* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * Configuration options for {@link DataLoader} instances. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @PublicApi public class DataLoaderOptions { private static final BatchLoaderContextProvider NULL_PROVIDER = () -> null; private boolean batchingEnabled; private boolean cachingEnabled; private boolean cachingExceptionsEnabled; private CacheKey<?> cacheKeyFunction; private CacheMap<?, ?> cacheMap; private ValueCache<?, ?> valueCache; private int maxBatchSize; private Supplier<StatisticsCollector> statisticsCollector; private BatchLoaderContextProvider environmentProvider; private ValueCacheOptions valueCacheOptions; /** * Creates a new data loader options with default settings. */ public DataLoaderOptions() { batchingEnabled = true; cachingEnabled = true; cachingExceptionsEnabled = true; maxBatchSize = -1; statisticsCollector = SimpleStatisticsCollector::new; environmentProvider = NULL_PROVIDER; valueCacheOptions = ValueCacheOptions.newOptions(); } /** * Clones the provided data loader options. * * @param other the other options instance */ public DataLoaderOptions(DataLoaderOptions other) {
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderOptions.java import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull; /* * Copyright (c) 2016 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package org.dataloader; /** * Configuration options for {@link DataLoader} instances. * * @author <a href="https://github.com/aschrijver/">Arnold Schrijver</a> */ @PublicApi public class DataLoaderOptions { private static final BatchLoaderContextProvider NULL_PROVIDER = () -> null; private boolean batchingEnabled; private boolean cachingEnabled; private boolean cachingExceptionsEnabled; private CacheKey<?> cacheKeyFunction; private CacheMap<?, ?> cacheMap; private ValueCache<?, ?> valueCache; private int maxBatchSize; private Supplier<StatisticsCollector> statisticsCollector; private BatchLoaderContextProvider environmentProvider; private ValueCacheOptions valueCacheOptions; /** * Creates a new data loader options with default settings. */ public DataLoaderOptions() { batchingEnabled = true; cachingEnabled = true; cachingExceptionsEnabled = true; maxBatchSize = -1; statisticsCollector = SimpleStatisticsCollector::new; environmentProvider = NULL_PROVIDER; valueCacheOptions = ValueCacheOptions.newOptions(); } /** * Clones the provided data loader options. * * @param other the other options instance */ public DataLoaderOptions(DataLoaderOptions other) {
nonNull(other);
graphql-java/java-dataloader
src/main/java/org/dataloader/DataLoaderOptions.java
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // }
import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull;
return Optional.ofNullable(valueCache); } /** * Sets the value cache implementation to use for caching values, if caching is enabled. * * @param valueCache the value cache instance * * @return the data loader options for fluent coding */ public DataLoaderOptions setValueCache(ValueCache<?, ?> valueCache) { this.valueCache = valueCache; return this; } /** * @return the {@link ValueCacheOptions} that control how the {@link ValueCache} will be used */ public ValueCacheOptions getValueCacheOptions() { return valueCacheOptions; } /** * Sets the {@link ValueCacheOptions} that control how the {@link ValueCache} will be used * * @param valueCacheOptions the value cache options * * @return the data loader options for fluent coding */ public DataLoaderOptions setValueCacheOptions(ValueCacheOptions valueCacheOptions) {
// Path: src/main/java/org/dataloader/impl/Assertions.java // @Internal // public class Assertions { // // public static void assertState(boolean state, Supplier<String> message) { // if (!state) { // throw new DataLoaderAssertionException(message.get()); // } // } // // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // // public static <T> T nonNull(T t, Supplier<String> message) { // if (t == null) { // throw new NullPointerException(message.get()); // } // return t; // } // // } // // Path: src/main/java/org/dataloader/stats/SimpleStatisticsCollector.java // public class SimpleStatisticsCollector implements StatisticsCollector { // private final AtomicLong loadCount = new AtomicLong(); // private final AtomicLong batchInvokeCount = new AtomicLong(); // private final AtomicLong batchLoadCount = new AtomicLong(); // private final AtomicLong cacheHitCount = new AtomicLong(); // private final AtomicLong batchLoadExceptionCount = new AtomicLong(); // private final AtomicLong loadErrorCount = new AtomicLong(); // // @Override // public long incrementLoadCount() { // return loadCount.incrementAndGet(); // } // // // @Override // public long incrementBatchLoadCountBy(long delta) { // batchInvokeCount.incrementAndGet(); // return batchLoadCount.addAndGet(delta); // } // // @Override // public long incrementCacheHitCount() { // return cacheHitCount.incrementAndGet(); // } // // @Override // public long incrementLoadErrorCount() { // return loadErrorCount.incrementAndGet(); // } // // @Override // public long incrementBatchLoadExceptionCount() { // return batchLoadExceptionCount.incrementAndGet(); // } // // @Override // public Statistics getStatistics() { // return new Statistics(loadCount.get(), loadErrorCount.get(), batchInvokeCount.get(), batchLoadCount.get(), batchLoadExceptionCount.get(), cacheHitCount.get()); // } // // @Override // public String toString() { // return getStatistics().toString(); // } // } // // Path: src/main/java/org/dataloader/stats/StatisticsCollector.java // @PublicSpi // public interface StatisticsCollector { // // /** // * Called to increment the number of loads // * // * @return the current value after increment // */ // long incrementLoadCount(); // // /** // * Called to increment the number of loads that resulted in an object deemed in error // * // * @return the current value after increment // */ // long incrementLoadErrorCount(); // // /** // * Called to increment the number of batch loads // * // * @param delta how much to add to the count // * // * @return the current value after increment // */ // long incrementBatchLoadCountBy(long delta); // // /** // * Called to increment the number of batch loads exceptions // * // * @return the current value after increment // */ // long incrementBatchLoadExceptionCount(); // // /** // * Called to increment the number of cache hits // * // * @return the current value after increment // */ // long incrementCacheHitCount(); // // /** // * @return the statistics that have been gathered up to this point in time // */ // Statistics getStatistics(); // } // // Path: src/main/java/org/dataloader/impl/Assertions.java // public static <T> T nonNull(T t) { // return nonNull(t, () -> "nonNull object required"); // } // Path: src/main/java/org/dataloader/DataLoaderOptions.java import org.dataloader.annotations.PublicApi; import org.dataloader.impl.Assertions; import org.dataloader.stats.SimpleStatisticsCollector; import org.dataloader.stats.StatisticsCollector; import java.util.Optional; import java.util.function.Supplier; import static org.dataloader.impl.Assertions.nonNull; return Optional.ofNullable(valueCache); } /** * Sets the value cache implementation to use for caching values, if caching is enabled. * * @param valueCache the value cache instance * * @return the data loader options for fluent coding */ public DataLoaderOptions setValueCache(ValueCache<?, ?> valueCache) { this.valueCache = valueCache; return this; } /** * @return the {@link ValueCacheOptions} that control how the {@link ValueCache} will be used */ public ValueCacheOptions getValueCacheOptions() { return valueCacheOptions; } /** * Sets the {@link ValueCacheOptions} that control how the {@link ValueCache} will be used * * @param valueCacheOptions the value cache options * * @return the data loader options for fluent coding */ public DataLoaderOptions setValueCacheOptions(ValueCacheOptions valueCacheOptions) {
this.valueCacheOptions = Assertions.nonNull(valueCacheOptions);
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/EarModeAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarMode { // // /** Ears enabled. */ // ENABLED, // // /** Ears disabled. */ // DISABLED; // // /** // * Check if this ear mode disables ear movement. // * @return {@code true} if ear movement is disabled // */ // public boolean isDisabled() { // return this == DISABLED; // } // // /** // * Check if this ear mode enables ear movement. // * @return {@code true} if ear movement is enabled // */ // public boolean isEnabled() { // return this == ENABLED; // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarMode; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to change Karotz ear mode in the background. */ public class EarModeAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param mode the ear mode to set */ public EarModeAsyncTask(Activity activity, EarMode mode) { super(activity); this.mode = mode; } /** * This tasks returns the ear mode or ({@code null}) if ear mode could not be changed. */ @Override protected EarMode doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarMode { // // /** Ears enabled. */ // ENABLED, // // /** Ears disabled. */ // DISABLED; // // /** // * Check if this ear mode disables ear movement. // * @return {@code true} if ear movement is disabled // */ // public boolean isDisabled() { // return this == DISABLED; // } // // /** // * Check if this ear mode enables ear movement. // * @return {@code true} if ear movement is enabled // */ // public boolean isEnabled() { // return this == ENABLED; // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/EarModeAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarMode; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to change Karotz ear mode in the background. */ public class EarModeAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param mode the ear mode to set */ public EarModeAsyncTask(Activity activity, EarMode mode) { super(activity); this.mode = mode; } /** * This tasks returns the ear mode or ({@code null}) if ear mode could not be changed. */ @Override protected EarMode doInBackground(Object... params) { try {
return Karotz.getInstance().earsMode(mode);
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/fragment/KarotzSettingsFragment.java
// Path: src/com/github/hobbe/android/openkarotz/activity/SettingsActivity.java // public class SettingsActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // // Display the fragment as the main content. // getFragmentManager().beginTransaction().replace(android.R.id.content, new KarotzSettingsFragment()).commit(); // // } // // // /** Key for Karotz hostname preference. */ // public static final String KEY_PREF_KAROTZ_HOST = "prefKarotzHost"; // // }
import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import com.github.hobbe.android.openkarotz.R; import com.github.hobbe.android.openkarotz.activity.SettingsActivity; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.fragment; /** * Karotz settings fragment. */ public class KarotzSettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.karotz_settings); SharedPreferences preferences = getPreferenceScreen().getSharedPreferences();
// Path: src/com/github/hobbe/android/openkarotz/activity/SettingsActivity.java // public class SettingsActivity extends Activity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // // Display the fragment as the main content. // getFragmentManager().beginTransaction().replace(android.R.id.content, new KarotzSettingsFragment()).commit(); // // } // // // /** Key for Karotz hostname preference. */ // public static final String KEY_PREF_KAROTZ_HOST = "prefKarotzHost"; // // } // Path: src/com/github/hobbe/android/openkarotz/fragment/KarotzSettingsFragment.java import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import com.github.hobbe.android.openkarotz.R; import com.github.hobbe.android.openkarotz.activity.SettingsActivity; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.fragment; /** * Karotz settings fragment. */ public class KarotzSettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.karotz_settings); SharedPreferences preferences = getPreferenceScreen().getSharedPreferences();
String value = preferences.getString(SettingsActivity.KEY_PREF_KAROTZ_HOST, "");
hobbe/OpenKarotz-Android
test/com/github/hobbe/android/openkarotz/karotz/EarPositionTest.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarPosition { // // /** Position 1. */ // POSITION_1((byte) 1), // // /** Position 2. */ // POSITION_2((byte) 2), // // /** Position 3. */ // POSITION_3((byte) 3), // // /** Position 4. */ // POSITION_4((byte) 4), // // /** Position 5. */ // POSITION_5((byte) 5), // // /** Position 6. */ // POSITION_6((byte) 6), // // /** Position 7. */ // POSITION_7((byte) 7), // // /** Position 8. */ // POSITION_8((byte) 8), // // /** Position 9. */ // POSITION_9((byte) 9), // // /** Position 10. */ // POSITION_10((byte) 10), // // /** Position 11. */ // POSITION_11((byte) 11), // // /** Position 12. */ // POSITION_12((byte) 12), // // /** Position 13. */ // POSITION_13((byte) 13), // // /** Position 14. */ // POSITION_14((byte) 14), // // /** Position 15. */ // POSITION_15((byte) 15), // // /** Position 16. */ // POSITION_16((byte) 16); // // private EarPosition(byte position) { // this.position = position; // } // // /** // * Get the position value. // * @return the position value // */ // public byte getPosition() { // return position; // } // // /** // * Get the angle corresponding to the ear position. // * @return the angle, 0 to 360° // */ // public int toAngle() { // return Math.round(position * 360.0f / 16.0f); // } // // @Override // public String toString() { // return String.valueOf(position); // } // // /** // * Get the ear position corresponding to the given angle. // * @param angle an angle, 0 to 360°; values above will be modded with 360 // * @return the ear position corresponding to the angle // */ // public static EarPosition fromAngle(int angle) { // int angle360 = angle % 360; // int position = Math.round((angle360 / 360.0f) * 16.0f) + 1; // return fromIntValue(position); // } // // /** // * Get the ear position corresponding to the given position value. // * @param position the ear position as int (1 to 16) // * @return the ear position corresponding to the given position value // */ // public static EarPosition fromIntValue(int position) { // switch (position) { // case 1: // return EarPosition.POSITION_1; // case 2: // return EarPosition.POSITION_2; // case 3: // return EarPosition.POSITION_3; // case 4: // return EarPosition.POSITION_4; // case 5: // return EarPosition.POSITION_5; // case 6: // return EarPosition.POSITION_6; // case 7: // return EarPosition.POSITION_7; // case 8: // return EarPosition.POSITION_8; // case 9: // return EarPosition.POSITION_9; // case 10: // return EarPosition.POSITION_10; // case 11: // return EarPosition.POSITION_11; // case 12: // return EarPosition.POSITION_12; // case 13: // return EarPosition.POSITION_13; // case 14: // return EarPosition.POSITION_14; // case 15: // return EarPosition.POSITION_15; // case 16: // return EarPosition.POSITION_16; // default: // return EarPosition.POSITION_1; // } // } // // // /** Possible positions: 1 to 16. */ // private final byte position; // }
import junit.framework.TestCase; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarPosition;
package com.github.hobbe.android.openkarotz.karotz; public class EarPositionTest extends TestCase { public void testFromAngle() {
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarPosition { // // /** Position 1. */ // POSITION_1((byte) 1), // // /** Position 2. */ // POSITION_2((byte) 2), // // /** Position 3. */ // POSITION_3((byte) 3), // // /** Position 4. */ // POSITION_4((byte) 4), // // /** Position 5. */ // POSITION_5((byte) 5), // // /** Position 6. */ // POSITION_6((byte) 6), // // /** Position 7. */ // POSITION_7((byte) 7), // // /** Position 8. */ // POSITION_8((byte) 8), // // /** Position 9. */ // POSITION_9((byte) 9), // // /** Position 10. */ // POSITION_10((byte) 10), // // /** Position 11. */ // POSITION_11((byte) 11), // // /** Position 12. */ // POSITION_12((byte) 12), // // /** Position 13. */ // POSITION_13((byte) 13), // // /** Position 14. */ // POSITION_14((byte) 14), // // /** Position 15. */ // POSITION_15((byte) 15), // // /** Position 16. */ // POSITION_16((byte) 16); // // private EarPosition(byte position) { // this.position = position; // } // // /** // * Get the position value. // * @return the position value // */ // public byte getPosition() { // return position; // } // // /** // * Get the angle corresponding to the ear position. // * @return the angle, 0 to 360° // */ // public int toAngle() { // return Math.round(position * 360.0f / 16.0f); // } // // @Override // public String toString() { // return String.valueOf(position); // } // // /** // * Get the ear position corresponding to the given angle. // * @param angle an angle, 0 to 360°; values above will be modded with 360 // * @return the ear position corresponding to the angle // */ // public static EarPosition fromAngle(int angle) { // int angle360 = angle % 360; // int position = Math.round((angle360 / 360.0f) * 16.0f) + 1; // return fromIntValue(position); // } // // /** // * Get the ear position corresponding to the given position value. // * @param position the ear position as int (1 to 16) // * @return the ear position corresponding to the given position value // */ // public static EarPosition fromIntValue(int position) { // switch (position) { // case 1: // return EarPosition.POSITION_1; // case 2: // return EarPosition.POSITION_2; // case 3: // return EarPosition.POSITION_3; // case 4: // return EarPosition.POSITION_4; // case 5: // return EarPosition.POSITION_5; // case 6: // return EarPosition.POSITION_6; // case 7: // return EarPosition.POSITION_7; // case 8: // return EarPosition.POSITION_8; // case 9: // return EarPosition.POSITION_9; // case 10: // return EarPosition.POSITION_10; // case 11: // return EarPosition.POSITION_11; // case 12: // return EarPosition.POSITION_12; // case 13: // return EarPosition.POSITION_13; // case 14: // return EarPosition.POSITION_14; // case 15: // return EarPosition.POSITION_15; // case 16: // return EarPosition.POSITION_16; // default: // return EarPosition.POSITION_1; // } // } // // // /** Possible positions: 1 to 16. */ // private final byte position; // } // Path: test/com/github/hobbe/android/openkarotz/karotz/EarPositionTest.java import junit.framework.TestCase; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarPosition; package com.github.hobbe.android.openkarotz.karotz; public class EarPositionTest extends TestCase { public void testFromAngle() {
assertEquals(EarPosition.POSITION_1, EarPosition.fromAngle(0));
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/GetPulseAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz LED pulse status in the background. */ public class GetPulseAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetPulseAsyncTask(Activity activity) { super(activity); } /** * This tasks returns {@code Boolean#TRUE true} if action was successful, else {@code Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/GetPulseAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz LED pulse status in the background. */ public class GetPulseAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetPulseAsyncTask(Activity activity) { super(activity); } /** * This tasks returns {@code Boolean#TRUE true} if action was successful, else {@code Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
return Boolean.valueOf(Karotz.getInstance().isPulsing());
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/WakeupAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to wake Karotz up in the background. */ public class WakeupAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public WakeupAsyncTask(Activity activity) { super(activity); } /** * This tasks returns {@code Boolean#TRUE true} if action was successful, else {@code Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/WakeupAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to wake Karotz up in the background. */ public class WakeupAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public WakeupAsyncTask(Activity activity) { super(activity); } /** * This tasks returns {@code Boolean#TRUE true} if action was successful, else {@code Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
return Boolean.valueOf(Karotz.getInstance().wakeup(true));
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/activity/SettingsActivity.java
// Path: src/com/github/hobbe/android/openkarotz/fragment/KarotzSettingsFragment.java // public class KarotzSettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // // Load the preferences from an XML resource // addPreferencesFromResource(R.xml.karotz_settings); // // SharedPreferences preferences = getPreferenceScreen().getSharedPreferences(); // // String value = preferences.getString(SettingsActivity.KEY_PREF_KAROTZ_HOST, ""); // updatePreferenceSummary(SettingsActivity.KEY_PREF_KAROTZ_HOST, value, R.string.karotz_host_pref_summary); // // } // // @Override // public void onPause() { // super.onPause(); // getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // } // // @Override // public void onResume() { // super.onResume(); // getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // } // // @Override // public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { // if (key.equals(SettingsActivity.KEY_PREF_KAROTZ_HOST)) { // String value = preferences.getString(key, ""); // updatePreferenceSummary(key, value, R.string.karotz_host_pref_summary); // } // } // // private void updatePreferenceSummary(String key, String value, int descResId) { // Preference pref = findPreference(key); // pref.setSummary(getString(descResId) + ' ' + value); // } // }
import com.github.hobbe.android.openkarotz.fragment.KarotzSettingsFragment; import android.app.Activity; import android.os.Bundle;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.activity; /** * Settings activity. */ public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Display the fragment as the main content.
// Path: src/com/github/hobbe/android/openkarotz/fragment/KarotzSettingsFragment.java // public class KarotzSettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // // Load the preferences from an XML resource // addPreferencesFromResource(R.xml.karotz_settings); // // SharedPreferences preferences = getPreferenceScreen().getSharedPreferences(); // // String value = preferences.getString(SettingsActivity.KEY_PREF_KAROTZ_HOST, ""); // updatePreferenceSummary(SettingsActivity.KEY_PREF_KAROTZ_HOST, value, R.string.karotz_host_pref_summary); // // } // // @Override // public void onPause() { // super.onPause(); // getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // } // // @Override // public void onResume() { // super.onResume(); // getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // } // // @Override // public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { // if (key.equals(SettingsActivity.KEY_PREF_KAROTZ_HOST)) { // String value = preferences.getString(key, ""); // updatePreferenceSummary(key, value, R.string.karotz_host_pref_summary); // } // } // // private void updatePreferenceSummary(String key, String value, int descResId) { // Preference pref = findPreference(key); // pref.setSummary(getString(descResId) + ' ' + value); // } // } // Path: src/com/github/hobbe/android/openkarotz/activity/SettingsActivity.java import com.github.hobbe.android.openkarotz.fragment.KarotzSettingsFragment; import android.app.Activity; import android.os.Bundle; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.activity; /** * Settings activity. */ public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content, new KarotzSettingsFragment()).commit();
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/GetStatusAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum KarotzStatus { // // /** Unknown status. */ // UNKNOWN, // // /** Off line status, cannot be reached. */ // OFFLINE, // // /** Sleeping status, Karotz is not active, but some actions can still be done. */ // SLEEPING, // // /** Awake status, Karotz is active. */ // AWAKE; // // /** // * Check if this status corresponds to an awake status. // * @return {@code true} if this is an awake status // */ // public boolean isAwake() { // return (this == AWAKE); // } // // /** // * Check if this status corresponds to an offline status. // * @return {@code true} if this is an offline status // */ // public boolean isOffline() { // return (this == UNKNOWN || this == OFFLINE); // } // // /** // * Check if this status corresponds to an online status. // * @return {@code true} if this is an online status // */ // public boolean isOnline() { // return (this == SLEEPING || this == AWAKE); // } // // /** // * Check if this status corresponds to a sleeping status. // * @return {@code true} if this is a sleeping status // */ // public boolean isSleeping() { // return (this == SLEEPING); // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.KarotzStatus; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz status in the background. */ public class GetStatusAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetStatusAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link KarotzStatus Karotz status}. */ @Override
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum KarotzStatus { // // /** Unknown status. */ // UNKNOWN, // // /** Off line status, cannot be reached. */ // OFFLINE, // // /** Sleeping status, Karotz is not active, but some actions can still be done. */ // SLEEPING, // // /** Awake status, Karotz is active. */ // AWAKE; // // /** // * Check if this status corresponds to an awake status. // * @return {@code true} if this is an awake status // */ // public boolean isAwake() { // return (this == AWAKE); // } // // /** // * Check if this status corresponds to an offline status. // * @return {@code true} if this is an offline status // */ // public boolean isOffline() { // return (this == UNKNOWN || this == OFFLINE); // } // // /** // * Check if this status corresponds to an online status. // * @return {@code true} if this is an online status // */ // public boolean isOnline() { // return (this == SLEEPING || this == AWAKE); // } // // /** // * Check if this status corresponds to a sleeping status. // * @return {@code true} if this is a sleeping status // */ // public boolean isSleeping() { // return (this == SLEEPING); // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/GetStatusAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.KarotzStatus; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz status in the background. */ public class GetStatusAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetStatusAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link KarotzStatus Karotz status}. */ @Override
protected KarotzStatus doInBackground(Object... params) {
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/GetStatusAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum KarotzStatus { // // /** Unknown status. */ // UNKNOWN, // // /** Off line status, cannot be reached. */ // OFFLINE, // // /** Sleeping status, Karotz is not active, but some actions can still be done. */ // SLEEPING, // // /** Awake status, Karotz is active. */ // AWAKE; // // /** // * Check if this status corresponds to an awake status. // * @return {@code true} if this is an awake status // */ // public boolean isAwake() { // return (this == AWAKE); // } // // /** // * Check if this status corresponds to an offline status. // * @return {@code true} if this is an offline status // */ // public boolean isOffline() { // return (this == UNKNOWN || this == OFFLINE); // } // // /** // * Check if this status corresponds to an online status. // * @return {@code true} if this is an online status // */ // public boolean isOnline() { // return (this == SLEEPING || this == AWAKE); // } // // /** // * Check if this status corresponds to a sleeping status. // * @return {@code true} if this is a sleeping status // */ // public boolean isSleeping() { // return (this == SLEEPING); // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.KarotzStatus; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz status in the background. */ public class GetStatusAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetStatusAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link KarotzStatus Karotz status}. */ @Override protected KarotzStatus doInBackground(Object... params) { if (!isCancelled()) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum KarotzStatus { // // /** Unknown status. */ // UNKNOWN, // // /** Off line status, cannot be reached. */ // OFFLINE, // // /** Sleeping status, Karotz is not active, but some actions can still be done. */ // SLEEPING, // // /** Awake status, Karotz is active. */ // AWAKE; // // /** // * Check if this status corresponds to an awake status. // * @return {@code true} if this is an awake status // */ // public boolean isAwake() { // return (this == AWAKE); // } // // /** // * Check if this status corresponds to an offline status. // * @return {@code true} if this is an offline status // */ // public boolean isOffline() { // return (this == UNKNOWN || this == OFFLINE); // } // // /** // * Check if this status corresponds to an online status. // * @return {@code true} if this is an online status // */ // public boolean isOnline() { // return (this == SLEEPING || this == AWAKE); // } // // /** // * Check if this status corresponds to a sleeping status. // * @return {@code true} if this is a sleeping status // */ // public boolean isSleeping() { // return (this == SLEEPING); // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/GetStatusAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.KarotzStatus; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz status in the background. */ public class GetStatusAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetStatusAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link KarotzStatus Karotz status}. */ @Override protected KarotzStatus doInBackground(Object... params) { if (!isCancelled()) { try {
return Karotz.getInstance().getStatus();
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/EarsResetAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to reset Karotz ears in the background. */ public class EarsResetAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public EarsResetAsyncTask(Activity activity) { super(activity); } /** * This tasks does not return anything ({@code null}). */ @Override protected Void doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/EarsResetAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to reset Karotz ears in the background. */ public class EarsResetAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public EarsResetAsyncTask(Activity activity) { super(activity); } /** * This tasks does not return anything ({@code null}). */ @Override protected Void doInBackground(Object... params) { try {
Karotz.getInstance().earsReset();
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/SoundControlAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum SoundControlCommand { // // /** Stop sound. */ // STOP("quit"), // // /** Pause sound. */ // PAUSE("pause"); // // private SoundControlCommand(String cmd) { // this.cmd = cmd; // } // // @Override // public String toString() { // return cmd; // } // // // private final String cmd; // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.SoundControlCommand; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to make Karotz pause or stop a playing sound in the background. */ public class SoundControlAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param cmd the sound URL to play */ public SoundControlAsyncTask(Activity activity, SoundControlCommand cmd) { super(activity); this.cmd = cmd; } /** * This tasks returns {@link Boolean#TRUE true} if the call was successful, else {@link Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum SoundControlCommand { // // /** Stop sound. */ // STOP("quit"), // // /** Pause sound. */ // PAUSE("pause"); // // private SoundControlCommand(String cmd) { // this.cmd = cmd; // } // // @Override // public String toString() { // return cmd; // } // // // private final String cmd; // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/SoundControlAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.SoundControlCommand; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to make Karotz pause or stop a playing sound in the background. */ public class SoundControlAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param cmd the sound URL to play */ public SoundControlAsyncTask(Activity activity, SoundControlCommand cmd) { super(activity); this.cmd = cmd; } /** * This tasks returns {@link Boolean#TRUE true} if the call was successful, else {@link Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
return Boolean.valueOf(Karotz.getInstance().soundControl(cmd));
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/GetColorAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz LED color in the background. */ public class GetColorAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetColorAsyncTask(Activity activity) { super(activity); } /** * This tasks returns the color code as an {@code Integer} or {@code null} if the Karotz cannot be contacted. */ @Override protected Integer doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/GetColorAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz LED color in the background. */ public class GetColorAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetColorAsyncTask(Activity activity) { super(activity); } /** * This tasks returns the color code as an {@code Integer} or {@code null} if the Karotz cannot be contacted. */ @Override protected Integer doInBackground(Object... params) { try {
return Integer.valueOf(Karotz.getInstance().getColor());
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/LedAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to change Karotz LED color and pulse in the background. */ public class LedAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param color the color to change to * @param pulse if {@code true}, LED will pulse */ public LedAsyncTask(Activity activity, int color, boolean pulse) { super(activity); this.color = color; this.pulse = pulse; } /** * This tasks returns the color code as an {@code Integer} or {@code null} if the Karotz cannot be contacted. */ @Override protected Integer doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/LedAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to change Karotz LED color and pulse in the background. */ public class LedAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param color the color to change to * @param pulse if {@code true}, LED will pulse */ public LedAsyncTask(Activity activity, int color, boolean pulse) { super(activity); this.color = color; this.pulse = pulse; } /** * This tasks returns the color code as an {@code Integer} or {@code null} if the Karotz cannot be contacted. */ @Override protected Integer doInBackground(Object... params) { try {
Karotz.getInstance().led(color, pulse);
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/GetEarModeAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarMode { // // /** Ears enabled. */ // ENABLED, // // /** Ears disabled. */ // DISABLED; // // /** // * Check if this ear mode disables ear movement. // * @return {@code true} if ear movement is disabled // */ // public boolean isDisabled() { // return this == DISABLED; // } // // /** // * Check if this ear mode enables ear movement. // * @return {@code true} if ear movement is enabled // */ // public boolean isEnabled() { // return this == ENABLED; // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarMode; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz ear mode in the background. */ public class GetEarModeAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetEarModeAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link EarMode ear mode}. */ @Override
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarMode { // // /** Ears enabled. */ // ENABLED, // // /** Ears disabled. */ // DISABLED; // // /** // * Check if this ear mode disables ear movement. // * @return {@code true} if ear movement is disabled // */ // public boolean isDisabled() { // return this == DISABLED; // } // // /** // * Check if this ear mode enables ear movement. // * @return {@code true} if ear movement is enabled // */ // public boolean isEnabled() { // return this == ENABLED; // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/GetEarModeAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarMode; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz ear mode in the background. */ public class GetEarModeAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetEarModeAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link EarMode ear mode}. */ @Override
protected EarMode doInBackground(Object... params) {
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/GetEarModeAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarMode { // // /** Ears enabled. */ // ENABLED, // // /** Ears disabled. */ // DISABLED; // // /** // * Check if this ear mode disables ear movement. // * @return {@code true} if ear movement is disabled // */ // public boolean isDisabled() { // return this == DISABLED; // } // // /** // * Check if this ear mode enables ear movement. // * @return {@code true} if ear movement is enabled // */ // public boolean isEnabled() { // return this == ENABLED; // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarMode; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz ear mode in the background. */ public class GetEarModeAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetEarModeAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link EarMode ear mode}. */ @Override protected EarMode doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/IKarotz.java // public enum EarMode { // // /** Ears enabled. */ // ENABLED, // // /** Ears disabled. */ // DISABLED; // // /** // * Check if this ear mode disables ear movement. // * @return {@code true} if ear movement is disabled // */ // public boolean isDisabled() { // return this == DISABLED; // } // // /** // * Check if this ear mode enables ear movement. // * @return {@code true} if ear movement is enabled // */ // public boolean isEnabled() { // return this == ENABLED; // } // } // // Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/GetEarModeAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.IKarotz.EarMode; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz ear mode in the background. */ public class GetEarModeAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetEarModeAsyncTask(Activity activity) { super(activity); } /** * This tasks returns a {@link EarMode ear mode}. */ @Override protected EarMode doInBackground(Object... params) { try {
return Karotz.getInstance().getEarMode();
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/GetVersionAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz version in the background. */ public class GetVersionAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetVersionAsyncTask(Activity activity) { super(activity); } /** * This tasks returns the Karotz version as a {@link String} or {@code null} if the Karotz cannot be contacted. */ @Override protected String doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/GetVersionAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to get Karotz version in the background. */ public class GetVersionAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public GetVersionAsyncTask(Activity activity) { super(activity); } /** * This tasks returns the Karotz version as a {@link String} or {@code null} if the Karotz cannot be contacted. */ @Override protected String doInBackground(Object... params) { try {
return Karotz.getInstance().getVersion();
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/SoundAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to make Karotz play a sound URL in the background. */ public class SoundAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param sound the sound URL to play */ public SoundAsyncTask(Activity activity, String sound) { super(activity); this.sound = sound; } /** * This tasks returns {@link Boolean#TRUE true} if the call was successful, else {@link Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/SoundAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to make Karotz play a sound URL in the background. */ public class SoundAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity * @param sound the sound URL to play */ public SoundAsyncTask(Activity activity, String sound) { super(activity); this.sound = sound; } /** * This tasks returns {@link Boolean#TRUE true} if the call was successful, else {@link Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
return Boolean.valueOf(Karotz.getInstance().sound(sound));
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/task/SleepAsyncTask.java
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // }
import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to put Karotz to sleep in the background. */ public abstract class SleepAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public SleepAsyncTask(Activity activity) { super(activity); } /** * This tasks returns {@code Boolean#TRUE true} if action was successful, else {@code Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
// Path: src/com/github/hobbe/android/openkarotz/karotz/Karotz.java // public class Karotz { // // private Karotz() { // // No instance // } // // /** // * Get the Karotz instance. // * // * @return the Karotz instance. // */ // public static IKarotz getInstance() { // if (k == null) { // throw new IllegalAccessError(); // } // return k; // } // // /** // * Initialize the Karotz application singleton. // * // * @param hostname the Karotz hostname. // */ // public static void initialize(String hostname) { // k = new OpenKarotz(hostname); // } // // // private static IKarotz k = null; // } // Path: src/com/github/hobbe/android/openkarotz/task/SleepAsyncTask.java import android.app.Activity; import android.util.Log; import com.github.hobbe.android.openkarotz.karotz.Karotz; import java.io.IOException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.task; /** * Task to put Karotz to sleep in the background. */ public abstract class SleepAsyncTask extends KarotzAsyncTask { /** * Initialize a new task. * * @param activity the calling activity */ public SleepAsyncTask(Activity activity) { super(activity); } /** * This tasks returns {@code Boolean#TRUE true} if action was successful, else {@code Boolean#FALSE false}. */ @Override protected Boolean doInBackground(Object... params) { try {
return Boolean.valueOf(Karotz.getInstance().sleep());
hobbe/OpenKarotz-Android
src/com/github/hobbe/android/openkarotz/karotz/OpenKarotz.java
// Path: src/com/github/hobbe/android/openkarotz/net/NetUtils.java // public class NetUtils { // // /** // * Given a URL, establishes an HttpUrlConnection and retrieves the web page content as a InputStream, which it // * returns as a string. // * // * @param myurl the URL to download // * @return the url content as string // * @throws IOException if an I/O error occurs // */ // public static String downloadUrl(String myurl) throws IOException { // return downloadUrl(new URL(myurl)); // } // // /** // * Given a URL, establishes an HttpUrlConnection and retrieves the web page content as a InputStream, which it // * returns as a string. // * // * @param url the URL to download // * @return the url content as string // * @throws IOException if an I/O error occurs // */ // public static String downloadUrl(URL url) throws IOException { // // InputStream is = null; // // try { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setReadTimeout(10000); // conn.setConnectTimeout(6000); // conn.setRequestMethod("GET"); // conn.setDoInput(true); // // // Starts the query // conn.connect(); // int response = conn.getResponseCode(); // Log.d(LOG_TAG, "Response code: " + response); // // is = conn.getInputStream(); // int len = conn.getContentLength(); // if (len < 0) { // len = 512; // } // // // Convert the InputStream into a string // String contentAsString = readIt(is, len); // Log.d(LOG_TAG, "Response string: " + contentAsString); // // return contentAsString; // // } finally { // // Makes sure that the InputStream is closed after the app is // // finished using it. // if (is != null) { // is.close(); // } // } // } // // /** // * Checks for availability of network connection. // * // * @param activity the calling activity // * @return {@code true} if network connection is available, {@code false} otherwise // */ // public static final boolean isNetworkConnectionAvailable(Activity activity) { // // ConnectivityManager connMgr = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); // // if (networkInfo != null && networkInfo.isConnected()) { // return true; // } // // return false; // } // // // Reads an InputStream and converts it to a String. // private static String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { // Reader reader = null; // reader = new InputStreamReader(stream, "UTF-8"); // char[] buffer = new char[len]; // int count = reader.read(buffer); // return new String(buffer, 0, count); // } // // // private static final String LOG_TAG = NetUtils.class.getSimpleName(); // }
import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Color; import android.util.Log; import com.github.hobbe.android.openkarotz.net.NetUtils; import java.io.IOException; import java.net.MalformedURLException;
/* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.karotz; /** * OpenKarotz implementation. */ public class OpenKarotz implements IKarotz { /** * Initialize a new OpenKarotz instance. * @param hostname the hostname or IP */ public OpenKarotz(String hostname) { this.hostname = hostname; try { this.api = new URL(PROTOCOL + "://" + hostname + ":" + PORT); } catch (MalformedURLException e) { e.printStackTrace(); } } @Override public EarPosition[] ears(EarPosition left, EarPosition right) throws IOException { // Default position EarPosition[] newPositions = new EarPosition[] { EarPosition.POSITION_1, EarPosition.POSITION_1 }; // Current position, if available if (state != null) { newPositions = new EarPosition[] { state.getLeftEarPosition(), state.getRightEarPosition() }; } URL url = new URL(api, CGI_BIN + "/ears?noreset=1&left=" + left.toString() + "&right=" + right.toString()); Log.d(LOG_TAG, url.toString());
// Path: src/com/github/hobbe/android/openkarotz/net/NetUtils.java // public class NetUtils { // // /** // * Given a URL, establishes an HttpUrlConnection and retrieves the web page content as a InputStream, which it // * returns as a string. // * // * @param myurl the URL to download // * @return the url content as string // * @throws IOException if an I/O error occurs // */ // public static String downloadUrl(String myurl) throws IOException { // return downloadUrl(new URL(myurl)); // } // // /** // * Given a URL, establishes an HttpUrlConnection and retrieves the web page content as a InputStream, which it // * returns as a string. // * // * @param url the URL to download // * @return the url content as string // * @throws IOException if an I/O error occurs // */ // public static String downloadUrl(URL url) throws IOException { // // InputStream is = null; // // try { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setReadTimeout(10000); // conn.setConnectTimeout(6000); // conn.setRequestMethod("GET"); // conn.setDoInput(true); // // // Starts the query // conn.connect(); // int response = conn.getResponseCode(); // Log.d(LOG_TAG, "Response code: " + response); // // is = conn.getInputStream(); // int len = conn.getContentLength(); // if (len < 0) { // len = 512; // } // // // Convert the InputStream into a string // String contentAsString = readIt(is, len); // Log.d(LOG_TAG, "Response string: " + contentAsString); // // return contentAsString; // // } finally { // // Makes sure that the InputStream is closed after the app is // // finished using it. // if (is != null) { // is.close(); // } // } // } // // /** // * Checks for availability of network connection. // * // * @param activity the calling activity // * @return {@code true} if network connection is available, {@code false} otherwise // */ // public static final boolean isNetworkConnectionAvailable(Activity activity) { // // ConnectivityManager connMgr = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); // // if (networkInfo != null && networkInfo.isConnected()) { // return true; // } // // return false; // } // // // Reads an InputStream and converts it to a String. // private static String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { // Reader reader = null; // reader = new InputStreamReader(stream, "UTF-8"); // char[] buffer = new char[len]; // int count = reader.read(buffer); // return new String(buffer, 0, count); // } // // // private static final String LOG_TAG = NetUtils.class.getSimpleName(); // } // Path: src/com/github/hobbe/android/openkarotz/karotz/OpenKarotz.java import java.net.URL; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Color; import android.util.Log; import com.github.hobbe.android.openkarotz.net.NetUtils; import java.io.IOException; import java.net.MalformedURLException; /* * OpenKarotz-Android * http://github.com/hobbe/OpenKarotz-Android * * Copyright (c) 2014 Olivier Bagot (http://github.com/hobbe) * * 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. * * http://opensource.org/licenses/MIT * */ package com.github.hobbe.android.openkarotz.karotz; /** * OpenKarotz implementation. */ public class OpenKarotz implements IKarotz { /** * Initialize a new OpenKarotz instance. * @param hostname the hostname or IP */ public OpenKarotz(String hostname) { this.hostname = hostname; try { this.api = new URL(PROTOCOL + "://" + hostname + ":" + PORT); } catch (MalformedURLException e) { e.printStackTrace(); } } @Override public EarPosition[] ears(EarPosition left, EarPosition right) throws IOException { // Default position EarPosition[] newPositions = new EarPosition[] { EarPosition.POSITION_1, EarPosition.POSITION_1 }; // Current position, if available if (state != null) { newPositions = new EarPosition[] { state.getLeftEarPosition(), state.getRightEarPosition() }; } URL url = new URL(api, CGI_BIN + "/ears?noreset=1&left=" + left.toString() + "&right=" + right.toString()); Log.d(LOG_TAG, url.toString());
String result = NetUtils.downloadUrl(url);
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/LineFactory.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.List;
package com.simon816.chatui.ui; public class LineFactory { private final List<Text> lines = Lists.newArrayList();
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/LineFactory.java import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.List; package com.simon816.chatui.ui; public class LineFactory { private final List<Text> lines = Lists.newArrayList();
public void appendNewLine(Text text, PlayerContext ctx) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/lib/event/CreatePlayerViewEvent.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // }
import static com.google.common.base.Preconditions.checkNotNull; import com.simon816.chatui.lib.PlayerChatView; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.cause.Cause;
package com.simon816.chatui.lib.event; public class CreatePlayerViewEvent implements Event { private final Cause cause; private final Player player;
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/event/CreatePlayerViewEvent.java import static com.google.common.base.Preconditions.checkNotNull; import com.simon816.chatui.lib.PlayerChatView; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.cause.Cause; package com.simon816.chatui.lib.event; public class CreatePlayerViewEvent implements Event { private final Cause cause; private final Player player;
private PlayerChatView view;
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/AnchorPaneUI.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import java.util.List;
package com.simon816.chatui.ui; public class AnchorPaneUI extends UIPane { public static final int ANCHOR_TOP = 1; public static final int ANCHOR_RIGHT = 2; public static final int ANCHOR_BOTTOM = 4; public static final int ANCHOR_LEFT = 8; private final Object2IntMap<UIComponent> constraints = new Object2IntOpenHashMap<>(); public AnchorPaneUI() { } public AnchorPaneUI(UIComponent... children) { addChildren(children); } @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/AnchorPaneUI.java import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import java.util.List; package com.simon816.chatui.ui; public class AnchorPaneUI extends UIPane { public static final int ANCHOR_TOP = 1; public static final int ANCHOR_RIGHT = 2; public static final int ANCHOR_BOTTOM = 4; public static final int ANCHOR_LEFT = 8; private final Object2IntMap<UIComponent> constraints = new Object2IntOpenHashMap<>(); public AnchorPaneUI() { } public AnchorPaneUI(UIComponent... children) { addChildren(children); } @Override
public void draw(PlayerContext ctx, LineFactory lineFactory) {
simon816/ChatUI
src/main/java/com/simon816/chatui/impl/ImplementationPagination.java
// Path: src/main/java/org/spongepowered/common/service/pagination/SpongePaginationAccessor.java // public class SpongePaginationAccessor { // // public static void replaceActivePagination(SpongePaginationService service, CommandSource oldSource, CommandSource newSource) { // SourcePaginations state = service.getPaginationState(oldSource, false); // ActivePagination active = state.get(state.getLastUuid()); // state.keys().remove(state.getLastUuid()); // service.getPaginationState(newSource, true).put(active); // } // // }
import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.common.service.pagination.SpongePaginationAccessor; import org.spongepowered.common.service.pagination.SpongePaginationService;
package com.simon816.chatui.impl; public class ImplementationPagination { public static void modify(PaginationService service, CommandSource oldSource, CommandSource newSource) { if (Sponge.getPlatform().asMap().get("CommonName").equals("Sponge")) { if (service instanceof SpongePaginationService) {
// Path: src/main/java/org/spongepowered/common/service/pagination/SpongePaginationAccessor.java // public class SpongePaginationAccessor { // // public static void replaceActivePagination(SpongePaginationService service, CommandSource oldSource, CommandSource newSource) { // SourcePaginations state = service.getPaginationState(oldSource, false); // ActivePagination active = state.get(state.getLastUuid()); // state.keys().remove(state.getLastUuid()); // service.getPaginationState(newSource, true).put(active); // } // // } // Path: src/main/java/com/simon816/chatui/impl/ImplementationPagination.java import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.common.service.pagination.SpongePaginationAccessor; import org.spongepowered.common.service.pagination.SpongePaginationService; package com.simon816.chatui.impl; public class ImplementationPagination { public static void modify(PaginationService service, CommandSource oldSource, CommandSource newSource) { if (Sponge.getPlatform().asMap().get("CommonName").equals("Sponge")) { if (service instanceof SpongePaginationService) {
SpongePaginationAccessor.replaceActivePagination((SpongePaginationService) service, oldSource, newSource);
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/UIComponent.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/ITextDrawable.java // public interface ITextDrawable { // // Text draw(PlayerContext ctx); // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.simon816.chatui.lib.ITextDrawable; import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text;
package com.simon816.chatui.ui; public interface UIComponent extends ITextDrawable { @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/ITextDrawable.java // public interface ITextDrawable { // // Text draw(PlayerContext ctx); // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/UIComponent.java import com.simon816.chatui.lib.ITextDrawable; import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; package com.simon816.chatui.ui; public interface UIComponent extends ITextDrawable { @Override
default Text draw(PlayerContext ctx) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/internal/ClickCallback.java // public class ClickCallback { // // private static final Cache<UUID, Consumer<PlayerChatView>> callbackCache = CacheBuilder.newBuilder() // .expireAfterAccess(5, TimeUnit.MINUTES) // .build(); // // public static CommandSpec createCommand() { // return CommandSpec.builder() // .arguments(GenericArguments.string(Text.of("uuid"))) // .executor((src, args) -> { // UUID uuid = UUID.fromString(args.<String>getOne("uuid").get()); // Consumer<PlayerChatView> consumer = callbackCache.getIfPresent(uuid); // if (consumer == null) { // throw new CommandException(Text.of("Callback expired")); // } // consumer.accept(ChatUILib.getView(src)); // return CommandResult.success(); // }).build(); // } // // public static String generateCommand(Consumer<PlayerChatView> handler) { // UUID uuid = UUID.randomUUID(); // callbackCache.put(uuid, handler); // return "/chatui exec " + uuid; // } // // }
import com.google.common.base.Utf8; import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.lib.internal.ClickCallback; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.source.ProxySource; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.serializer.TextSerializers; import java.util.List; import java.util.function.Consumer;
package com.simon816.chatui.util; public class Utils { public static CommandSource getRealSource(CommandSource source) { while (source instanceof ProxySource) { source = ((ProxySource) source).getOriginalSource(); } return source; }
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/internal/ClickCallback.java // public class ClickCallback { // // private static final Cache<UUID, Consumer<PlayerChatView>> callbackCache = CacheBuilder.newBuilder() // .expireAfterAccess(5, TimeUnit.MINUTES) // .build(); // // public static CommandSpec createCommand() { // return CommandSpec.builder() // .arguments(GenericArguments.string(Text.of("uuid"))) // .executor((src, args) -> { // UUID uuid = UUID.fromString(args.<String>getOne("uuid").get()); // Consumer<PlayerChatView> consumer = callbackCache.getIfPresent(uuid); // if (consumer == null) { // throw new CommandException(Text.of("Callback expired")); // } // consumer.accept(ChatUILib.getView(src)); // return CommandResult.success(); // }).build(); // } // // public static String generateCommand(Consumer<PlayerChatView> handler) { // UUID uuid = UUID.randomUUID(); // callbackCache.put(uuid, handler); // return "/chatui exec " + uuid; // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java import com.google.common.base.Utf8; import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.lib.internal.ClickCallback; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.source.ProxySource; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.serializer.TextSerializers; import java.util.List; import java.util.function.Consumer; package com.simon816.chatui.util; public class Utils { public static CommandSource getRealSource(CommandSource source) { while (source instanceof ProxySource) { source = ((ProxySource) source).getOriginalSource(); } return source; }
public static ClickAction<?> execClick(Consumer<PlayerChatView> handler) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/internal/ClickCallback.java // public class ClickCallback { // // private static final Cache<UUID, Consumer<PlayerChatView>> callbackCache = CacheBuilder.newBuilder() // .expireAfterAccess(5, TimeUnit.MINUTES) // .build(); // // public static CommandSpec createCommand() { // return CommandSpec.builder() // .arguments(GenericArguments.string(Text.of("uuid"))) // .executor((src, args) -> { // UUID uuid = UUID.fromString(args.<String>getOne("uuid").get()); // Consumer<PlayerChatView> consumer = callbackCache.getIfPresent(uuid); // if (consumer == null) { // throw new CommandException(Text.of("Callback expired")); // } // consumer.accept(ChatUILib.getView(src)); // return CommandResult.success(); // }).build(); // } // // public static String generateCommand(Consumer<PlayerChatView> handler) { // UUID uuid = UUID.randomUUID(); // callbackCache.put(uuid, handler); // return "/chatui exec " + uuid; // } // // }
import com.google.common.base.Utf8; import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.lib.internal.ClickCallback; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.source.ProxySource; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.serializer.TextSerializers; import java.util.List; import java.util.function.Consumer;
package com.simon816.chatui.util; public class Utils { public static CommandSource getRealSource(CommandSource source) { while (source instanceof ProxySource) { source = ((ProxySource) source).getOriginalSource(); } return source; } public static ClickAction<?> execClick(Consumer<PlayerChatView> handler) {
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/internal/ClickCallback.java // public class ClickCallback { // // private static final Cache<UUID, Consumer<PlayerChatView>> callbackCache = CacheBuilder.newBuilder() // .expireAfterAccess(5, TimeUnit.MINUTES) // .build(); // // public static CommandSpec createCommand() { // return CommandSpec.builder() // .arguments(GenericArguments.string(Text.of("uuid"))) // .executor((src, args) -> { // UUID uuid = UUID.fromString(args.<String>getOne("uuid").get()); // Consumer<PlayerChatView> consumer = callbackCache.getIfPresent(uuid); // if (consumer == null) { // throw new CommandException(Text.of("Callback expired")); // } // consumer.accept(ChatUILib.getView(src)); // return CommandResult.success(); // }).build(); // } // // public static String generateCommand(Consumer<PlayerChatView> handler) { // UUID uuid = UUID.randomUUID(); // callbackCache.put(uuid, handler); // return "/chatui exec " + uuid; // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java import com.google.common.base.Utf8; import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.lib.internal.ClickCallback; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.source.ProxySource; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.serializer.TextSerializers; import java.util.List; import java.util.function.Consumer; package com.simon816.chatui.util; public class Utils { public static CommandSource getRealSource(CommandSource source) { while (source instanceof ProxySource) { source = ((ProxySource) source).getOriginalSource(); } return source; } public static ClickAction<?> execClick(Consumer<PlayerChatView> handler) {
return TextActions.runCommand(ClickCallback.generateCommand(handler));
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/internal/ClickCallback.java // public class ClickCallback { // // private static final Cache<UUID, Consumer<PlayerChatView>> callbackCache = CacheBuilder.newBuilder() // .expireAfterAccess(5, TimeUnit.MINUTES) // .build(); // // public static CommandSpec createCommand() { // return CommandSpec.builder() // .arguments(GenericArguments.string(Text.of("uuid"))) // .executor((src, args) -> { // UUID uuid = UUID.fromString(args.<String>getOne("uuid").get()); // Consumer<PlayerChatView> consumer = callbackCache.getIfPresent(uuid); // if (consumer == null) { // throw new CommandException(Text.of("Callback expired")); // } // consumer.accept(ChatUILib.getView(src)); // return CommandResult.success(); // }).build(); // } // // public static String generateCommand(Consumer<PlayerChatView> handler) { // UUID uuid = UUID.randomUUID(); // callbackCache.put(uuid, handler); // return "/chatui exec " + uuid; // } // // }
import com.google.common.base.Utf8; import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.lib.internal.ClickCallback; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.source.ProxySource; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.serializer.TextSerializers; import java.util.List; import java.util.function.Consumer;
package com.simon816.chatui.util; public class Utils { public static CommandSource getRealSource(CommandSource source) { while (source instanceof ProxySource) { source = ((ProxySource) source).getOriginalSource(); } return source; } public static ClickAction<?> execClick(Consumer<PlayerChatView> handler) { return TextActions.runCommand(ClickCallback.generateCommand(handler)); } public static ClickAction<?> execClick(Runnable action) { return execClick(view -> { action.run(); view.update(); }); }
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/internal/ClickCallback.java // public class ClickCallback { // // private static final Cache<UUID, Consumer<PlayerChatView>> callbackCache = CacheBuilder.newBuilder() // .expireAfterAccess(5, TimeUnit.MINUTES) // .build(); // // public static CommandSpec createCommand() { // return CommandSpec.builder() // .arguments(GenericArguments.string(Text.of("uuid"))) // .executor((src, args) -> { // UUID uuid = UUID.fromString(args.<String>getOne("uuid").get()); // Consumer<PlayerChatView> consumer = callbackCache.getIfPresent(uuid); // if (consumer == null) { // throw new CommandException(Text.of("Callback expired")); // } // consumer.accept(ChatUILib.getView(src)); // return CommandResult.success(); // }).build(); // } // // public static String generateCommand(Consumer<PlayerChatView> handler) { // UUID uuid = UUID.randomUUID(); // callbackCache.put(uuid, handler); // return "/chatui exec " + uuid; // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java import com.google.common.base.Utf8; import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.lib.internal.ClickCallback; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.source.ProxySource; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.serializer.TextSerializers; import java.util.List; import java.util.function.Consumer; package com.simon816.chatui.util; public class Utils { public static CommandSource getRealSource(CommandSource source) { while (source instanceof ProxySource) { source = ((ProxySource) source).getOriginalSource(); } return source; } public static ClickAction<?> execClick(Consumer<PlayerChatView> handler) { return TextActions.runCommand(ClickCallback.generateCommand(handler)); } public static ClickAction<?> execClick(Runnable action) { return execClick(view -> { action.run(); view.update(); }); }
public static void sendMessageSplitLarge(PlayerContext ctx, Text text) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/table/DefaultColumnRenderer.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.List;
package com.simon816.chatui.ui.table; public class DefaultColumnRenderer implements TableColumnRenderer { @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/table/DefaultColumnRenderer.java import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.List; package com.simon816.chatui.ui.table; public class DefaultColumnRenderer implements TableColumnRenderer { @Override
public List<Text> renderCell(Object value, int row, int tableWidth, PlayerContext ctx) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/HBoxUI.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.simon816.chatui.lib.PlayerContext; import java.util.List;
package com.simon816.chatui.ui; public class HBoxUI extends UIPane { @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/HBoxUI.java import com.simon816.chatui.lib.PlayerContext; import java.util.List; package com.simon816.chatui.ui; public class HBoxUI extends UIPane { @Override
public void draw(PlayerContext ctx, LineFactory lineFactory) {
simon816/ChatUI
src/main/java/com/simon816/chatui/ChatUIView.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/TopWindow.java // public interface TopWindow extends ITextDrawable { // // void onClose(); // // void onTextInput(PlayerChatView view, Text input); // // boolean onCommand(PlayerChatView view, String[] args); // // }
import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.TopWindow; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.chat.ChatType; import java.util.Optional;
package com.simon816.chatui; // A wrapper class to enclose both ActivePlayerChatView and DisabledChatView class ChatUIView implements PlayerChatView { private PlayerChatView actualView; public ChatUIView(PlayerChatView actualView) { this.actualView = actualView; } public PlayerChatView getActualView() { return this.actualView; } @Override public Player getPlayer() { return this.actualView.getPlayer(); } @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/TopWindow.java // public interface TopWindow extends ITextDrawable { // // void onClose(); // // void onTextInput(PlayerChatView view, Text input); // // boolean onCommand(PlayerChatView view, String[] args); // // } // Path: src/main/java/com/simon816/chatui/ChatUIView.java import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.TopWindow; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.chat.ChatType; import java.util.Optional; package com.simon816.chatui; // A wrapper class to enclose both ActivePlayerChatView and DisabledChatView class ChatUIView implements PlayerChatView { private PlayerChatView actualView; public ChatUIView(PlayerChatView actualView) { this.actualView = actualView; } public PlayerChatView getActualView() { return this.actualView; } @Override public Player getPlayer() { return this.actualView.getPlayer(); } @Override
public TopWindow getWindow() {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/table/TableScrollHelper.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/ui/table/TableRenderer.java // interface TableViewport { // // int getFirstRowIndex(); // // int getFirstColumnIndex(); // // }
import com.simon816.chatui.ui.table.TableRenderer.TableViewport;
return false; } this.scrollOffset++; return true; } public boolean canScrollDown() { return this.scrollOffset < this.model.getRowCount() - 1; } public int getScrollOffset() { return this.scrollOffset; } public boolean scrollToOffset(int offset) { if (offset < 0 || offset >= this.model.getRowCount()) { return false; } this.scrollOffset = offset; return true; } public void reset() { this.scrollOffset = 0; } public TableModel getModel() { return this.model; }
// Path: ChatUILib/src/main/java/com/simon816/chatui/ui/table/TableRenderer.java // interface TableViewport { // // int getFirstRowIndex(); // // int getFirstColumnIndex(); // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/table/TableScrollHelper.java import com.simon816.chatui.ui.table.TableRenderer.TableViewport; return false; } this.scrollOffset++; return true; } public boolean canScrollDown() { return this.scrollOffset < this.model.getRowCount() - 1; } public int getScrollOffset() { return this.scrollOffset; } public boolean scrollToOffset(int offset) { if (offset < 0 || offset >= this.model.getRowCount()) { return false; } this.scrollOffset = offset; return true; } public void reset() { this.scrollOffset = 0; } public TableModel getModel() { return this.model; }
public TableViewport createViewport() {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/util/TextBuffer.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.ArrayList;
package com.simon816.chatui.util; public class TextBuffer { private final ArrayList<Text> buffer = Lists.newArrayList(); private int width;
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/util/TextBuffer.java import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.ArrayList; package com.simon816.chatui.util; public class TextBuffer { private final ArrayList<Text> buffer = Lists.newArrayList(); private int width;
private final PlayerContext ctx;
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/lib/event/PlayerChangeConfigEvent.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/config/PlayerSettings.java // @ConfigSerializable // public class PlayerSettings { // // public static final int DEFAULT_BUFFER_WIDTH = 320; // public static final int DEFAULT_BUFFER_HEIGHT = 180; // public static final int LINE_HEIGHT = 9; // public static final int DEFAULT_BUFFER_HEIGHT_LINES = DEFAULT_BUFFER_HEIGHT / LINE_HEIGHT; // // @Setting("display-width") // private int width = DEFAULT_BUFFER_WIDTH; // // @Setting("display-height") // private int height = DEFAULT_BUFFER_HEIGHT; // // @Setting("force-unicode") // private boolean forceUnicode = false; // // @Setting("font-data") // private String fontData = null; // // public PlayerSettings() { // } // // public PlayerSettings(int width, int height, boolean forceUnicode, String fontData) { // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.fontData = fontData; // } // // public int getWidth() { // return this.width; // } // // public PlayerSettings withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // return new PlayerSettings(width, this.height, this.forceUnicode, this.fontData); // } // // public int getHeightLines() { // return this.height / LINE_HEIGHT; // } // // public int getHeight() { // return this.height; // } // // public PlayerSettings withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // return new PlayerSettings(this.width, height, this.forceUnicode, this.fontData); // } // // public boolean getForceUnicode() { // return this.forceUnicode; // } // // public PlayerSettings withUnicode(boolean forceUnicode) { // return new PlayerSettings(this.width, this.height, forceUnicode, this.fontData); // } // // public String getFontData() { // return this.fontData; // } // // public PlayerSettings withFontData(String fontData) { // FontData.checkValid(fontData); // if (fontData != null && fontData.isEmpty()) { // fontData = null; // } // return new PlayerSettings(this.width, this.height, this.forceUnicode, fontData); // } // // public PlayerContext createContext(Player player) { // return new PlayerContext(player, getWidth(), getHeightLines(), getForceUnicode(), // FontData.fromString(getFontData(), LibConfig.defaultFontData())); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PlayerSettings settings = (PlayerSettings) obj; // return settings.width == this.width && settings.height == this.height && settings.forceUnicode == this.forceUnicode // && ((this.fontData == null && settings.fontData == null) || (this.fontData != null && this.fontData.equals(settings.fontData))); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .add("fontData", this.fontData) // .toString(); // } // }
import com.simon816.chatui.lib.config.PlayerSettings; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.cause.Cause;
package com.simon816.chatui.lib.event; public class PlayerChangeConfigEvent implements Event { private final Cause cause; private final Player player;
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/config/PlayerSettings.java // @ConfigSerializable // public class PlayerSettings { // // public static final int DEFAULT_BUFFER_WIDTH = 320; // public static final int DEFAULT_BUFFER_HEIGHT = 180; // public static final int LINE_HEIGHT = 9; // public static final int DEFAULT_BUFFER_HEIGHT_LINES = DEFAULT_BUFFER_HEIGHT / LINE_HEIGHT; // // @Setting("display-width") // private int width = DEFAULT_BUFFER_WIDTH; // // @Setting("display-height") // private int height = DEFAULT_BUFFER_HEIGHT; // // @Setting("force-unicode") // private boolean forceUnicode = false; // // @Setting("font-data") // private String fontData = null; // // public PlayerSettings() { // } // // public PlayerSettings(int width, int height, boolean forceUnicode, String fontData) { // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.fontData = fontData; // } // // public int getWidth() { // return this.width; // } // // public PlayerSettings withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // return new PlayerSettings(width, this.height, this.forceUnicode, this.fontData); // } // // public int getHeightLines() { // return this.height / LINE_HEIGHT; // } // // public int getHeight() { // return this.height; // } // // public PlayerSettings withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // return new PlayerSettings(this.width, height, this.forceUnicode, this.fontData); // } // // public boolean getForceUnicode() { // return this.forceUnicode; // } // // public PlayerSettings withUnicode(boolean forceUnicode) { // return new PlayerSettings(this.width, this.height, forceUnicode, this.fontData); // } // // public String getFontData() { // return this.fontData; // } // // public PlayerSettings withFontData(String fontData) { // FontData.checkValid(fontData); // if (fontData != null && fontData.isEmpty()) { // fontData = null; // } // return new PlayerSettings(this.width, this.height, this.forceUnicode, fontData); // } // // public PlayerContext createContext(Player player) { // return new PlayerContext(player, getWidth(), getHeightLines(), getForceUnicode(), // FontData.fromString(getFontData(), LibConfig.defaultFontData())); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PlayerSettings settings = (PlayerSettings) obj; // return settings.width == this.width && settings.height == this.height && settings.forceUnicode == this.forceUnicode // && ((this.fontData == null && settings.fontData == null) || (this.fontData != null && this.fontData.equals(settings.fontData))); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .add("fontData", this.fontData) // .toString(); // } // } // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/event/PlayerChangeConfigEvent.java import com.simon816.chatui.lib.config.PlayerSettings; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.cause.Cause; package com.simon816.chatui.lib.event; public class PlayerChangeConfigEvent implements Event { private final Cause cause; private final Player player;
private final PlayerSettings oldSettings;
simon816/ChatUI
src/main/java/com/simon816/chatui/pagination/TabbedPaginationBuilder.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/config/PlayerSettings.java // @ConfigSerializable // public class PlayerSettings { // // public static final int DEFAULT_BUFFER_WIDTH = 320; // public static final int DEFAULT_BUFFER_HEIGHT = 180; // public static final int LINE_HEIGHT = 9; // public static final int DEFAULT_BUFFER_HEIGHT_LINES = DEFAULT_BUFFER_HEIGHT / LINE_HEIGHT; // // @Setting("display-width") // private int width = DEFAULT_BUFFER_WIDTH; // // @Setting("display-height") // private int height = DEFAULT_BUFFER_HEIGHT; // // @Setting("force-unicode") // private boolean forceUnicode = false; // // @Setting("font-data") // private String fontData = null; // // public PlayerSettings() { // } // // public PlayerSettings(int width, int height, boolean forceUnicode, String fontData) { // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.fontData = fontData; // } // // public int getWidth() { // return this.width; // } // // public PlayerSettings withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // return new PlayerSettings(width, this.height, this.forceUnicode, this.fontData); // } // // public int getHeightLines() { // return this.height / LINE_HEIGHT; // } // // public int getHeight() { // return this.height; // } // // public PlayerSettings withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // return new PlayerSettings(this.width, height, this.forceUnicode, this.fontData); // } // // public boolean getForceUnicode() { // return this.forceUnicode; // } // // public PlayerSettings withUnicode(boolean forceUnicode) { // return new PlayerSettings(this.width, this.height, forceUnicode, this.fontData); // } // // public String getFontData() { // return this.fontData; // } // // public PlayerSettings withFontData(String fontData) { // FontData.checkValid(fontData); // if (fontData != null && fontData.isEmpty()) { // fontData = null; // } // return new PlayerSettings(this.width, this.height, this.forceUnicode, fontData); // } // // public PlayerContext createContext(Player player) { // return new PlayerContext(player, getWidth(), getHeightLines(), getForceUnicode(), // FontData.fromString(getFontData(), LibConfig.defaultFontData())); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PlayerSettings settings = (PlayerSettings) obj; // return settings.width == this.width && settings.height == this.height && settings.forceUnicode == this.forceUnicode // && ((this.fontData == null && settings.fontData == null) || (this.fontData != null && this.fontData.equals(settings.fontData))); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .add("fontData", this.fontData) // .toString(); // } // }
import com.simon816.chatui.lib.config.PlayerSettings; import org.spongepowered.api.service.pagination.PaginationList; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.api.text.Text;
package com.simon816.chatui.pagination; public class TabbedPaginationBuilder implements PaginationList.Builder { private final PaginationList.Builder builder; private final PaginationService service; private final int removedHeight; public TabbedPaginationBuilder(PaginationService service) { this.builder = service.builder(); this.service = service; // This cannot be obtained without a Window object this.removedHeight = 2;
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/config/PlayerSettings.java // @ConfigSerializable // public class PlayerSettings { // // public static final int DEFAULT_BUFFER_WIDTH = 320; // public static final int DEFAULT_BUFFER_HEIGHT = 180; // public static final int LINE_HEIGHT = 9; // public static final int DEFAULT_BUFFER_HEIGHT_LINES = DEFAULT_BUFFER_HEIGHT / LINE_HEIGHT; // // @Setting("display-width") // private int width = DEFAULT_BUFFER_WIDTH; // // @Setting("display-height") // private int height = DEFAULT_BUFFER_HEIGHT; // // @Setting("force-unicode") // private boolean forceUnicode = false; // // @Setting("font-data") // private String fontData = null; // // public PlayerSettings() { // } // // public PlayerSettings(int width, int height, boolean forceUnicode, String fontData) { // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.fontData = fontData; // } // // public int getWidth() { // return this.width; // } // // public PlayerSettings withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // return new PlayerSettings(width, this.height, this.forceUnicode, this.fontData); // } // // public int getHeightLines() { // return this.height / LINE_HEIGHT; // } // // public int getHeight() { // return this.height; // } // // public PlayerSettings withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // return new PlayerSettings(this.width, height, this.forceUnicode, this.fontData); // } // // public boolean getForceUnicode() { // return this.forceUnicode; // } // // public PlayerSettings withUnicode(boolean forceUnicode) { // return new PlayerSettings(this.width, this.height, forceUnicode, this.fontData); // } // // public String getFontData() { // return this.fontData; // } // // public PlayerSettings withFontData(String fontData) { // FontData.checkValid(fontData); // if (fontData != null && fontData.isEmpty()) { // fontData = null; // } // return new PlayerSettings(this.width, this.height, this.forceUnicode, fontData); // } // // public PlayerContext createContext(Player player) { // return new PlayerContext(player, getWidth(), getHeightLines(), getForceUnicode(), // FontData.fromString(getFontData(), LibConfig.defaultFontData())); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PlayerSettings settings = (PlayerSettings) obj; // return settings.width == this.width && settings.height == this.height && settings.forceUnicode == this.forceUnicode // && ((this.fontData == null && settings.fontData == null) || (this.fontData != null && this.fontData.equals(settings.fontData))); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .add("fontData", this.fontData) // .toString(); // } // } // Path: src/main/java/com/simon816/chatui/pagination/TabbedPaginationBuilder.java import com.simon816.chatui.lib.config.PlayerSettings; import org.spongepowered.api.service.pagination.PaginationList; import org.spongepowered.api.service.pagination.PaginationService; import org.spongepowered.api.text.Text; package com.simon816.chatui.pagination; public class TabbedPaginationBuilder implements PaginationList.Builder { private final PaginationList.Builder builder; private final PaginationService service; private final int removedHeight; public TabbedPaginationBuilder(PaginationService service) { this.builder = service.builder(); this.service = service; // This cannot be obtained without a Window object this.removedHeight = 2;
this.builder.linesPerPage(PlayerSettings.DEFAULT_BUFFER_HEIGHT_LINES - this.removedHeight);
simon816/ChatUI
src/main/java/com/simon816/chatui/tabs/config/ConfigEntry.java
// Path: src/main/java/com/simon816/chatui/util/ExtraUtils.java // public class ExtraUtils { // // public static ClickAction<?> clickAction(Runnable action, Tab tab) { // return clickAction(view -> { // action.run(); // return true; // }, tab); // } // // public static ClickAction<?> clickAction(Consumer<PlayerChatView> consumer, Tab tab) { // return clickAction(view -> { // consumer.accept(view); // return true; // }, tab); // } // // public static ClickAction<?> clickAction(BooleanSupplier action, Tab tab) { // return clickAction((Predicate<PlayerChatView>) view -> action.getAsBoolean(), tab); // } // // public static ClickAction<?> clickAction(Predicate<PlayerChatView> action, Tab tab) { // return Utils.execClick(clickHandler(action, tab)); // } // // public static Consumer<PlayerChatView> clickHandler(Predicate<PlayerChatView> action, Tab tab) { // return view -> { // PlayerChatView unwrapped = ChatUI.unwrapView(view); // if (!ChatUI.isTabActive(unwrapped, tab)) { // return; // } // if (action.test(unwrapped)) { // view.update(); // } // }; // } // // }
import static com.google.common.base.Preconditions.checkArgument; import com.simon816.chatui.util.ExtraUtils; import ninja.leaping.configurate.ConfigurationNode; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextFormat; import org.spongepowered.api.text.format.TextStyles;
private final Text text; public UnknownValueType(Object value) { this.text = Text.of("[Unknown] ", value); } @Override public Text toText(boolean focus) { return this.text; } } static class ComplexValue extends ConfigValue { private static final Text LINK = Text.of(TextFormat.of(TextColors.BLUE, TextStyles.UNDERLINE), "Click to open"); private static final Text LINK_BLUR = Text.of(TextFormat.of(TextColors.DARK_GRAY, TextStyles.UNDERLINE), "Click to open"); private final ConfigurationNode node; public ComplexValue(ConfigurationNode node) { this.node = node; } @Override public Text toText(boolean focus) { return focus ? LINK : LINK_BLUR; } @Override protected ClickAction<?> createClickAction(ConfigEntry entry, ConfigEditTab boundTab) {
// Path: src/main/java/com/simon816/chatui/util/ExtraUtils.java // public class ExtraUtils { // // public static ClickAction<?> clickAction(Runnable action, Tab tab) { // return clickAction(view -> { // action.run(); // return true; // }, tab); // } // // public static ClickAction<?> clickAction(Consumer<PlayerChatView> consumer, Tab tab) { // return clickAction(view -> { // consumer.accept(view); // return true; // }, tab); // } // // public static ClickAction<?> clickAction(BooleanSupplier action, Tab tab) { // return clickAction((Predicate<PlayerChatView>) view -> action.getAsBoolean(), tab); // } // // public static ClickAction<?> clickAction(Predicate<PlayerChatView> action, Tab tab) { // return Utils.execClick(clickHandler(action, tab)); // } // // public static Consumer<PlayerChatView> clickHandler(Predicate<PlayerChatView> action, Tab tab) { // return view -> { // PlayerChatView unwrapped = ChatUI.unwrapView(view); // if (!ChatUI.isTabActive(unwrapped, tab)) { // return; // } // if (action.test(unwrapped)) { // view.update(); // } // }; // } // // } // Path: src/main/java/com/simon816/chatui/tabs/config/ConfigEntry.java import static com.google.common.base.Preconditions.checkArgument; import com.simon816.chatui.util.ExtraUtils; import ninja.leaping.configurate.ConfigurationNode; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextFormat; import org.spongepowered.api.text.format.TextStyles; private final Text text; public UnknownValueType(Object value) { this.text = Text.of("[Unknown] ", value); } @Override public Text toText(boolean focus) { return this.text; } } static class ComplexValue extends ConfigValue { private static final Text LINK = Text.of(TextFormat.of(TextColors.BLUE, TextStyles.UNDERLINE), "Click to open"); private static final Text LINK_BLUR = Text.of(TextFormat.of(TextColors.DARK_GRAY, TextStyles.UNDERLINE), "Click to open"); private final ConfigurationNode node; public ComplexValue(ConfigurationNode node) { this.node = node; } @Override public Text toText(boolean focus) { return focus ? LINK : LINK_BLUR; } @Override protected ClickAction<?> createClickAction(ConfigEntry entry, ConfigEditTab boundTab) {
return ExtraUtils.clickAction(() -> {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/BlockRenderContext.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public enum Context { // BLOCKS, // BRAILLE // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public static abstract class RenderingContext { // // final List<Layer> layers = Lists.newArrayList(); // // public abstract Context getType(); // // protected abstract LineDrawingContext createDrawContext(PlayerContext ctx); // // public void addLayer(Layer layer) { // this.layers.add(layer); // } // // public void clear() { // this.layers.clear(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/LineDrawingContext.java // public static class PixelMetadata { // // public final TextColor color; // public final ClickAction<?> clickHandler; // public final boolean locked; // // public PixelMetadata(TextColor color) { // this(color, null, false); // } // // public PixelMetadata(TextColor color, Consumer<PlayerChatView> callback, boolean locked) { // this.color = color; // this.clickHandler = callback == null ? null : Utils.execClick(callback); // this.locked = locked; // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PixelMetadata other = (PixelMetadata) obj; // // Don't care about locked here // return other.color == this.color && other.clickHandler == this.clickHandler; // } // // public Text toText(String string) { // Text.Builder b = Text.builder(string).color(this.color); // if (this.clickHandler != null) { // b.onClick(this.clickHandler); // } // return b.build(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/ShapeFunction.java // public static interface DrawHandler { // // default void setup(LineDrawingContext ctx, Object... args) { // } // // default void finish(LineDrawingContext ctx) { // } // // void write(LineDrawingContext ctx, int x, int y, Object... args); // }
import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.ui.canvas.CanvasUI.Context; import com.simon816.chatui.ui.canvas.CanvasUI.RenderingContext; import com.simon816.chatui.ui.canvas.LineDrawingContext.PixelMetadata; import com.simon816.chatui.ui.canvas.ShapeFunction.DrawHandler; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors;
package com.simon816.chatui.ui.canvas; public class BlockRenderContext extends RenderingContext { private static final PixelMetadata EMPTY_DATA = new PixelMetadata(TextColors.BLACK); @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public enum Context { // BLOCKS, // BRAILLE // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public static abstract class RenderingContext { // // final List<Layer> layers = Lists.newArrayList(); // // public abstract Context getType(); // // protected abstract LineDrawingContext createDrawContext(PlayerContext ctx); // // public void addLayer(Layer layer) { // this.layers.add(layer); // } // // public void clear() { // this.layers.clear(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/LineDrawingContext.java // public static class PixelMetadata { // // public final TextColor color; // public final ClickAction<?> clickHandler; // public final boolean locked; // // public PixelMetadata(TextColor color) { // this(color, null, false); // } // // public PixelMetadata(TextColor color, Consumer<PlayerChatView> callback, boolean locked) { // this.color = color; // this.clickHandler = callback == null ? null : Utils.execClick(callback); // this.locked = locked; // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PixelMetadata other = (PixelMetadata) obj; // // Don't care about locked here // return other.color == this.color && other.clickHandler == this.clickHandler; // } // // public Text toText(String string) { // Text.Builder b = Text.builder(string).color(this.color); // if (this.clickHandler != null) { // b.onClick(this.clickHandler); // } // return b.build(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/ShapeFunction.java // public static interface DrawHandler { // // default void setup(LineDrawingContext ctx, Object... args) { // } // // default void finish(LineDrawingContext ctx) { // } // // void write(LineDrawingContext ctx, int x, int y, Object... args); // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/BlockRenderContext.java import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.ui.canvas.CanvasUI.Context; import com.simon816.chatui.ui.canvas.CanvasUI.RenderingContext; import com.simon816.chatui.ui.canvas.LineDrawingContext.PixelMetadata; import com.simon816.chatui.ui.canvas.ShapeFunction.DrawHandler; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors; package com.simon816.chatui.ui.canvas; public class BlockRenderContext extends RenderingContext { private static final PixelMetadata EMPTY_DATA = new PixelMetadata(TextColors.BLACK); @Override
public Context getType() {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/BlockRenderContext.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public enum Context { // BLOCKS, // BRAILLE // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public static abstract class RenderingContext { // // final List<Layer> layers = Lists.newArrayList(); // // public abstract Context getType(); // // protected abstract LineDrawingContext createDrawContext(PlayerContext ctx); // // public void addLayer(Layer layer) { // this.layers.add(layer); // } // // public void clear() { // this.layers.clear(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/LineDrawingContext.java // public static class PixelMetadata { // // public final TextColor color; // public final ClickAction<?> clickHandler; // public final boolean locked; // // public PixelMetadata(TextColor color) { // this(color, null, false); // } // // public PixelMetadata(TextColor color, Consumer<PlayerChatView> callback, boolean locked) { // this.color = color; // this.clickHandler = callback == null ? null : Utils.execClick(callback); // this.locked = locked; // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PixelMetadata other = (PixelMetadata) obj; // // Don't care about locked here // return other.color == this.color && other.clickHandler == this.clickHandler; // } // // public Text toText(String string) { // Text.Builder b = Text.builder(string).color(this.color); // if (this.clickHandler != null) { // b.onClick(this.clickHandler); // } // return b.build(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/ShapeFunction.java // public static interface DrawHandler { // // default void setup(LineDrawingContext ctx, Object... args) { // } // // default void finish(LineDrawingContext ctx) { // } // // void write(LineDrawingContext ctx, int x, int y, Object... args); // }
import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.ui.canvas.CanvasUI.Context; import com.simon816.chatui.ui.canvas.CanvasUI.RenderingContext; import com.simon816.chatui.ui.canvas.LineDrawingContext.PixelMetadata; import com.simon816.chatui.ui.canvas.ShapeFunction.DrawHandler; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors;
package com.simon816.chatui.ui.canvas; public class BlockRenderContext extends RenderingContext { private static final PixelMetadata EMPTY_DATA = new PixelMetadata(TextColors.BLACK); @Override public Context getType() { return Context.BLOCKS; } @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public enum Context { // BLOCKS, // BRAILLE // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/CanvasUI.java // public static abstract class RenderingContext { // // final List<Layer> layers = Lists.newArrayList(); // // public abstract Context getType(); // // protected abstract LineDrawingContext createDrawContext(PlayerContext ctx); // // public void addLayer(Layer layer) { // this.layers.add(layer); // } // // public void clear() { // this.layers.clear(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/LineDrawingContext.java // public static class PixelMetadata { // // public final TextColor color; // public final ClickAction<?> clickHandler; // public final boolean locked; // // public PixelMetadata(TextColor color) { // this(color, null, false); // } // // public PixelMetadata(TextColor color, Consumer<PlayerChatView> callback, boolean locked) { // this.color = color; // this.clickHandler = callback == null ? null : Utils.execClick(callback); // this.locked = locked; // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (obj == null || obj.getClass() != this.getClass()) { // return false; // } // PixelMetadata other = (PixelMetadata) obj; // // Don't care about locked here // return other.color == this.color && other.clickHandler == this.clickHandler; // } // // public Text toText(String string) { // Text.Builder b = Text.builder(string).color(this.color); // if (this.clickHandler != null) { // b.onClick(this.clickHandler); // } // return b.build(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/ShapeFunction.java // public static interface DrawHandler { // // default void setup(LineDrawingContext ctx, Object... args) { // } // // default void finish(LineDrawingContext ctx) { // } // // void write(LineDrawingContext ctx, int x, int y, Object... args); // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/BlockRenderContext.java import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.ui.canvas.CanvasUI.Context; import com.simon816.chatui.ui.canvas.CanvasUI.RenderingContext; import com.simon816.chatui.ui.canvas.LineDrawingContext.PixelMetadata; import com.simon816.chatui.ui.canvas.ShapeFunction.DrawHandler; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors; package com.simon816.chatui.ui.canvas; public class BlockRenderContext extends RenderingContext { private static final PixelMetadata EMPTY_DATA = new PixelMetadata(TextColors.BLACK); @Override public Context getType() { return Context.BLOCKS; } @Override
protected LineDrawingContext createDrawContext(PlayerContext ctx) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/VBoxUI.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.simon816.chatui.lib.PlayerContext; import java.util.List;
package com.simon816.chatui.ui; public class VBoxUI extends UIPane { @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/VBoxUI.java import com.simon816.chatui.lib.PlayerContext; import java.util.List; package com.simon816.chatui.ui; public class VBoxUI extends UIPane { @Override
public void draw(PlayerContext ctx, LineFactory lineFactory) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/UIPane.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import java.util.List;
package com.simon816.chatui.ui; public abstract class UIPane implements UIComponent { private final List<UIComponent> children = Lists.newArrayList(); public List<UIComponent> getChildren() { return this.children; } public void addChildren(UIComponent... components) { for (UIComponent component : components) { this.children.add(component); } } @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/UIPane.java import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import java.util.List; package com.simon816.chatui.ui; public abstract class UIPane implements UIComponent { private final List<UIComponent> children = Lists.newArrayList(); public List<UIComponent> getChildren() { return this.children; } public void addChildren(UIComponent... components) { for (UIComponent component : components) { this.children.add(component); } } @Override
public int getMinWidth(PlayerContext ctx) {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/table/TableRenderer.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.List;
package com.simon816.chatui.ui.table; public interface TableRenderer { interface TableViewport { int getFirstRowIndex(); int getFirstColumnIndex(); } TableViewport getViewport();
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/table/TableRenderer.java import com.simon816.chatui.lib.PlayerContext; import org.spongepowered.api.text.Text; import java.util.List; package com.simon816.chatui.ui.table; public interface TableRenderer { interface TableViewport { int getFirstRowIndex(); int getFirstColumnIndex(); } TableViewport getViewport();
Text applySideBorders(int rowIndex, List<Text> line, int[] colMaxWidths, PlayerContext ctx);
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/LineDrawingContext.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java // public class Utils { // // public static CommandSource getRealSource(CommandSource source) { // while (source instanceof ProxySource) { // source = ((ProxySource) source).getOriginalSource(); // } // return source; // } // // public static ClickAction<?> execClick(Consumer<PlayerChatView> handler) { // return TextActions.runCommand(ClickCallback.generateCommand(handler)); // } // // public static ClickAction<?> execClick(Runnable action) { // return execClick(view -> { // action.run(); // view.update(); // }); // } // // public static void sendMessageSplitLarge(PlayerContext ctx, Text text) { // String json = TextSerializers.JSON.serialize(text); // int size = Utf8.encodedLength(json); // if (size > 32767) { // List<Text> lines = ctx.utils().splitLines(text, ctx.width); // ctx.getPlayer().sendMessages(lines); // } else { // ctx.getPlayer().sendMessage(text); // } // } // // }
import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.util.Utils; import it.unimi.dsi.fastutil.ints.Int2CharMap; import it.unimi.dsi.fastutil.ints.Int2CharOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors; import java.util.function.Consumer;
package com.simon816.chatui.ui.canvas; public class LineDrawingContext { private final Line[] lines; private final int width; private final char emptyChar; private final PixelMetadata emptyData; private final int emptyCharWidth; private PixelMetadata currentData;
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/util/Utils.java // public class Utils { // // public static CommandSource getRealSource(CommandSource source) { // while (source instanceof ProxySource) { // source = ((ProxySource) source).getOriginalSource(); // } // return source; // } // // public static ClickAction<?> execClick(Consumer<PlayerChatView> handler) { // return TextActions.runCommand(ClickCallback.generateCommand(handler)); // } // // public static ClickAction<?> execClick(Runnable action) { // return execClick(view -> { // action.run(); // view.update(); // }); // } // // public static void sendMessageSplitLarge(PlayerContext ctx, Text text) { // String json = TextSerializers.JSON.serialize(text); // int size = Utf8.encodedLength(json); // if (size > 32767) { // List<Text> lines = ctx.utils().splitLines(text, ctx.width); // ctx.getPlayer().sendMessages(lines); // } else { // ctx.getPlayer().sendMessage(text); // } // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/canvas/LineDrawingContext.java import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.PlayerContext; import com.simon816.chatui.util.Utils; import it.unimi.dsi.fastutil.ints.Int2CharMap; import it.unimi.dsi.fastutil.ints.Int2CharOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.ClickAction; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors; import java.util.function.Consumer; package com.simon816.chatui.ui.canvas; public class LineDrawingContext { private final Line[] lines; private final int width; private final char emptyChar; private final PixelMetadata emptyData; private final int emptyCharWidth; private PixelMetadata currentData;
public LineDrawingContext(PlayerContext ctx, char emptyChar, PixelMetadata emptyData) {
simon816/ChatUI
src/main/java/com/simon816/chatui/DisabledChatView.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/TopWindow.java // public interface TopWindow extends ITextDrawable { // // void onClose(); // // void onTextInput(PlayerChatView view, Text input); // // boolean onCommand(PlayerChatView view, String[] args); // // }
import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.TopWindow; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.chat.ChatType; import org.spongepowered.api.text.format.TextColors; import java.util.Optional; import java.util.UUID;
package com.simon816.chatui; public class DisabledChatView implements PlayerChatView { private static final Text DISABLED_MESSAGE; static { Text.Builder builder = Text.builder("ChatUI is disabled, type "); builder.append(Text.builder("/chatui enable") .color(TextColors.GREEN) .onClick(TextActions.suggestCommand("/chatui enable")) .build(), Text.of(" to re-enable")); DISABLED_MESSAGE = builder.build(); } private final UUID playerUuid; DisabledChatView(Player player) { this.playerUuid = player.getUniqueId(); } @Override public void initialize() { getPlayer().sendMessage(DISABLED_MESSAGE); } @Override public Player getPlayer() { return Sponge.getServer().getPlayer(this.playerUuid).get(); } @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerChatView.java // public interface PlayerChatView { // // public Player getPlayer(); // // public TopWindow getWindow(); // // public boolean showWindow(TopWindow window); // // public boolean removeShownWindow(); // // public void update(); // // public boolean handleIncoming(Text message); // // public Optional<Text> transformOutgoing(CommandSource sender, Text originalOutgoing, ChatType type); // // public boolean handleCommand(String[] args); // // public void onRemove(); // // public void initialize(); // // } // // Path: ChatUILib/src/main/java/com/simon816/chatui/lib/TopWindow.java // public interface TopWindow extends ITextDrawable { // // void onClose(); // // void onTextInput(PlayerChatView view, Text input); // // boolean onCommand(PlayerChatView view, String[] args); // // } // Path: src/main/java/com/simon816/chatui/DisabledChatView.java import com.simon816.chatui.lib.PlayerChatView; import com.simon816.chatui.lib.TopWindow; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.chat.ChatType; import org.spongepowered.api.text.format.TextColors; import java.util.Optional; import java.util.UUID; package com.simon816.chatui; public class DisabledChatView implements PlayerChatView { private static final Text DISABLED_MESSAGE; static { Text.Builder builder = Text.builder("ChatUI is disabled, type "); builder.append(Text.builder("/chatui enable") .color(TextColors.GREEN) .onClick(TextActions.suggestCommand("/chatui enable")) .build(), Text.of(" to re-enable")); DISABLED_MESSAGE = builder.build(); } private final UUID playerUuid; DisabledChatView(Player player) { this.playerUuid = player.getUniqueId(); } @Override public void initialize() { getPlayer().sendMessage(DISABLED_MESSAGE); } @Override public Player getPlayer() { return Sponge.getServer().getPlayer(this.playerUuid).get(); } @Override
public TopWindow getWindow() {
simon816/ChatUI
ChatUILib/src/main/java/com/simon816/chatui/ui/FlowPaneUI.java
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // }
import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import java.util.Iterator; import java.util.List;
package com.simon816.chatui.ui; public class FlowPaneUI extends UIPane { public static final int WRAP_HORIZONALLY = 1; public static final int WRAP_VERTICALLY = 2; private int mode = WRAP_HORIZONALLY; public FlowPaneUI() { } public FlowPaneUI(int mode) { setWrapMode(mode); } public void setWrapMode(int mode) { checkArgument(mode == WRAP_HORIZONALLY || mode == WRAP_VERTICALLY, "Invalid mode"); this.mode = mode; } @Override
// Path: ChatUILib/src/main/java/com/simon816/chatui/lib/PlayerContext.java // public class PlayerContext { // // public final int height; // public final int width; // public final boolean forceUnicode; // // private final UUID playerUUID; // private final TextUtils utils; // // public PlayerContext(Player player, int width, int height, boolean forceUnicode, FontData fontData) { // this(player.getUniqueId(), width, height, forceUnicode, new TextUtils(fontData, forceUnicode, player.getUniqueId())); // checkArgument(height >= 1, "Height must be at least one"); // checkArgument(width >= 1, "Width must be at least one"); // } // // private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) { // this.playerUUID = playerUuid; // this.width = width; // this.height = height; // this.forceUnicode = forceUnicode; // this.utils = utils; // } // // public Player getPlayer() { // return Sponge.getServer().getPlayer(this.playerUUID).get(); // } // // public TextUtils utils() { // return this.utils; // } // // public PlayerContext withHeight(int height) { // checkArgument(height >= 1, "Height must be at least one"); // if (height == this.height) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, height, this.forceUnicode, this.utils); // } // // public PlayerContext withWidth(int width) { // checkArgument(width >= 1, "Width must be at least one"); // if (width == this.width) { // return this; // } // return new PlayerContext(this.playerUUID, width, this.height, this.forceUnicode, this.utils); // } // // public PlayerContext withUnicode(boolean forceUnicode) { // if (forceUnicode == this.forceUnicode) { // return this; // } // return new PlayerContext(this.playerUUID, this.width, this.height, forceUnicode, // new TextUtils(this.utils.getFontData(), forceUnicode, this.playerUUID)); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("player", this.getPlayer()) // .add("width", this.width) // .add("height", this.height) // .add("forceUnicode", this.forceUnicode) // .toString(); // } // // } // Path: ChatUILib/src/main/java/com/simon816/chatui/ui/FlowPaneUI.java import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.Lists; import com.simon816.chatui.lib.PlayerContext; import java.util.Iterator; import java.util.List; package com.simon816.chatui.ui; public class FlowPaneUI extends UIPane { public static final int WRAP_HORIZONALLY = 1; public static final int WRAP_VERTICALLY = 2; private int mode = WRAP_HORIZONALLY; public FlowPaneUI() { } public FlowPaneUI(int mode) { setWrapMode(mode); } public void setWrapMode(int mode) { checkArgument(mode == WRAP_HORIZONALLY || mode == WRAP_VERTICALLY, "Invalid mode"); this.mode = mode; } @Override
public void draw(PlayerContext ctx, LineFactory lineFactory) {
paolodongilli/SASAbus
src/it/sasabz/android/sasabus/classes/adapter/MyListAdapter.java
// Path: src/it/sasabz/android/sasabus/SASAbus.java // public class SASAbus extends Application { // private int dbDownloadAttempts; // // private static Context context = null; // // @Override // public void onCreate() // { // // Init values which could be loaded from files stored in res/raw // setDbDownloadAttempts(0); // super.onCreate(); // context = this.getApplicationContext(); // } // // @Override // public void onTerminate() // { // //do nothing // MySQLiteDBAdapter.closeAll(); // } // // /** // * @return the Strings and Variables stored in the Context; // */ // public static Context getContext() // { // return context; // } // // /** // * @param dbDownloadAttempts the dbDownloadAttempts to set // */ // public void setDbDownloadAttempts(int dbDownloadAttempts) { // this.dbDownloadAttempts = dbDownloadAttempts; // } // // /** // * @return the dbDownloadAttempts // */ // public int getDbDownloadAttempts() { // return dbDownloadAttempts; // } // // // } // // Path: src/it/sasabz/android/sasabus/classes/dbobjects/DBObject.java // public class DBObject { // // /* // * The id is the integer which identifies the object in the database // */ // private int id = 0; // // /** // * This constructor creates an dbobject // */ // public DBObject() // { // super(); // //Nothing to do // } // // /** // * this creates a dbobject with an identifier, which is the id // * provided in the database // * @param identifier is the identifier from the database // */ // public DBObject(int identifier) // { // super(); // setId(identifier); // } // // /** // * // * @return the integer which identifies the object in the database // */ // public int getId() { // return id; // } // // /** // * // * @param id is the integer which identifies the object in the database // */ // public void setId(int id) { // this.id = id; // } // // // // }
import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import it.sasabz.android.sasabus.SASAbus; import it.sasabz.android.sasabus.classes.dbobjects.DBObject; import java.util.Vector; import android.R; import android.content.Context;
/** * * MyListAdapter.java * * * Copyright (C) 2012 Markus Windegger * * This file is part of SasaBus. * SasaBus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SasaBus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SasaBus. If not, see <http://www.gnu.org/licenses/>. * */ package it.sasabz.android.sasabus.classes.adapter; /** * @author Markus Windegger (markus@mowiso.com) * */ public class MyListAdapter extends BaseAdapter { private final Context context;
// Path: src/it/sasabz/android/sasabus/SASAbus.java // public class SASAbus extends Application { // private int dbDownloadAttempts; // // private static Context context = null; // // @Override // public void onCreate() // { // // Init values which could be loaded from files stored in res/raw // setDbDownloadAttempts(0); // super.onCreate(); // context = this.getApplicationContext(); // } // // @Override // public void onTerminate() // { // //do nothing // MySQLiteDBAdapter.closeAll(); // } // // /** // * @return the Strings and Variables stored in the Context; // */ // public static Context getContext() // { // return context; // } // // /** // * @param dbDownloadAttempts the dbDownloadAttempts to set // */ // public void setDbDownloadAttempts(int dbDownloadAttempts) { // this.dbDownloadAttempts = dbDownloadAttempts; // } // // /** // * @return the dbDownloadAttempts // */ // public int getDbDownloadAttempts() { // return dbDownloadAttempts; // } // // // } // // Path: src/it/sasabz/android/sasabus/classes/dbobjects/DBObject.java // public class DBObject { // // /* // * The id is the integer which identifies the object in the database // */ // private int id = 0; // // /** // * This constructor creates an dbobject // */ // public DBObject() // { // super(); // //Nothing to do // } // // /** // * this creates a dbobject with an identifier, which is the id // * provided in the database // * @param identifier is the identifier from the database // */ // public DBObject(int identifier) // { // super(); // setId(identifier); // } // // /** // * // * @return the integer which identifies the object in the database // */ // public int getId() { // return id; // } // // /** // * // * @param id is the integer which identifies the object in the database // */ // public void setId(int id) { // this.id = id; // } // // // // } // Path: src/it/sasabz/android/sasabus/classes/adapter/MyListAdapter.java import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import it.sasabz.android.sasabus.SASAbus; import it.sasabz.android.sasabus.classes.dbobjects.DBObject; import java.util.Vector; import android.R; import android.content.Context; /** * * MyListAdapter.java * * * Copyright (C) 2012 Markus Windegger * * This file is part of SasaBus. * SasaBus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SasaBus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SasaBus. If not, see <http://www.gnu.org/licenses/>. * */ package it.sasabz.android.sasabus.classes.adapter; /** * @author Markus Windegger (markus@mowiso.com) * */ public class MyListAdapter extends BaseAdapter { private final Context context;
private final Vector<DBObject> list;