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
coderJohnZhang/TvLauncher
src/com/gotech/tv/launcher/parser/BaseJsonParser.java
// Path: src/com/gotech/tv/launcher/util/Constant.java // public class Constant { // // public static final int VIEW_PAGER_DURATION = 500; // public static final int MENU_HOME = 0; // public static final int MENU_APP = 1; // public static final int MENU_SETTING = 2; // public static final int TRAN_DUR_ANIM = 500; // public static final float APP_PAGE_SIZE = 12.0f; // public static final int APP_PAGE_COLUMNS = 4; // public static final int MOVE = 1; // public static final int PAGE_ITEM_NUM = 6; // public static final int DIALOG_AUTO_DISMISS = 0; // public static final int TIME_OUT = 5000; // // /** // * 加(解)密钥匙 // */ // public static final String DesEncryptKey = "TvLauncher"; // // /** // * 存取用户IP和软件类型 // **/ // public static final String UserServerConfigTxt = "serverconfig.txt"; // // /** // * 存用户名和密码文件 // **/ // public static final String UserDataTxt = "userpwd.txt"; // // /** // * 软件类型 // */ // public static String SOFTWARE_TYPE = "TvLauncher"; // // /** // * 默认分组号 // * 默认:创维 999 // */ // public static String MAC_REGISTER_DEFAULT_CODE = "009"; // // /** // * JSON数据格式错误 // **/ // public static int ParseData_FormatWrong = 2; // // /** // * 解析成功 // **/ // public static int ParseData_Success = 0; // // /** // * 用户访问超时 或 未登录 // **/ // public static int ParseData_TimeOut = 1; // // }
import org.json.JSONException; import org.json.JSONObject; import com.gotech.tv.launcher.util.Constant;
package com.gotech.tv.launcher.parser; public abstract class BaseJsonParser<Result> { public abstract Result parse(JSONObject data) throws DataParseException; public static JSONObject convert(String data) throws DataParseException { if (data == null || data.length() <= 0) {
// Path: src/com/gotech/tv/launcher/util/Constant.java // public class Constant { // // public static final int VIEW_PAGER_DURATION = 500; // public static final int MENU_HOME = 0; // public static final int MENU_APP = 1; // public static final int MENU_SETTING = 2; // public static final int TRAN_DUR_ANIM = 500; // public static final float APP_PAGE_SIZE = 12.0f; // public static final int APP_PAGE_COLUMNS = 4; // public static final int MOVE = 1; // public static final int PAGE_ITEM_NUM = 6; // public static final int DIALOG_AUTO_DISMISS = 0; // public static final int TIME_OUT = 5000; // // /** // * 加(解)密钥匙 // */ // public static final String DesEncryptKey = "TvLauncher"; // // /** // * 存取用户IP和软件类型 // **/ // public static final String UserServerConfigTxt = "serverconfig.txt"; // // /** // * 存用户名和密码文件 // **/ // public static final String UserDataTxt = "userpwd.txt"; // // /** // * 软件类型 // */ // public static String SOFTWARE_TYPE = "TvLauncher"; // // /** // * 默认分组号 // * 默认:创维 999 // */ // public static String MAC_REGISTER_DEFAULT_CODE = "009"; // // /** // * JSON数据格式错误 // **/ // public static int ParseData_FormatWrong = 2; // // /** // * 解析成功 // **/ // public static int ParseData_Success = 0; // // /** // * 用户访问超时 或 未登录 // **/ // public static int ParseData_TimeOut = 1; // // } // Path: src/com/gotech/tv/launcher/parser/BaseJsonParser.java import org.json.JSONException; import org.json.JSONObject; import com.gotech.tv.launcher.util.Constant; package com.gotech.tv.launcher.parser; public abstract class BaseJsonParser<Result> { public abstract Result parse(JSONObject data) throws DataParseException; public static JSONObject convert(String data) throws DataParseException { if (data == null || data.length() <= 0) {
throw new DataParseException(Constant.ParseData_FormatWrong, "no data back");
anotherMe17/CommonAdapterSample
commonadapter/src/main/java/io/github/anotherme17/commonadapter/manager/ItemViewManager.java
// Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/ItemViewDelegate.java // public interface ItemViewDelegate<T> { // // public abstract // @LayoutRes // int getItemLayoutId(); // // public abstract int getItemViewId(); // // public abstract void onViewHolderCreated(Context context, View view, T data, int position); // // public abstract void convert(Context context, ViewHolder viewHolder, T data, int position); // }
import android.support.annotation.NonNull; import android.support.v4.util.SparseArrayCompat; import java.util.ArrayList; import java.util.List; import io.github.anotherme17.commonadapter.ItemViewDelegate;
package io.github.anotherme17.commonadapter.manager; /** * 项目名称:CommonAdapterSample * 类描述: * 创建人:renhao * 创建时间:2016/11/24 9:11 * 修改备注: */ public class ItemViewManager<T> { public boolean isSignal = true; public int signalId = 0;
// Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/ItemViewDelegate.java // public interface ItemViewDelegate<T> { // // public abstract // @LayoutRes // int getItemLayoutId(); // // public abstract int getItemViewId(); // // public abstract void onViewHolderCreated(Context context, View view, T data, int position); // // public abstract void convert(Context context, ViewHolder viewHolder, T data, int position); // } // Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/manager/ItemViewManager.java import android.support.annotation.NonNull; import android.support.v4.util.SparseArrayCompat; import java.util.ArrayList; import java.util.List; import io.github.anotherme17.commonadapter.ItemViewDelegate; package io.github.anotherme17.commonadapter.manager; /** * 项目名称:CommonAdapterSample * 类描述: * 创建人:renhao * 创建时间:2016/11/24 9:11 * 修改备注: */ public class ItemViewManager<T> { public boolean isSignal = true; public int signalId = 0;
protected SparseArrayCompat<ItemViewDelegate<T>> mDelegate = new SparseArrayCompat<>();
anotherMe17/CommonAdapterSample
app/src/main/java/io/github/anotherme17/commonadaptersample/engine/ApiEngine.java
// Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/BannerModel.java // public class BannerModel { // public List<String> imgs; // public List<String> tips; // } // // Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/NormalModel.java // public class NormalModel { // public String title; // public String detail; // public String avatorPath; // public boolean selected; // // public NormalModel() { // } // // public NormalModel(String title, String detail, String avatorPath) { // this.title = title; // this.detail = detail; // this.avatorPath = avatorPath; // } // }
import java.util.List; import io.github.anotherme17.commonadaptersample.model.BannerModel; import io.github.anotherme17.commonadaptersample.model.NormalModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Url;
package io.github.anotherme17.commonadaptersample.engine; /** * 作者:王浩 邮件:[email protected] * 创建时间:15/9/17 上午10:19 * 描述: */ public interface ApiEngine { @GET("normalModels.json")
// Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/BannerModel.java // public class BannerModel { // public List<String> imgs; // public List<String> tips; // } // // Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/NormalModel.java // public class NormalModel { // public String title; // public String detail; // public String avatorPath; // public boolean selected; // // public NormalModel() { // } // // public NormalModel(String title, String detail, String avatorPath) { // this.title = title; // this.detail = detail; // this.avatorPath = avatorPath; // } // } // Path: app/src/main/java/io/github/anotherme17/commonadaptersample/engine/ApiEngine.java import java.util.List; import io.github.anotherme17.commonadaptersample.model.BannerModel; import io.github.anotherme17.commonadaptersample.model.NormalModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Url; package io.github.anotherme17.commonadaptersample.engine; /** * 作者:王浩 邮件:[email protected] * 创建时间:15/9/17 上午10:19 * 描述: */ public interface ApiEngine { @GET("normalModels.json")
Call<List<NormalModel>> getNormalModels();
anotherMe17/CommonAdapterSample
app/src/main/java/io/github/anotherme17/commonadaptersample/engine/ApiEngine.java
// Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/BannerModel.java // public class BannerModel { // public List<String> imgs; // public List<String> tips; // } // // Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/NormalModel.java // public class NormalModel { // public String title; // public String detail; // public String avatorPath; // public boolean selected; // // public NormalModel() { // } // // public NormalModel(String title, String detail, String avatorPath) { // this.title = title; // this.detail = detail; // this.avatorPath = avatorPath; // } // }
import java.util.List; import io.github.anotherme17.commonadaptersample.model.BannerModel; import io.github.anotherme17.commonadaptersample.model.NormalModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Url;
package io.github.anotherme17.commonadaptersample.engine; /** * 作者:王浩 邮件:[email protected] * 创建时间:15/9/17 上午10:19 * 描述: */ public interface ApiEngine { @GET("normalModels.json") Call<List<NormalModel>> getNormalModels(); @GET
// Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/BannerModel.java // public class BannerModel { // public List<String> imgs; // public List<String> tips; // } // // Path: app/src/main/java/io/github/anotherme17/commonadaptersample/model/NormalModel.java // public class NormalModel { // public String title; // public String detail; // public String avatorPath; // public boolean selected; // // public NormalModel() { // } // // public NormalModel(String title, String detail, String avatorPath) { // this.title = title; // this.detail = detail; // this.avatorPath = avatorPath; // } // } // Path: app/src/main/java/io/github/anotherme17/commonadaptersample/engine/ApiEngine.java import java.util.List; import io.github.anotherme17.commonadaptersample.model.BannerModel; import io.github.anotherme17.commonadaptersample.model.NormalModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Url; package io.github.anotherme17.commonadaptersample.engine; /** * 作者:王浩 邮件:[email protected] * 创建时间:15/9/17 上午10:19 * 描述: */ public interface ApiEngine { @GET("normalModels.json") Call<List<NormalModel>> getNormalModels(); @GET
Call<BannerModel> loadBannerData(@Url String url);
anotherMe17/CommonAdapterSample
common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/manager/RvDelegateManager.java
// Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/RvItemViewDelegate.java // public interface RvItemViewDelegate<T> { // // /** // * 设置Item的LayoutId // */ // public abstract // @LayoutRes // int getItemLayoutId(); // // /** // * <P>通过 {@code position} 和 {@code itemData} 判断是否为该位置的Item <br/> // * 如果返回true 则将依次调用以下接口 <br/> // * {@link RvItemViewDelegate#onViewHolderCreated(Context, RvHolderHelper)} <br/> // * {@link RvItemViewDelegate#setItemChildListener(RvHolderHelper, int)}<br/> // * {@link RvItemViewDelegate#convert(Context, RvHolderHelper, int, Object)}<br/> // * </P> // * // * @param position Item的位置 // * @param itemData Item的内容 // * @return {@code true} - 是该位置的Item <br/> // * <code> false</code> - 不是该位置的Item // */ // public abstract boolean isDelegate(int position, T itemData); // // /** // * Item被创建时调用 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // */ // public abstract void onViewHolderCreated(Context context, RvHolderHelper helper); // // /** // * 设置Item内部ChildView 的监听 在 {@link io.github.anotherme17.commonrvadapter.adapter.RecyclerViewAdapter#onCreateViewHolder(ViewGroup, int)} 中调用 // * // * @param helper {@link RvHolderHelper} // * @param viewType Item 的 layoutId // */ // public abstract void setItemChildListener(RvHolderHelper helper, int viewType); // // /** // * 在此为Item里的View 赋值 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // * @param position Item的位置 不包括头和尾 // * @param itemData Item的内容 // */ // public abstract void convert(Context context, RvHolderHelper helper, int position, T itemData); // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateAlreadyExistException.java // public class DelegateAlreadyExistException extends RuntimeException { // // public DelegateAlreadyExistException(int viewType, RvItemViewDelegate delegate) { // super("An ItemViewDelegate is already registered for the viewTypeId = " // + viewType // + ". Already registered ItemViewDelegate is " // + delegate); // } // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateNotFoundException.java // public class DelegateNotFoundException extends RuntimeException { // // public DelegateNotFoundException() { // super("Can not Find any Delegate"); // } // // public DelegateNotFoundException(RvItemViewDelegate delegate) { // super("Can not find ItemViewDelegate = " + delegate); // } // // public DelegateNotFoundException(@LayoutRes int layoutId) { // super("Can not find ItemViewDelegate Which Layout Id = " + layoutId); // } // }
import android.support.annotation.LayoutRes; import android.support.v4.util.SparseArrayCompat; import io.github.anotherme17.commonrvadapter.RvItemViewDelegate; import io.github.anotherme17.commonrvadapter.exception.DelegateAlreadyExistException; import io.github.anotherme17.commonrvadapter.exception.DelegateNotFoundException;
package io.github.anotherme17.commonrvadapter.manager; /** * ItemDelegate 帮助类 * * @author anotherme17 * @version 1.0.0 */ public class RvDelegateManager<T> { protected SparseArrayCompat<RvItemViewDelegate<T>> mDelegates = new SparseArrayCompat<>(); public void addDelegate(RvItemViewDelegate<T> delegate) { int viewType = delegate.getItemLayoutId(); if (mDelegates.get(viewType) != null) {
// Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/RvItemViewDelegate.java // public interface RvItemViewDelegate<T> { // // /** // * 设置Item的LayoutId // */ // public abstract // @LayoutRes // int getItemLayoutId(); // // /** // * <P>通过 {@code position} 和 {@code itemData} 判断是否为该位置的Item <br/> // * 如果返回true 则将依次调用以下接口 <br/> // * {@link RvItemViewDelegate#onViewHolderCreated(Context, RvHolderHelper)} <br/> // * {@link RvItemViewDelegate#setItemChildListener(RvHolderHelper, int)}<br/> // * {@link RvItemViewDelegate#convert(Context, RvHolderHelper, int, Object)}<br/> // * </P> // * // * @param position Item的位置 // * @param itemData Item的内容 // * @return {@code true} - 是该位置的Item <br/> // * <code> false</code> - 不是该位置的Item // */ // public abstract boolean isDelegate(int position, T itemData); // // /** // * Item被创建时调用 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // */ // public abstract void onViewHolderCreated(Context context, RvHolderHelper helper); // // /** // * 设置Item内部ChildView 的监听 在 {@link io.github.anotherme17.commonrvadapter.adapter.RecyclerViewAdapter#onCreateViewHolder(ViewGroup, int)} 中调用 // * // * @param helper {@link RvHolderHelper} // * @param viewType Item 的 layoutId // */ // public abstract void setItemChildListener(RvHolderHelper helper, int viewType); // // /** // * 在此为Item里的View 赋值 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // * @param position Item的位置 不包括头和尾 // * @param itemData Item的内容 // */ // public abstract void convert(Context context, RvHolderHelper helper, int position, T itemData); // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateAlreadyExistException.java // public class DelegateAlreadyExistException extends RuntimeException { // // public DelegateAlreadyExistException(int viewType, RvItemViewDelegate delegate) { // super("An ItemViewDelegate is already registered for the viewTypeId = " // + viewType // + ". Already registered ItemViewDelegate is " // + delegate); // } // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateNotFoundException.java // public class DelegateNotFoundException extends RuntimeException { // // public DelegateNotFoundException() { // super("Can not Find any Delegate"); // } // // public DelegateNotFoundException(RvItemViewDelegate delegate) { // super("Can not find ItemViewDelegate = " + delegate); // } // // public DelegateNotFoundException(@LayoutRes int layoutId) { // super("Can not find ItemViewDelegate Which Layout Id = " + layoutId); // } // } // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/manager/RvDelegateManager.java import android.support.annotation.LayoutRes; import android.support.v4.util.SparseArrayCompat; import io.github.anotherme17.commonrvadapter.RvItemViewDelegate; import io.github.anotherme17.commonrvadapter.exception.DelegateAlreadyExistException; import io.github.anotherme17.commonrvadapter.exception.DelegateNotFoundException; package io.github.anotherme17.commonrvadapter.manager; /** * ItemDelegate 帮助类 * * @author anotherme17 * @version 1.0.0 */ public class RvDelegateManager<T> { protected SparseArrayCompat<RvItemViewDelegate<T>> mDelegates = new SparseArrayCompat<>(); public void addDelegate(RvItemViewDelegate<T> delegate) { int viewType = delegate.getItemLayoutId(); if (mDelegates.get(viewType) != null) {
throw new DelegateAlreadyExistException(viewType, mDelegates.get(viewType));
anotherMe17/CommonAdapterSample
common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/manager/RvDelegateManager.java
// Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/RvItemViewDelegate.java // public interface RvItemViewDelegate<T> { // // /** // * 设置Item的LayoutId // */ // public abstract // @LayoutRes // int getItemLayoutId(); // // /** // * <P>通过 {@code position} 和 {@code itemData} 判断是否为该位置的Item <br/> // * 如果返回true 则将依次调用以下接口 <br/> // * {@link RvItemViewDelegate#onViewHolderCreated(Context, RvHolderHelper)} <br/> // * {@link RvItemViewDelegate#setItemChildListener(RvHolderHelper, int)}<br/> // * {@link RvItemViewDelegate#convert(Context, RvHolderHelper, int, Object)}<br/> // * </P> // * // * @param position Item的位置 // * @param itemData Item的内容 // * @return {@code true} - 是该位置的Item <br/> // * <code> false</code> - 不是该位置的Item // */ // public abstract boolean isDelegate(int position, T itemData); // // /** // * Item被创建时调用 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // */ // public abstract void onViewHolderCreated(Context context, RvHolderHelper helper); // // /** // * 设置Item内部ChildView 的监听 在 {@link io.github.anotherme17.commonrvadapter.adapter.RecyclerViewAdapter#onCreateViewHolder(ViewGroup, int)} 中调用 // * // * @param helper {@link RvHolderHelper} // * @param viewType Item 的 layoutId // */ // public abstract void setItemChildListener(RvHolderHelper helper, int viewType); // // /** // * 在此为Item里的View 赋值 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // * @param position Item的位置 不包括头和尾 // * @param itemData Item的内容 // */ // public abstract void convert(Context context, RvHolderHelper helper, int position, T itemData); // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateAlreadyExistException.java // public class DelegateAlreadyExistException extends RuntimeException { // // public DelegateAlreadyExistException(int viewType, RvItemViewDelegate delegate) { // super("An ItemViewDelegate is already registered for the viewTypeId = " // + viewType // + ". Already registered ItemViewDelegate is " // + delegate); // } // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateNotFoundException.java // public class DelegateNotFoundException extends RuntimeException { // // public DelegateNotFoundException() { // super("Can not Find any Delegate"); // } // // public DelegateNotFoundException(RvItemViewDelegate delegate) { // super("Can not find ItemViewDelegate = " + delegate); // } // // public DelegateNotFoundException(@LayoutRes int layoutId) { // super("Can not find ItemViewDelegate Which Layout Id = " + layoutId); // } // }
import android.support.annotation.LayoutRes; import android.support.v4.util.SparseArrayCompat; import io.github.anotherme17.commonrvadapter.RvItemViewDelegate; import io.github.anotherme17.commonrvadapter.exception.DelegateAlreadyExistException; import io.github.anotherme17.commonrvadapter.exception.DelegateNotFoundException;
package io.github.anotherme17.commonrvadapter.manager; /** * ItemDelegate 帮助类 * * @author anotherme17 * @version 1.0.0 */ public class RvDelegateManager<T> { protected SparseArrayCompat<RvItemViewDelegate<T>> mDelegates = new SparseArrayCompat<>(); public void addDelegate(RvItemViewDelegate<T> delegate) { int viewType = delegate.getItemLayoutId(); if (mDelegates.get(viewType) != null) { throw new DelegateAlreadyExistException(viewType, mDelegates.get(viewType)); } else { mDelegates.put(viewType, delegate); } } public void addDelegate(RvItemViewDelegate<T>... delegates) { for (RvItemViewDelegate<T> delegate : delegates) { addDelegate(delegate); } } public void removeDelegate(RvItemViewDelegate<T> delegate) { int indexToRemove = mDelegates.indexOfValue(delegate); if (indexToRemove >= 0) { mDelegates.removeAt(indexToRemove); } else {
// Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/RvItemViewDelegate.java // public interface RvItemViewDelegate<T> { // // /** // * 设置Item的LayoutId // */ // public abstract // @LayoutRes // int getItemLayoutId(); // // /** // * <P>通过 {@code position} 和 {@code itemData} 判断是否为该位置的Item <br/> // * 如果返回true 则将依次调用以下接口 <br/> // * {@link RvItemViewDelegate#onViewHolderCreated(Context, RvHolderHelper)} <br/> // * {@link RvItemViewDelegate#setItemChildListener(RvHolderHelper, int)}<br/> // * {@link RvItemViewDelegate#convert(Context, RvHolderHelper, int, Object)}<br/> // * </P> // * // * @param position Item的位置 // * @param itemData Item的内容 // * @return {@code true} - 是该位置的Item <br/> // * <code> false</code> - 不是该位置的Item // */ // public abstract boolean isDelegate(int position, T itemData); // // /** // * Item被创建时调用 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // */ // public abstract void onViewHolderCreated(Context context, RvHolderHelper helper); // // /** // * 设置Item内部ChildView 的监听 在 {@link io.github.anotherme17.commonrvadapter.adapter.RecyclerViewAdapter#onCreateViewHolder(ViewGroup, int)} 中调用 // * // * @param helper {@link RvHolderHelper} // * @param viewType Item 的 layoutId // */ // public abstract void setItemChildListener(RvHolderHelper helper, int viewType); // // /** // * 在此为Item里的View 赋值 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // * @param position Item的位置 不包括头和尾 // * @param itemData Item的内容 // */ // public abstract void convert(Context context, RvHolderHelper helper, int position, T itemData); // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateAlreadyExistException.java // public class DelegateAlreadyExistException extends RuntimeException { // // public DelegateAlreadyExistException(int viewType, RvItemViewDelegate delegate) { // super("An ItemViewDelegate is already registered for the viewTypeId = " // + viewType // + ". Already registered ItemViewDelegate is " // + delegate); // } // } // // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateNotFoundException.java // public class DelegateNotFoundException extends RuntimeException { // // public DelegateNotFoundException() { // super("Can not Find any Delegate"); // } // // public DelegateNotFoundException(RvItemViewDelegate delegate) { // super("Can not find ItemViewDelegate = " + delegate); // } // // public DelegateNotFoundException(@LayoutRes int layoutId) { // super("Can not find ItemViewDelegate Which Layout Id = " + layoutId); // } // } // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/manager/RvDelegateManager.java import android.support.annotation.LayoutRes; import android.support.v4.util.SparseArrayCompat; import io.github.anotherme17.commonrvadapter.RvItemViewDelegate; import io.github.anotherme17.commonrvadapter.exception.DelegateAlreadyExistException; import io.github.anotherme17.commonrvadapter.exception.DelegateNotFoundException; package io.github.anotherme17.commonrvadapter.manager; /** * ItemDelegate 帮助类 * * @author anotherme17 * @version 1.0.0 */ public class RvDelegateManager<T> { protected SparseArrayCompat<RvItemViewDelegate<T>> mDelegates = new SparseArrayCompat<>(); public void addDelegate(RvItemViewDelegate<T> delegate) { int viewType = delegate.getItemLayoutId(); if (mDelegates.get(viewType) != null) { throw new DelegateAlreadyExistException(viewType, mDelegates.get(viewType)); } else { mDelegates.put(viewType, delegate); } } public void addDelegate(RvItemViewDelegate<T>... delegates) { for (RvItemViewDelegate<T> delegate : delegates) { addDelegate(delegate); } } public void removeDelegate(RvItemViewDelegate<T> delegate) { int indexToRemove = mDelegates.indexOfValue(delegate); if (indexToRemove >= 0) { mDelegates.removeAt(indexToRemove); } else {
throw new DelegateNotFoundException(delegate);
anotherMe17/CommonAdapterSample
commonadapter/src/main/java/io/github/anotherme17/commonadapter/common/CommonAdapterUitl.java
// Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/BaseMultiAdapter.java // public class BaseMultiAdapter<T> extends BaseAdapter { // private static final String TAG = "BaseMultiAdapter"; // // protected Context mContext; // protected List<T> mDatas; // // protected ItemViewManager<T> mViewManager; // // public BaseMultiAdapter(Context context, List<T> datas) { // this.mContext = context; // this.mDatas = datas; // mViewManager = new ItemViewManager<>(); // } // // public BaseMultiAdapter(Context context, List<T> datas, List<Integer> typeIds) { // this(context, datas); // mViewManager.addMapTab(typeIds); // } // // public BaseMultiAdapter(Context context, List<T> datas, int[] typeIds) { // this(context, datas); // mViewManager.addMapTab(typeIds); // } // // public void addSignalItem(T data, int position) { // mDatas.add(position, data); // notifyDataSetChanged(); // } // // public void addMultiItem(T data, int typeId, int position) { // mDatas.add(position, data); // mViewManager.addMapTab(typeId, position); // notifyDataSetChanged(); // } // // protected void setSignalMode(int typeId) { // mViewManager.isSignal = true; // mViewManager.signalId = typeId; // } // // protected void setMultiMode() { // mViewManager.isSignal = false; // mViewManager.signalId = 0; // } // // protected void addItemViewType(int typeId) { // mViewManager.addMapTab(typeId); // } // // protected void addItemViewType(int typeId, int position) { // mViewManager.addMapTab(typeId, position); // } // // public void addItemViewDegelate(ItemViewDelegate<T> viewDelegate) { // mViewManager.addDelegate(viewDelegate); // } // // public int getItemViewDegelateSize() { // return mViewManager.getDelegateCount(); // } // // public ItemViewDelegate<T> getItemViewDegelate(int position) { // return mViewManager.getItemViewDelegate(position); // } // // @Override // public int getCount() { // return mDatas.size(); // } // // @Override // public T getItem(int position) { // return mDatas.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public int getViewTypeCount() { // return getItemViewDegelateSize(); // } // // @Override // public int getItemViewType(int position) { // return mViewManager.getItemViewType(position); // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // ItemViewDelegate<T> viewDelegate = getItemViewDegelate(position); // int layoutId = viewDelegate.getItemLayoutId(); // ViewHolder viewHolder = null; // if (convertView == null) { // View view = LayoutInflater.from(mContext).inflate(layoutId, parent, false); // viewHolder = new ViewHolder(mContext, view, parent, position); // viewHolder.mLayoutId = layoutId; // viewDelegate.onViewHolderCreated(mContext, view, mDatas.get(position), position); // } else { // viewHolder = (ViewHolder) convertView.getTag(); // viewHolder.mPosition = position; // } // viewDelegate.convert(mContext, viewHolder, mDatas.get(position), position); // //convert(viewHolder, mDatas.get(position), position); // // return viewHolder.getConvertView(); // } // // } // // Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/ItemViewDelegate.java // public interface ItemViewDelegate<T> { // // public abstract // @LayoutRes // int getItemLayoutId(); // // public abstract int getItemViewId(); // // public abstract void onViewHolderCreated(Context context, View view, T data, int position); // // public abstract void convert(Context context, ViewHolder viewHolder, T data, int position); // }
import android.content.Context; import android.widget.ListView; import java.util.List; import io.github.anotherme17.commonadapter.BaseMultiAdapter; import io.github.anotherme17.commonadapter.ItemViewDelegate;
package io.github.anotherme17.commonadapter.common; /** * 项目名称:CommonAdapterSample * 类描述: * 创建人:renhao * 创建时间:2016/11/21 14:55 * 修改备注: */ public class CommonAdapterUitl<T> extends BaseMultiAdapter<T> { public CommonAdapterUitl(Context context, List<T> datas) { super(context, datas); } public CommonAdapterUitl(Context context, List<T> datas, int[] typeIds) { super(context, datas, typeIds); } public CommonAdapterUitl(Context context, List<T> datas, List<Integer> typeIds) { super(context, datas, typeIds); } public static class Builder<T> { private CommonAdapterUitl<T> mAdapter;
// Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/BaseMultiAdapter.java // public class BaseMultiAdapter<T> extends BaseAdapter { // private static final String TAG = "BaseMultiAdapter"; // // protected Context mContext; // protected List<T> mDatas; // // protected ItemViewManager<T> mViewManager; // // public BaseMultiAdapter(Context context, List<T> datas) { // this.mContext = context; // this.mDatas = datas; // mViewManager = new ItemViewManager<>(); // } // // public BaseMultiAdapter(Context context, List<T> datas, List<Integer> typeIds) { // this(context, datas); // mViewManager.addMapTab(typeIds); // } // // public BaseMultiAdapter(Context context, List<T> datas, int[] typeIds) { // this(context, datas); // mViewManager.addMapTab(typeIds); // } // // public void addSignalItem(T data, int position) { // mDatas.add(position, data); // notifyDataSetChanged(); // } // // public void addMultiItem(T data, int typeId, int position) { // mDatas.add(position, data); // mViewManager.addMapTab(typeId, position); // notifyDataSetChanged(); // } // // protected void setSignalMode(int typeId) { // mViewManager.isSignal = true; // mViewManager.signalId = typeId; // } // // protected void setMultiMode() { // mViewManager.isSignal = false; // mViewManager.signalId = 0; // } // // protected void addItemViewType(int typeId) { // mViewManager.addMapTab(typeId); // } // // protected void addItemViewType(int typeId, int position) { // mViewManager.addMapTab(typeId, position); // } // // public void addItemViewDegelate(ItemViewDelegate<T> viewDelegate) { // mViewManager.addDelegate(viewDelegate); // } // // public int getItemViewDegelateSize() { // return mViewManager.getDelegateCount(); // } // // public ItemViewDelegate<T> getItemViewDegelate(int position) { // return mViewManager.getItemViewDelegate(position); // } // // @Override // public int getCount() { // return mDatas.size(); // } // // @Override // public T getItem(int position) { // return mDatas.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public int getViewTypeCount() { // return getItemViewDegelateSize(); // } // // @Override // public int getItemViewType(int position) { // return mViewManager.getItemViewType(position); // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // ItemViewDelegate<T> viewDelegate = getItemViewDegelate(position); // int layoutId = viewDelegate.getItemLayoutId(); // ViewHolder viewHolder = null; // if (convertView == null) { // View view = LayoutInflater.from(mContext).inflate(layoutId, parent, false); // viewHolder = new ViewHolder(mContext, view, parent, position); // viewHolder.mLayoutId = layoutId; // viewDelegate.onViewHolderCreated(mContext, view, mDatas.get(position), position); // } else { // viewHolder = (ViewHolder) convertView.getTag(); // viewHolder.mPosition = position; // } // viewDelegate.convert(mContext, viewHolder, mDatas.get(position), position); // //convert(viewHolder, mDatas.get(position), position); // // return viewHolder.getConvertView(); // } // // } // // Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/ItemViewDelegate.java // public interface ItemViewDelegate<T> { // // public abstract // @LayoutRes // int getItemLayoutId(); // // public abstract int getItemViewId(); // // public abstract void onViewHolderCreated(Context context, View view, T data, int position); // // public abstract void convert(Context context, ViewHolder viewHolder, T data, int position); // } // Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/common/CommonAdapterUitl.java import android.content.Context; import android.widget.ListView; import java.util.List; import io.github.anotherme17.commonadapter.BaseMultiAdapter; import io.github.anotherme17.commonadapter.ItemViewDelegate; package io.github.anotherme17.commonadapter.common; /** * 项目名称:CommonAdapterSample * 类描述: * 创建人:renhao * 创建时间:2016/11/21 14:55 * 修改备注: */ public class CommonAdapterUitl<T> extends BaseMultiAdapter<T> { public CommonAdapterUitl(Context context, List<T> datas) { super(context, datas); } public CommonAdapterUitl(Context context, List<T> datas, int[] typeIds) { super(context, datas, typeIds); } public CommonAdapterUitl(Context context, List<T> datas, List<Integer> typeIds) { super(context, datas, typeIds); } public static class Builder<T> { private CommonAdapterUitl<T> mAdapter;
public Builder<T> createSignalAdapter(Context context, List<T> datas, ItemViewDelegate<T> viewDelegate) {
anotherMe17/CommonAdapterSample
commonadapter/src/main/java/io/github/anotherme17/commonadapter/BaseMultiAdapter.java
// Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/manager/ItemViewManager.java // public class ItemViewManager<T> { // public boolean isSignal = true; // public int signalId = 0; // protected SparseArrayCompat<ItemViewDelegate<T>> mDelegate = new SparseArrayCompat<>(); // // /** // * // */ // protected List<Integer> mMapTab = new ArrayList<>(); // // public ItemViewManager<T> addDelegate(@NonNull ItemViewDelegate<T> viewDelegate) { // int viewTypeId = viewDelegate.getItemViewId(); // if (mDelegate.get(viewTypeId) != null) { // throw new IllegalArgumentException("An ItemViewDelegate is already registered for the viewTypeId = " // + viewTypeId // + ". Already registered ItemViewDelegate is " // + mDelegate.get(viewTypeId)); // } // mDelegate.put(viewTypeId, viewDelegate); // return this; // } // // public ItemViewManager<T> addDelegate(@NonNull ItemViewDelegate<T> viewDelegate, int viewTypeId) { // if (mDelegate.get(viewTypeId) != null) { // throw new IllegalArgumentException("An ItemViewDelegate is already registered for the viewTypeId = " // + viewTypeId // + ". Already registered ItemViewDelegate is " // + mDelegate.get(viewTypeId)); // } // mDelegate.put(viewTypeId, viewDelegate); // return this; // } // // public ItemViewManager<T> removeDelegate(@NonNull ItemViewDelegate<T> viewDelegate) { // int indexToRemove = mDelegate.indexOfValue(viewDelegate); // if (indexToRemove >= 0) { // removeMapTabAll(mDelegate.keyAt(indexToRemove)); // mDelegate.removeAt(indexToRemove); // } else { // throw new IllegalArgumentException("Can not find ItemViewDelegate = " + viewDelegate); // } // // return this; // } // // public ItemViewManager<T> removeDelegate(int viewTypeId) { // int indexToRemove = mDelegate.indexOfKey(viewTypeId); // if (indexToRemove >= 0) { // removeMapTabAll(mDelegate.keyAt(indexToRemove)); // mDelegate.removeAt(indexToRemove); // } else { // throw new IllegalArgumentException("Can not find ItemType = " + viewTypeId); // } // // return this; // } // // /** // * 将types和degelate关联起来 // * // * @param typeIds 传入的type // */ // public void addMapTab(List<Integer> typeIds) { // mMapTab = typeIds; // } // // public void addMapTab(int[] typeIds) { // mMapTab = new ArrayList<>(); // for (int type : typeIds) { // mMapTab.add(type); // } // } // // public void addMapTab(int typeId, int position) { // if (position > getMapTabCount()) // throw new ArrayIndexOutOfBoundsException("position = " + position + "Can not over than MapTab size = " + getMapTabCount()); // mMapTab.add(position, typeId); // } // // public void addMapTab(int typeId) { // mMapTab.add(typeId); // } // // public int removeMapTabAll(int typeId) { // int removeNum = 0; // while (removeMapTab(typeId)) { // removeNum++; // } // return removeNum; // } // // public boolean removeMapTab(int typeId) { // return mMapTab.remove(Integer.valueOf(typeId)); // } // // public int getItemViewType(int position) { // return isSignal ? 0 : mDelegate.indexOfKey(mMapTab.get(position)); // } // // public int getItemViewLayoutId(int viewTypeId) { // return mDelegate.get(viewTypeId).getItemLayoutId(); // } // // public int getItemViewLayoutIdWithPosition(int position) { // return isSignal ? getItemViewLayoutId(signalId) : getItemViewLayoutId(mMapTab.get(position)); // } // // public ItemViewDelegate<T> getItemViewDelegate(int position) { // return isSignal ? mDelegate.get(signalId) : mDelegate.get(mMapTab.get(position)); // } // // public int getViewTypeId(int position) { // return isSignal ? signalId : mMapTab.get(position); // } // // public int getDelegateCount() { // return isSignal ? 1 : mDelegate.size(); // } // // public int getMapTabCount() { // return isSignal ? 1 : mMapTab.size(); // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.List; import io.github.anotherme17.commonadapter.manager.ItemViewManager;
package io.github.anotherme17.commonadapter; /** * 项目名称:CommonAdapterSample * 类描述: * 创建人:renhao * 创建时间:2016/11/24 11:03 * 修改备注: */ public class BaseMultiAdapter<T> extends BaseAdapter { private static final String TAG = "BaseMultiAdapter"; protected Context mContext; protected List<T> mDatas;
// Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/manager/ItemViewManager.java // public class ItemViewManager<T> { // public boolean isSignal = true; // public int signalId = 0; // protected SparseArrayCompat<ItemViewDelegate<T>> mDelegate = new SparseArrayCompat<>(); // // /** // * // */ // protected List<Integer> mMapTab = new ArrayList<>(); // // public ItemViewManager<T> addDelegate(@NonNull ItemViewDelegate<T> viewDelegate) { // int viewTypeId = viewDelegate.getItemViewId(); // if (mDelegate.get(viewTypeId) != null) { // throw new IllegalArgumentException("An ItemViewDelegate is already registered for the viewTypeId = " // + viewTypeId // + ". Already registered ItemViewDelegate is " // + mDelegate.get(viewTypeId)); // } // mDelegate.put(viewTypeId, viewDelegate); // return this; // } // // public ItemViewManager<T> addDelegate(@NonNull ItemViewDelegate<T> viewDelegate, int viewTypeId) { // if (mDelegate.get(viewTypeId) != null) { // throw new IllegalArgumentException("An ItemViewDelegate is already registered for the viewTypeId = " // + viewTypeId // + ". Already registered ItemViewDelegate is " // + mDelegate.get(viewTypeId)); // } // mDelegate.put(viewTypeId, viewDelegate); // return this; // } // // public ItemViewManager<T> removeDelegate(@NonNull ItemViewDelegate<T> viewDelegate) { // int indexToRemove = mDelegate.indexOfValue(viewDelegate); // if (indexToRemove >= 0) { // removeMapTabAll(mDelegate.keyAt(indexToRemove)); // mDelegate.removeAt(indexToRemove); // } else { // throw new IllegalArgumentException("Can not find ItemViewDelegate = " + viewDelegate); // } // // return this; // } // // public ItemViewManager<T> removeDelegate(int viewTypeId) { // int indexToRemove = mDelegate.indexOfKey(viewTypeId); // if (indexToRemove >= 0) { // removeMapTabAll(mDelegate.keyAt(indexToRemove)); // mDelegate.removeAt(indexToRemove); // } else { // throw new IllegalArgumentException("Can not find ItemType = " + viewTypeId); // } // // return this; // } // // /** // * 将types和degelate关联起来 // * // * @param typeIds 传入的type // */ // public void addMapTab(List<Integer> typeIds) { // mMapTab = typeIds; // } // // public void addMapTab(int[] typeIds) { // mMapTab = new ArrayList<>(); // for (int type : typeIds) { // mMapTab.add(type); // } // } // // public void addMapTab(int typeId, int position) { // if (position > getMapTabCount()) // throw new ArrayIndexOutOfBoundsException("position = " + position + "Can not over than MapTab size = " + getMapTabCount()); // mMapTab.add(position, typeId); // } // // public void addMapTab(int typeId) { // mMapTab.add(typeId); // } // // public int removeMapTabAll(int typeId) { // int removeNum = 0; // while (removeMapTab(typeId)) { // removeNum++; // } // return removeNum; // } // // public boolean removeMapTab(int typeId) { // return mMapTab.remove(Integer.valueOf(typeId)); // } // // public int getItemViewType(int position) { // return isSignal ? 0 : mDelegate.indexOfKey(mMapTab.get(position)); // } // // public int getItemViewLayoutId(int viewTypeId) { // return mDelegate.get(viewTypeId).getItemLayoutId(); // } // // public int getItemViewLayoutIdWithPosition(int position) { // return isSignal ? getItemViewLayoutId(signalId) : getItemViewLayoutId(mMapTab.get(position)); // } // // public ItemViewDelegate<T> getItemViewDelegate(int position) { // return isSignal ? mDelegate.get(signalId) : mDelegate.get(mMapTab.get(position)); // } // // public int getViewTypeId(int position) { // return isSignal ? signalId : mMapTab.get(position); // } // // public int getDelegateCount() { // return isSignal ? 1 : mDelegate.size(); // } // // public int getMapTabCount() { // return isSignal ? 1 : mMapTab.size(); // } // } // Path: commonadapter/src/main/java/io/github/anotherme17/commonadapter/BaseMultiAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.List; import io.github.anotherme17.commonadapter.manager.ItemViewManager; package io.github.anotherme17.commonadapter; /** * 项目名称:CommonAdapterSample * 类描述: * 创建人:renhao * 创建时间:2016/11/24 11:03 * 修改备注: */ public class BaseMultiAdapter<T> extends BaseAdapter { private static final String TAG = "BaseMultiAdapter"; protected Context mContext; protected List<T> mDatas;
protected ItemViewManager<T> mViewManager;
anotherMe17/CommonAdapterSample
common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateNotFoundException.java
// Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/RvItemViewDelegate.java // public interface RvItemViewDelegate<T> { // // /** // * 设置Item的LayoutId // */ // public abstract // @LayoutRes // int getItemLayoutId(); // // /** // * <P>通过 {@code position} 和 {@code itemData} 判断是否为该位置的Item <br/> // * 如果返回true 则将依次调用以下接口 <br/> // * {@link RvItemViewDelegate#onViewHolderCreated(Context, RvHolderHelper)} <br/> // * {@link RvItemViewDelegate#setItemChildListener(RvHolderHelper, int)}<br/> // * {@link RvItemViewDelegate#convert(Context, RvHolderHelper, int, Object)}<br/> // * </P> // * // * @param position Item的位置 // * @param itemData Item的内容 // * @return {@code true} - 是该位置的Item <br/> // * <code> false</code> - 不是该位置的Item // */ // public abstract boolean isDelegate(int position, T itemData); // // /** // * Item被创建时调用 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // */ // public abstract void onViewHolderCreated(Context context, RvHolderHelper helper); // // /** // * 设置Item内部ChildView 的监听 在 {@link io.github.anotherme17.commonrvadapter.adapter.RecyclerViewAdapter#onCreateViewHolder(ViewGroup, int)} 中调用 // * // * @param helper {@link RvHolderHelper} // * @param viewType Item 的 layoutId // */ // public abstract void setItemChildListener(RvHolderHelper helper, int viewType); // // /** // * 在此为Item里的View 赋值 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // * @param position Item的位置 不包括头和尾 // * @param itemData Item的内容 // */ // public abstract void convert(Context context, RvHolderHelper helper, int position, T itemData); // }
import android.support.annotation.LayoutRes; import io.github.anotherme17.commonrvadapter.RvItemViewDelegate;
package io.github.anotherme17.commonrvadapter.exception; /** * Created by Administrator on 2017/2/10. */ public class DelegateNotFoundException extends RuntimeException { public DelegateNotFoundException() { super("Can not Find any Delegate"); }
// Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/RvItemViewDelegate.java // public interface RvItemViewDelegate<T> { // // /** // * 设置Item的LayoutId // */ // public abstract // @LayoutRes // int getItemLayoutId(); // // /** // * <P>通过 {@code position} 和 {@code itemData} 判断是否为该位置的Item <br/> // * 如果返回true 则将依次调用以下接口 <br/> // * {@link RvItemViewDelegate#onViewHolderCreated(Context, RvHolderHelper)} <br/> // * {@link RvItemViewDelegate#setItemChildListener(RvHolderHelper, int)}<br/> // * {@link RvItemViewDelegate#convert(Context, RvHolderHelper, int, Object)}<br/> // * </P> // * // * @param position Item的位置 // * @param itemData Item的内容 // * @return {@code true} - 是该位置的Item <br/> // * <code> false</code> - 不是该位置的Item // */ // public abstract boolean isDelegate(int position, T itemData); // // /** // * Item被创建时调用 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // */ // public abstract void onViewHolderCreated(Context context, RvHolderHelper helper); // // /** // * 设置Item内部ChildView 的监听 在 {@link io.github.anotherme17.commonrvadapter.adapter.RecyclerViewAdapter#onCreateViewHolder(ViewGroup, int)} 中调用 // * // * @param helper {@link RvHolderHelper} // * @param viewType Item 的 layoutId // */ // public abstract void setItemChildListener(RvHolderHelper helper, int viewType); // // /** // * 在此为Item里的View 赋值 // * // * @param context {@link Context} 上下文 // * @param helper {@link RvHolderHelper} // * @param position Item的位置 不包括头和尾 // * @param itemData Item的内容 // */ // public abstract void convert(Context context, RvHolderHelper helper, int position, T itemData); // } // Path: common-rv-adapter/src/main/java/io/github/anotherme17/commonrvadapter/exception/DelegateNotFoundException.java import android.support.annotation.LayoutRes; import io.github.anotherme17.commonrvadapter.RvItemViewDelegate; package io.github.anotherme17.commonrvadapter.exception; /** * Created by Administrator on 2017/2/10. */ public class DelegateNotFoundException extends RuntimeException { public DelegateNotFoundException() { super("Can not Find any Delegate"); }
public DelegateNotFoundException(RvItemViewDelegate delegate) {
OpenWatch/OpenWatch-Android
app/OpenWatch/src/org/ale/openwatch/model/OWServerObjectInterface.java
// Path: app/OpenWatch/src/org/ale/openwatch/constants/Constants.java // public static enum CONTENT_TYPE { VIDEO, PHOTO, AUDIO, STORY, INVESTIGATION, MISSION };
import android.content.Context; import com.orm.androrm.QuerySet; import org.ale.openwatch.constants.Constants.CONTENT_TYPE; import org.json.JSONObject;
package org.ale.openwatch.model; public interface OWServerObjectInterface { public String getTitle(Context c); public void setTitle(Context c, String title); public String getFirstPosted(Context c); public void setFirstPosted(Context c, String first_posted); public String getLastEdited(Context c); public void setLastEdited(Context c, String last_edited); public void setViews(Context c, int views); public Integer getViews(Context c); public void setActions(Context c, int actions); public Integer getActions(Context c); public void setServerId(Context c, int server_id); public Integer getServerId(Context c); public void setDescription(Context c, String description); public String getDescription(Context c); public void setThumbnailUrl(Context c, String url); public String getThumbnailUrl(Context c); public OWUser getUser(Context c); public void setUser(Context c, OWUser user); public String getUUID(Context c); public void setUUID(Context c, String uuid); public void setLat(Context c, double lat); public double getLat(Context c); public void setLon(Context c, double lon); public double getLon(Context c);
// Path: app/OpenWatch/src/org/ale/openwatch/constants/Constants.java // public static enum CONTENT_TYPE { VIDEO, PHOTO, AUDIO, STORY, INVESTIGATION, MISSION }; // Path: app/OpenWatch/src/org/ale/openwatch/model/OWServerObjectInterface.java import android.content.Context; import com.orm.androrm.QuerySet; import org.ale.openwatch.constants.Constants.CONTENT_TYPE; import org.json.JSONObject; package org.ale.openwatch.model; public interface OWServerObjectInterface { public String getTitle(Context c); public void setTitle(Context c, String title); public String getFirstPosted(Context c); public void setFirstPosted(Context c, String first_posted); public String getLastEdited(Context c); public void setLastEdited(Context c, String last_edited); public void setViews(Context c, int views); public Integer getViews(Context c); public void setActions(Context c, int actions); public Integer getActions(Context c); public void setServerId(Context c, int server_id); public Integer getServerId(Context c); public void setDescription(Context c, String description); public String getDescription(Context c); public void setThumbnailUrl(Context c, String url); public String getThumbnailUrl(Context c); public OWUser getUser(Context c); public void setUser(Context c, OWUser user); public String getUUID(Context c); public void setUUID(Context c, String uuid); public void setLat(Context c, double lat); public double getLat(Context c); public void setLon(Context c, double lon); public double getLon(Context c);
public CONTENT_TYPE getContentType(Context c);
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/BaseTest.java
// Path: sdk/src/test/java/com/stormpath/sdk/utils/MockAndroidPlatform.java // public class MockAndroidPlatform extends AndroidPlatform { // // PreferenceStore preferenceStore = mock(PreferenceStore.class); // // ExecutorService synchronousExecutorService = new SynchronousExecutorService(); // // StormpathLogger logger = mock(StormpathLogger.class); // // public MockAndroidPlatform() { // super(Mocks.appContext()); // } // // @Override // public PreferenceStore preferenceStore() { // return preferenceStore; // } // // @Override // public ExecutorService httpExecutorService() { // return synchronousExecutorService; // } // // @Override // public Executor callbackExecutor() { // return synchronousExecutorService; // } // // @Override // public StormpathLogger logger() { // return logger; // } // // @Override // public String unknownErrorMessage() { // return "There was an unexpected error, please try again later."; // } // // @Override // public String networkErrorMessage() { // return "There was a problem with the network connection, please check your settings."; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // }
import com.stormpath.sdk.utils.MockAndroidPlatform; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.After; import org.junit.Before; import java.net.HttpURLConnection; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest;
package com.stormpath.sdk; public class BaseTest { private MockWebServer mockWebServer; private Platform mockPlatform; @Before public void setUp() throws Exception {
// Path: sdk/src/test/java/com/stormpath/sdk/utils/MockAndroidPlatform.java // public class MockAndroidPlatform extends AndroidPlatform { // // PreferenceStore preferenceStore = mock(PreferenceStore.class); // // ExecutorService synchronousExecutorService = new SynchronousExecutorService(); // // StormpathLogger logger = mock(StormpathLogger.class); // // public MockAndroidPlatform() { // super(Mocks.appContext()); // } // // @Override // public PreferenceStore preferenceStore() { // return preferenceStore; // } // // @Override // public ExecutorService httpExecutorService() { // return synchronousExecutorService; // } // // @Override // public Executor callbackExecutor() { // return synchronousExecutorService; // } // // @Override // public StormpathLogger logger() { // return logger; // } // // @Override // public String unknownErrorMessage() { // return "There was an unexpected error, please try again later."; // } // // @Override // public String networkErrorMessage() { // return "There was a problem with the network connection, please check your settings."; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // Path: sdk/src/test/java/com/stormpath/sdk/BaseTest.java import com.stormpath.sdk.utils.MockAndroidPlatform; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.After; import org.junit.Before; import java.net.HttpURLConnection; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; package com.stormpath.sdk; public class BaseTest { private MockWebServer mockWebServer; private Platform mockPlatform; @Before public void setUp() throws Exception {
mockPlatform = new MockAndroidPlatform();
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/BaseTest.java
// Path: sdk/src/test/java/com/stormpath/sdk/utils/MockAndroidPlatform.java // public class MockAndroidPlatform extends AndroidPlatform { // // PreferenceStore preferenceStore = mock(PreferenceStore.class); // // ExecutorService synchronousExecutorService = new SynchronousExecutorService(); // // StormpathLogger logger = mock(StormpathLogger.class); // // public MockAndroidPlatform() { // super(Mocks.appContext()); // } // // @Override // public PreferenceStore preferenceStore() { // return preferenceStore; // } // // @Override // public ExecutorService httpExecutorService() { // return synchronousExecutorService; // } // // @Override // public Executor callbackExecutor() { // return synchronousExecutorService; // } // // @Override // public StormpathLogger logger() { // return logger; // } // // @Override // public String unknownErrorMessage() { // return "There was an unexpected error, please try again later."; // } // // @Override // public String networkErrorMessage() { // return "There was a problem with the network connection, please check your settings."; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // }
import com.stormpath.sdk.utils.MockAndroidPlatform; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.After; import org.junit.Before; import java.net.HttpURLConnection; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest;
mockWebServer.shutdown(); } catch (Throwable t) { // Frankly, my dear, I don't give a damn } } protected String mockServerUrl() { return mockWebServer.url("/").toString(); } protected Platform mockPlatform() { return mockPlatform; } protected void initWithDefaults() { StormpathConfiguration config = new StormpathConfiguration.Builder().baseUrl(mockServerUrl()).build(); Stormpath.init(mockPlatform, config); Stormpath.setLogLevel(StormpathLogger.VERBOSE); } protected void enqueueResponse(MockResponse mockResponse) { mockWebServer.enqueue(mockResponse); } protected void enqueueStringResponse(String body) { MockResponse mockResponse = new MockResponse().setBody(body).setResponseCode(HttpURLConnection.HTTP_OK); mockWebServer.enqueue(mockResponse); } protected void enqueueResponse(String filename) {
// Path: sdk/src/test/java/com/stormpath/sdk/utils/MockAndroidPlatform.java // public class MockAndroidPlatform extends AndroidPlatform { // // PreferenceStore preferenceStore = mock(PreferenceStore.class); // // ExecutorService synchronousExecutorService = new SynchronousExecutorService(); // // StormpathLogger logger = mock(StormpathLogger.class); // // public MockAndroidPlatform() { // super(Mocks.appContext()); // } // // @Override // public PreferenceStore preferenceStore() { // return preferenceStore; // } // // @Override // public ExecutorService httpExecutorService() { // return synchronousExecutorService; // } // // @Override // public Executor callbackExecutor() { // return synchronousExecutorService; // } // // @Override // public StormpathLogger logger() { // return logger; // } // // @Override // public String unknownErrorMessage() { // return "There was an unexpected error, please try again later."; // } // // @Override // public String networkErrorMessage() { // return "There was a problem with the network connection, please check your settings."; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // Path: sdk/src/test/java/com/stormpath/sdk/BaseTest.java import com.stormpath.sdk.utils.MockAndroidPlatform; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.After; import org.junit.Before; import java.net.HttpURLConnection; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; mockWebServer.shutdown(); } catch (Throwable t) { // Frankly, my dear, I don't give a damn } } protected String mockServerUrl() { return mockWebServer.url("/").toString(); } protected Platform mockPlatform() { return mockPlatform; } protected void initWithDefaults() { StormpathConfiguration config = new StormpathConfiguration.Builder().baseUrl(mockServerUrl()).build(); Stormpath.init(mockPlatform, config); Stormpath.setLogLevel(StormpathLogger.VERBOSE); } protected void enqueueResponse(MockResponse mockResponse) { mockWebServer.enqueue(mockResponse); } protected void enqueueStringResponse(String body) { MockResponse mockResponse = new MockResponse().setBody(body).setResponseCode(HttpURLConnection.HTTP_OK); mockWebServer.enqueue(mockResponse); } protected void enqueueResponse(String filename) {
String body = ResourceUtils.readFromFile(filename);
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/LoginTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/StormpathTestCallback.java // public class StormpathTestCallback<T> implements StormpathCallback<T> { // // public T response; // // public StormpathError error; // // @Override // public void onSuccess(T t) { // this.response = t; // } // // @Override // public void onFailure(StormpathError error) { // this.error = error; // } // }
import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import com.stormpath.sdk.utils.StormpathTestCallback; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
@Test public void failedLoginCallsFailure() throws Exception { enqueueResponse("stormpath-login-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.login("user", "pass", callback); assertThat(callback.error.code()).isEqualTo(7100); assertThat(callback.error.status()).isEqualTo(400); assertThat(callback.error.developerMessage()).isEqualTo("Login attempt failed because the specified password is incorrect."); assertThat(callback.error.message()).isEqualTo("Invalid username or password."); assertThat(callback.error.moreInfo()).isEqualTo("http://docs.stormpath.com/errors/7100"); } @Test public void failedDeserializationCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.login("user", "pass", callback); assertThat(callback.error.message()).isEqualTo("There was an unexpected error, please try again later."); assertThat(callback.error.throwable()).isNotNull(); } @Test public void missingAccessTokenCallsFailure() throws Exception { enqueueStringResponse("{}"); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.login("user", "pass", callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/StormpathTestCallback.java // public class StormpathTestCallback<T> implements StormpathCallback<T> { // // public T response; // // public StormpathError error; // // @Override // public void onSuccess(T t) { // this.response = t; // } // // @Override // public void onFailure(StormpathError error) { // this.error = error; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/LoginTest.java import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import com.stormpath.sdk.utils.StormpathTestCallback; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @Test public void failedLoginCallsFailure() throws Exception { enqueueResponse("stormpath-login-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.login("user", "pass", callback); assertThat(callback.error.code()).isEqualTo(7100); assertThat(callback.error.status()).isEqualTo(400); assertThat(callback.error.developerMessage()).isEqualTo("Login attempt failed because the specified password is incorrect."); assertThat(callback.error.message()).isEqualTo("Invalid username or password."); assertThat(callback.error.moreInfo()).isEqualTo("http://docs.stormpath.com/errors/7100"); } @Test public void failedDeserializationCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.login("user", "pass", callback); assertThat(callback.error.message()).isEqualTo("There was an unexpected error, please try again later."); assertThat(callback.error.throwable()).isNotNull(); } @Test public void missingAccessTokenCallsFailure() throws Exception { enqueueStringResponse("{}"); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.login("user", "pass", callback);
verify(callback).onFailure(any(StormpathError.class));
stormpath/stormpath-sdk-android
sdk/src/main/java/com/stormpath/sdk/android/AndroidPlatform.java
// Path: sdk/src/main/java/com/stormpath/sdk/Platform.java // public abstract class Platform { // // /** // * @return the executor which should be used to run http calls on. This can't be the main thread on Android. // */ // public abstract ExecutorService httpExecutorService(); // // /** // * @return the executor which should be used for callbacks. This must be the main thread on Android. // */ // public abstract Executor callbackExecutor(); // // public abstract StormpathLogger logger(); // // public abstract PreferenceStore preferenceStore(); // // public abstract String unknownErrorMessage(); // // public abstract String networkErrorMessage(); // // } // // Path: sdk/src/main/java/com/stormpath/sdk/PreferenceStore.java // public interface PreferenceStore { // // void setAccessToken(String accessToken); // // String getAccessToken(); // // void clearAccessToken(); // // void setRefreshToken(String refreshToken); // // String getRefreshToken(); // // void clearRefreshToken(); // } // // Path: sdk/src/main/java/com/stormpath/sdk/StormpathLogger.java // public abstract class StormpathLogger { // // public static final int SILENT = 100; // // /** // * Logging levels -- values match up with android.util.Log // */ // public static final int VERBOSE = 2; // // public static final int DEBUG = 3; // // public static final int INFO = 4; // // public static final int WARN = 5; // // public static final int ERROR = 6; // // public static final int ASSERT = 7; // // @Retention(RetentionPolicy.SOURCE) // @IntDef(value = {SILENT, VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT}) // public @interface LogLevel { // // } // // /** // * By default we don't log anything. // */ // private int logLevel = SILENT; // // public void setLogLevel(@LogLevel int logLevel) { // this.logLevel = logLevel; // } // // protected abstract void log(@LogLevel int logLevel, String message); // // protected void log(@LogLevel int logLevel, Throwable throwable, String message, Object... args) { // if (!isLoggable(logLevel)) { // return; // } // // if (message == null) { // if (throwable == null) { // return; // Swallow message if it's null and there's no throwable. // } // // message = getStackTraceString(throwable); // } else { // if (args.length > 0) { // message = String.format(message, args); // } // if (throwable != null) { // message += "\n" + getStackTraceString(throwable); // } // } // // log(logLevel, message); // } // // private boolean isLoggable(@LogLevel int level) { // return level >= this.logLevel; // } // // private String getStackTraceString(Throwable t) { // // Don't replace this with Log.getStackTraceString() - it hides // // UnknownHostException, which is not what we want. // StringWriter sw = new StringWriter(256); // PrintWriter pw = new PrintWriter(sw, false); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // // public void v(String message, Object... args) { // log(VERBOSE, null, message, args); // } // // public void d(String message, Object... args) { // log(DEBUG, null, message, args); // } // // public void i(String message, Object... args) { // log(INFO, null, message, args); // } // // public void w(String message, Object... args) { // log(WARN, null, message, args); // } // // public void e(String message, Object... args) { // log(ERROR, null, message, args); // } // // public void wtf(String message, Object... args) { // log(ASSERT, null, message, args); // } // // public void v(Throwable t, String message, Object... args) { // log(VERBOSE, t, message, args); // } // // public void d(Throwable t, String message, Object... args) { // log(DEBUG, t, message, args); // } // // public void i(Throwable t, String message, Object... args) { // log(INFO, t, message, args); // } // // public void w(Throwable t, String message, Object... args) { // log(WARN, t, message, args); // } // // public void e(Throwable t, String message, Object... args) { // log(ERROR, t, message, args); // } // // public void wtf(Throwable t, String message, Object... args) { // log(ASSERT, t, message, args); // } // }
import com.stormpath.sdk.Platform; import com.stormpath.sdk.PreferenceStore; import com.stormpath.sdk.R; import com.stormpath.sdk.StormpathLogger; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import okhttp3.internal.Util;
package com.stormpath.sdk.android; public class AndroidPlatform extends Platform { private static final ExecutorService DEFAULT_HTTP_EXECUTOR_SERVICE = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("Stormpath Http Dispatcher", false)); private static final Executor DEFAULT_CALLBACK_EXECUTOR = new Executor() { private final Handler mainHandler = new Handler(Looper.getMainLooper()); @Override public void execute(@NonNull Runnable command) { mainHandler.post(command); } }; private final ExecutorService httpExecutor; private final Executor callbackExecutor;
// Path: sdk/src/main/java/com/stormpath/sdk/Platform.java // public abstract class Platform { // // /** // * @return the executor which should be used to run http calls on. This can't be the main thread on Android. // */ // public abstract ExecutorService httpExecutorService(); // // /** // * @return the executor which should be used for callbacks. This must be the main thread on Android. // */ // public abstract Executor callbackExecutor(); // // public abstract StormpathLogger logger(); // // public abstract PreferenceStore preferenceStore(); // // public abstract String unknownErrorMessage(); // // public abstract String networkErrorMessage(); // // } // // Path: sdk/src/main/java/com/stormpath/sdk/PreferenceStore.java // public interface PreferenceStore { // // void setAccessToken(String accessToken); // // String getAccessToken(); // // void clearAccessToken(); // // void setRefreshToken(String refreshToken); // // String getRefreshToken(); // // void clearRefreshToken(); // } // // Path: sdk/src/main/java/com/stormpath/sdk/StormpathLogger.java // public abstract class StormpathLogger { // // public static final int SILENT = 100; // // /** // * Logging levels -- values match up with android.util.Log // */ // public static final int VERBOSE = 2; // // public static final int DEBUG = 3; // // public static final int INFO = 4; // // public static final int WARN = 5; // // public static final int ERROR = 6; // // public static final int ASSERT = 7; // // @Retention(RetentionPolicy.SOURCE) // @IntDef(value = {SILENT, VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT}) // public @interface LogLevel { // // } // // /** // * By default we don't log anything. // */ // private int logLevel = SILENT; // // public void setLogLevel(@LogLevel int logLevel) { // this.logLevel = logLevel; // } // // protected abstract void log(@LogLevel int logLevel, String message); // // protected void log(@LogLevel int logLevel, Throwable throwable, String message, Object... args) { // if (!isLoggable(logLevel)) { // return; // } // // if (message == null) { // if (throwable == null) { // return; // Swallow message if it's null and there's no throwable. // } // // message = getStackTraceString(throwable); // } else { // if (args.length > 0) { // message = String.format(message, args); // } // if (throwable != null) { // message += "\n" + getStackTraceString(throwable); // } // } // // log(logLevel, message); // } // // private boolean isLoggable(@LogLevel int level) { // return level >= this.logLevel; // } // // private String getStackTraceString(Throwable t) { // // Don't replace this with Log.getStackTraceString() - it hides // // UnknownHostException, which is not what we want. // StringWriter sw = new StringWriter(256); // PrintWriter pw = new PrintWriter(sw, false); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // // public void v(String message, Object... args) { // log(VERBOSE, null, message, args); // } // // public void d(String message, Object... args) { // log(DEBUG, null, message, args); // } // // public void i(String message, Object... args) { // log(INFO, null, message, args); // } // // public void w(String message, Object... args) { // log(WARN, null, message, args); // } // // public void e(String message, Object... args) { // log(ERROR, null, message, args); // } // // public void wtf(String message, Object... args) { // log(ASSERT, null, message, args); // } // // public void v(Throwable t, String message, Object... args) { // log(VERBOSE, t, message, args); // } // // public void d(Throwable t, String message, Object... args) { // log(DEBUG, t, message, args); // } // // public void i(Throwable t, String message, Object... args) { // log(INFO, t, message, args); // } // // public void w(Throwable t, String message, Object... args) { // log(WARN, t, message, args); // } // // public void e(Throwable t, String message, Object... args) { // log(ERROR, t, message, args); // } // // public void wtf(Throwable t, String message, Object... args) { // log(ASSERT, t, message, args); // } // } // Path: sdk/src/main/java/com/stormpath/sdk/android/AndroidPlatform.java import com.stormpath.sdk.Platform; import com.stormpath.sdk.PreferenceStore; import com.stormpath.sdk.R; import com.stormpath.sdk.StormpathLogger; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import okhttp3.internal.Util; package com.stormpath.sdk.android; public class AndroidPlatform extends Platform { private static final ExecutorService DEFAULT_HTTP_EXECUTOR_SERVICE = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("Stormpath Http Dispatcher", false)); private static final Executor DEFAULT_CALLBACK_EXECUTOR = new Executor() { private final Handler mainHandler = new Handler(Looper.getMainLooper()); @Override public void execute(@NonNull Runnable command) { mainHandler.post(command); } }; private final ExecutorService httpExecutor; private final Executor callbackExecutor;
private final StormpathLogger logger;
stormpath/stormpath-sdk-android
sdk/src/main/java/com/stormpath/sdk/android/AndroidPlatform.java
// Path: sdk/src/main/java/com/stormpath/sdk/Platform.java // public abstract class Platform { // // /** // * @return the executor which should be used to run http calls on. This can't be the main thread on Android. // */ // public abstract ExecutorService httpExecutorService(); // // /** // * @return the executor which should be used for callbacks. This must be the main thread on Android. // */ // public abstract Executor callbackExecutor(); // // public abstract StormpathLogger logger(); // // public abstract PreferenceStore preferenceStore(); // // public abstract String unknownErrorMessage(); // // public abstract String networkErrorMessage(); // // } // // Path: sdk/src/main/java/com/stormpath/sdk/PreferenceStore.java // public interface PreferenceStore { // // void setAccessToken(String accessToken); // // String getAccessToken(); // // void clearAccessToken(); // // void setRefreshToken(String refreshToken); // // String getRefreshToken(); // // void clearRefreshToken(); // } // // Path: sdk/src/main/java/com/stormpath/sdk/StormpathLogger.java // public abstract class StormpathLogger { // // public static final int SILENT = 100; // // /** // * Logging levels -- values match up with android.util.Log // */ // public static final int VERBOSE = 2; // // public static final int DEBUG = 3; // // public static final int INFO = 4; // // public static final int WARN = 5; // // public static final int ERROR = 6; // // public static final int ASSERT = 7; // // @Retention(RetentionPolicy.SOURCE) // @IntDef(value = {SILENT, VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT}) // public @interface LogLevel { // // } // // /** // * By default we don't log anything. // */ // private int logLevel = SILENT; // // public void setLogLevel(@LogLevel int logLevel) { // this.logLevel = logLevel; // } // // protected abstract void log(@LogLevel int logLevel, String message); // // protected void log(@LogLevel int logLevel, Throwable throwable, String message, Object... args) { // if (!isLoggable(logLevel)) { // return; // } // // if (message == null) { // if (throwable == null) { // return; // Swallow message if it's null and there's no throwable. // } // // message = getStackTraceString(throwable); // } else { // if (args.length > 0) { // message = String.format(message, args); // } // if (throwable != null) { // message += "\n" + getStackTraceString(throwable); // } // } // // log(logLevel, message); // } // // private boolean isLoggable(@LogLevel int level) { // return level >= this.logLevel; // } // // private String getStackTraceString(Throwable t) { // // Don't replace this with Log.getStackTraceString() - it hides // // UnknownHostException, which is not what we want. // StringWriter sw = new StringWriter(256); // PrintWriter pw = new PrintWriter(sw, false); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // // public void v(String message, Object... args) { // log(VERBOSE, null, message, args); // } // // public void d(String message, Object... args) { // log(DEBUG, null, message, args); // } // // public void i(String message, Object... args) { // log(INFO, null, message, args); // } // // public void w(String message, Object... args) { // log(WARN, null, message, args); // } // // public void e(String message, Object... args) { // log(ERROR, null, message, args); // } // // public void wtf(String message, Object... args) { // log(ASSERT, null, message, args); // } // // public void v(Throwable t, String message, Object... args) { // log(VERBOSE, t, message, args); // } // // public void d(Throwable t, String message, Object... args) { // log(DEBUG, t, message, args); // } // // public void i(Throwable t, String message, Object... args) { // log(INFO, t, message, args); // } // // public void w(Throwable t, String message, Object... args) { // log(WARN, t, message, args); // } // // public void e(Throwable t, String message, Object... args) { // log(ERROR, t, message, args); // } // // public void wtf(Throwable t, String message, Object... args) { // log(ASSERT, t, message, args); // } // }
import com.stormpath.sdk.Platform; import com.stormpath.sdk.PreferenceStore; import com.stormpath.sdk.R; import com.stormpath.sdk.StormpathLogger; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import okhttp3.internal.Util;
package com.stormpath.sdk.android; public class AndroidPlatform extends Platform { private static final ExecutorService DEFAULT_HTTP_EXECUTOR_SERVICE = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("Stormpath Http Dispatcher", false)); private static final Executor DEFAULT_CALLBACK_EXECUTOR = new Executor() { private final Handler mainHandler = new Handler(Looper.getMainLooper()); @Override public void execute(@NonNull Runnable command) { mainHandler.post(command); } }; private final ExecutorService httpExecutor; private final Executor callbackExecutor; private final StormpathLogger logger;
// Path: sdk/src/main/java/com/stormpath/sdk/Platform.java // public abstract class Platform { // // /** // * @return the executor which should be used to run http calls on. This can't be the main thread on Android. // */ // public abstract ExecutorService httpExecutorService(); // // /** // * @return the executor which should be used for callbacks. This must be the main thread on Android. // */ // public abstract Executor callbackExecutor(); // // public abstract StormpathLogger logger(); // // public abstract PreferenceStore preferenceStore(); // // public abstract String unknownErrorMessage(); // // public abstract String networkErrorMessage(); // // } // // Path: sdk/src/main/java/com/stormpath/sdk/PreferenceStore.java // public interface PreferenceStore { // // void setAccessToken(String accessToken); // // String getAccessToken(); // // void clearAccessToken(); // // void setRefreshToken(String refreshToken); // // String getRefreshToken(); // // void clearRefreshToken(); // } // // Path: sdk/src/main/java/com/stormpath/sdk/StormpathLogger.java // public abstract class StormpathLogger { // // public static final int SILENT = 100; // // /** // * Logging levels -- values match up with android.util.Log // */ // public static final int VERBOSE = 2; // // public static final int DEBUG = 3; // // public static final int INFO = 4; // // public static final int WARN = 5; // // public static final int ERROR = 6; // // public static final int ASSERT = 7; // // @Retention(RetentionPolicy.SOURCE) // @IntDef(value = {SILENT, VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT}) // public @interface LogLevel { // // } // // /** // * By default we don't log anything. // */ // private int logLevel = SILENT; // // public void setLogLevel(@LogLevel int logLevel) { // this.logLevel = logLevel; // } // // protected abstract void log(@LogLevel int logLevel, String message); // // protected void log(@LogLevel int logLevel, Throwable throwable, String message, Object... args) { // if (!isLoggable(logLevel)) { // return; // } // // if (message == null) { // if (throwable == null) { // return; // Swallow message if it's null and there's no throwable. // } // // message = getStackTraceString(throwable); // } else { // if (args.length > 0) { // message = String.format(message, args); // } // if (throwable != null) { // message += "\n" + getStackTraceString(throwable); // } // } // // log(logLevel, message); // } // // private boolean isLoggable(@LogLevel int level) { // return level >= this.logLevel; // } // // private String getStackTraceString(Throwable t) { // // Don't replace this with Log.getStackTraceString() - it hides // // UnknownHostException, which is not what we want. // StringWriter sw = new StringWriter(256); // PrintWriter pw = new PrintWriter(sw, false); // t.printStackTrace(pw); // pw.flush(); // return sw.toString(); // } // // public void v(String message, Object... args) { // log(VERBOSE, null, message, args); // } // // public void d(String message, Object... args) { // log(DEBUG, null, message, args); // } // // public void i(String message, Object... args) { // log(INFO, null, message, args); // } // // public void w(String message, Object... args) { // log(WARN, null, message, args); // } // // public void e(String message, Object... args) { // log(ERROR, null, message, args); // } // // public void wtf(String message, Object... args) { // log(ASSERT, null, message, args); // } // // public void v(Throwable t, String message, Object... args) { // log(VERBOSE, t, message, args); // } // // public void d(Throwable t, String message, Object... args) { // log(DEBUG, t, message, args); // } // // public void i(Throwable t, String message, Object... args) { // log(INFO, t, message, args); // } // // public void w(Throwable t, String message, Object... args) { // log(WARN, t, message, args); // } // // public void e(Throwable t, String message, Object... args) { // log(ERROR, t, message, args); // } // // public void wtf(Throwable t, String message, Object... args) { // log(ASSERT, t, message, args); // } // } // Path: sdk/src/main/java/com/stormpath/sdk/android/AndroidPlatform.java import com.stormpath.sdk.Platform; import com.stormpath.sdk.PreferenceStore; import com.stormpath.sdk.R; import com.stormpath.sdk.StormpathLogger; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import okhttp3.internal.Util; package com.stormpath.sdk.android; public class AndroidPlatform extends Platform { private static final ExecutorService DEFAULT_HTTP_EXECUTOR_SERVICE = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("Stormpath Http Dispatcher", false)); private static final Executor DEFAULT_CALLBACK_EXECUTOR = new Executor() { private final Handler mainHandler = new Handler(Looper.getMainLooper()); @Override public void execute(@NonNull Runnable command) { mainHandler.post(command); } }; private final ExecutorService httpExecutor; private final Executor callbackExecutor; private final StormpathLogger logger;
private final PreferenceStore preferenceStore;
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/SocialProvidersTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/AccountStore.java // public class AccountStore { // private String href; // // private Map<String, String> provider; // // private String authorizeUri; // // public String getHref() { // return href; // } // // public String getProviderId() { // return provider.get("providerId"); // } // // public String getAuthorizeUri() { // return authorizeUri; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/LoginModel.java // public class LoginModel { // private List<FormField> formFields; // private List<AccountStore> accountStores; // // public List<FormField> getFormFields() { // return formFields; // } // // public List<AccountStore> getAccountStores() { // return accountStores; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.AccountStore; import com.stormpath.sdk.models.LoginModel; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify;
package com.stormpath.sdk; public class SocialProvidersTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/spa-config"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulFetchCallsSuccess() throws Exception { enqueueResponse("stormpath-social-providers-response.json");
// Path: sdk/src/main/java/com/stormpath/sdk/models/AccountStore.java // public class AccountStore { // private String href; // // private Map<String, String> provider; // // private String authorizeUri; // // public String getHref() { // return href; // } // // public String getProviderId() { // return provider.get("providerId"); // } // // public String getAuthorizeUri() { // return authorizeUri; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/LoginModel.java // public class LoginModel { // private List<FormField> formFields; // private List<AccountStore> accountStores; // // public List<FormField> getFormFields() { // return formFields; // } // // public List<AccountStore> getAccountStores() { // return accountStores; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/SocialProvidersTest.java import com.stormpath.sdk.models.AccountStore; import com.stormpath.sdk.models.LoginModel; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify; package com.stormpath.sdk; public class SocialProvidersTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/spa-config"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulFetchCallsSuccess() throws Exception { enqueueResponse("stormpath-social-providers-response.json");
StormpathCallback<LoginModel> callback = mock(StormpathCallback.class);
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/SocialProvidersTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/AccountStore.java // public class AccountStore { // private String href; // // private Map<String, String> provider; // // private String authorizeUri; // // public String getHref() { // return href; // } // // public String getProviderId() { // return provider.get("providerId"); // } // // public String getAuthorizeUri() { // return authorizeUri; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/LoginModel.java // public class LoginModel { // private List<FormField> formFields; // private List<AccountStore> accountStores; // // public List<FormField> getFormFields() { // return formFields; // } // // public List<AccountStore> getAccountStores() { // return accountStores; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.AccountStore; import com.stormpath.sdk.models.LoginModel; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify;
package com.stormpath.sdk; public class SocialProvidersTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/spa-config"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulFetchCallsSuccess() throws Exception { enqueueResponse("stormpath-social-providers-response.json"); StormpathCallback<LoginModel> callback = mock(StormpathCallback.class); Stormpath.apiManager.getLoginModel(callback); verify(callback).onSuccess(any(LoginModel.class)); } @Test public void successfulFetchReturnsCorrectData() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); SocialProvidersCallback callback = new SocialProvidersCallback(); enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(callback); assertThat(callback.loginModel.getAccountStores()).hasSize(3);
// Path: sdk/src/main/java/com/stormpath/sdk/models/AccountStore.java // public class AccountStore { // private String href; // // private Map<String, String> provider; // // private String authorizeUri; // // public String getHref() { // return href; // } // // public String getProviderId() { // return provider.get("providerId"); // } // // public String getAuthorizeUri() { // return authorizeUri; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/LoginModel.java // public class LoginModel { // private List<FormField> formFields; // private List<AccountStore> accountStores; // // public List<FormField> getFormFields() { // return formFields; // } // // public List<AccountStore> getAccountStores() { // return accountStores; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/SocialProvidersTest.java import com.stormpath.sdk.models.AccountStore; import com.stormpath.sdk.models.LoginModel; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify; package com.stormpath.sdk; public class SocialProvidersTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/spa-config"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulFetchCallsSuccess() throws Exception { enqueueResponse("stormpath-social-providers-response.json"); StormpathCallback<LoginModel> callback = mock(StormpathCallback.class); Stormpath.apiManager.getLoginModel(callback); verify(callback).onSuccess(any(LoginModel.class)); } @Test public void successfulFetchReturnsCorrectData() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); SocialProvidersCallback callback = new SocialProvidersCallback(); enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(callback); assertThat(callback.loginModel.getAccountStores()).hasSize(3);
AccountStore facebook = callback.loginModel.getAccountStores().get(0);
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/SocialProvidersTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/AccountStore.java // public class AccountStore { // private String href; // // private Map<String, String> provider; // // private String authorizeUri; // // public String getHref() { // return href; // } // // public String getProviderId() { // return provider.get("providerId"); // } // // public String getAuthorizeUri() { // return authorizeUri; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/LoginModel.java // public class LoginModel { // private List<FormField> formFields; // private List<AccountStore> accountStores; // // public List<FormField> getFormFields() { // return formFields; // } // // public List<AccountStore> getAccountStores() { // return accountStores; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.AccountStore; import com.stormpath.sdk.models.LoginModel; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify;
@Test public void successfulFetchReturnsCorrectData() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); SocialProvidersCallback callback = new SocialProvidersCallback(); enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(callback); assertThat(callback.loginModel.getAccountStores()).hasSize(3); AccountStore facebook = callback.loginModel.getAccountStores().get(0); AccountStore google = callback.loginModel.getAccountStores().get(1); AccountStore linkedin = callback.loginModel.getAccountStores().get(2); assertThat(facebook.getProviderId()).isEqualTo("facebook"); assertThat(facebook.getHref()).isEqualTo("1234567890123456"); assertThat(google.getProviderId()).isEqualTo("google"); assertThat(google.getHref()).isEqualTo("123456789012-abcdefghijklmnopqrstuwvxyz123456.apps.googleusercontent.com"); assertThat(linkedin.getProviderId()).isEqualTo("linkedin"); assertThat(linkedin.getHref()).isEqualTo("abcdef12345678"); } @Test public void failedFetchCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<LoginModel> callback = mock(StormpathCallback.class); Stormpath.apiManager.getLoginModel(callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/AccountStore.java // public class AccountStore { // private String href; // // private Map<String, String> provider; // // private String authorizeUri; // // public String getHref() { // return href; // } // // public String getProviderId() { // return provider.get("providerId"); // } // // public String getAuthorizeUri() { // return authorizeUri; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/LoginModel.java // public class LoginModel { // private List<FormField> formFields; // private List<AccountStore> accountStores; // // public List<FormField> getFormFields() { // return formFields; // } // // public List<AccountStore> getAccountStores() { // return accountStores; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/SocialProvidersTest.java import com.stormpath.sdk.models.AccountStore; import com.stormpath.sdk.models.LoginModel; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify; @Test public void successfulFetchReturnsCorrectData() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); SocialProvidersCallback callback = new SocialProvidersCallback(); enqueueResponse("stormpath-social-providers-response.json"); Stormpath.apiManager.getLoginModel(callback); assertThat(callback.loginModel.getAccountStores()).hasSize(3); AccountStore facebook = callback.loginModel.getAccountStores().get(0); AccountStore google = callback.loginModel.getAccountStores().get(1); AccountStore linkedin = callback.loginModel.getAccountStores().get(2); assertThat(facebook.getProviderId()).isEqualTo("facebook"); assertThat(facebook.getHref()).isEqualTo("1234567890123456"); assertThat(google.getProviderId()).isEqualTo("google"); assertThat(google.getHref()).isEqualTo("123456789012-abcdefghijklmnopqrstuwvxyz123456.apps.googleusercontent.com"); assertThat(linkedin.getProviderId()).isEqualTo("linkedin"); assertThat(linkedin.getHref()).isEqualTo("abcdef12345678"); } @Test public void failedFetchCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<LoginModel> callback = mock(StormpathCallback.class); Stormpath.apiManager.getLoginModel(callback);
verify(callback).onFailure(any(StormpathError.class));
stormpath/stormpath-sdk-android
sdk/src/main/java/com/stormpath/sdk/StormpathCallback.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.StormpathError;
package com.stormpath.sdk; public interface StormpathCallback<T> { void onSuccess(T t);
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/main/java/com/stormpath/sdk/StormpathCallback.java import com.stormpath.sdk.models.StormpathError; package com.stormpath.sdk; public interface StormpathCallback<T> { void onSuccess(T t);
void onFailure(StormpathError error);
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/VerifyEmailTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package com.stormpath.sdk; public class VerifyEmailTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { String sptoken = "OiqqtEzEHJZwrZ70SYJh8"; enqueueEmptyResponse(HttpURLConnection.HTTP_OK); Stormpath.verifyEmail(sptoken, mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/verify?sptoken=OiqqtEzEHJZwrZ70SYJh8"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulVerifyCallsSuccess() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.verifyEmail("OiqqtEzEHJZwrZ70SYJh8", callback); verify(callback).onSuccess(null); } @Test public void failedVerifyCallsFailure() throws Exception { enqueueResponse("stormpath-verify-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.verifyEmail("OiqqtEzEHJZwrZ70SYJh8", callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/VerifyEmailTest.java import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package com.stormpath.sdk; public class VerifyEmailTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { String sptoken = "OiqqtEzEHJZwrZ70SYJh8"; enqueueEmptyResponse(HttpURLConnection.HTTP_OK); Stormpath.verifyEmail(sptoken, mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/verify?sptoken=OiqqtEzEHJZwrZ70SYJh8"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulVerifyCallsSuccess() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.verifyEmail("OiqqtEzEHJZwrZ70SYJh8", callback); verify(callback).onSuccess(null); } @Test public void failedVerifyCallsFailure() throws Exception { enqueueResponse("stormpath-verify-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.verifyEmail("OiqqtEzEHJZwrZ70SYJh8", callback);
verify(callback).onFailure(any(StormpathError.class));
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/RegisterTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/RegistrationForm.java // public class RegistrationForm implements Serializable { // @Json(name = "givenName") // private String givenName; // // @Json(name = "surname") // private String surname; // // @Json(name = "email") // private String email; // // @Json(name = "password") // private String password; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Map<String, String> customData; // // public RegistrationForm(String email, String password) { // this.email = email; // this.password = password; // } // // public String getGivenName() { // return givenName; // } // // public RegistrationForm setGivenName(String givenName) { // this.givenName = givenName; // return this; // } // // public String getSurname() { // return surname; // } // // public RegistrationForm setSurname(String surname) { // this.surname = surname; // return this; // } // // public String getEmail() { // return email; // } // // public RegistrationForm setEmail(String email) { // this.email = email; // return this; // } // // public String getPassword() { // return password; // } // // public RegistrationForm setPassword(String password) { // this.password = password; // return this; // } // // public String getUsername() { // return username; // } // // public RegistrationForm setUsername(String username) { // this.username = username; // return this; // } // // public Map<String, String> getCustomData() { // return customData; // } // // public RegistrationForm setCustomData(Map<String, String> customData) { // this.customData = customData; // return this; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // }
import com.stormpath.sdk.models.RegistrationForm; import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package com.stormpath.sdk; public class RegisterTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueResponse("stormpath-register-response.json");
// Path: sdk/src/main/java/com/stormpath/sdk/models/RegistrationForm.java // public class RegistrationForm implements Serializable { // @Json(name = "givenName") // private String givenName; // // @Json(name = "surname") // private String surname; // // @Json(name = "email") // private String email; // // @Json(name = "password") // private String password; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Map<String, String> customData; // // public RegistrationForm(String email, String password) { // this.email = email; // this.password = password; // } // // public String getGivenName() { // return givenName; // } // // public RegistrationForm setGivenName(String givenName) { // this.givenName = givenName; // return this; // } // // public String getSurname() { // return surname; // } // // public RegistrationForm setSurname(String surname) { // this.surname = surname; // return this; // } // // public String getEmail() { // return email; // } // // public RegistrationForm setEmail(String email) { // this.email = email; // return this; // } // // public String getPassword() { // return password; // } // // public RegistrationForm setPassword(String password) { // this.password = password; // return this; // } // // public String getUsername() { // return username; // } // // public RegistrationForm setUsername(String username) { // this.username = username; // return this; // } // // public Map<String, String> getCustomData() { // return customData; // } // // public RegistrationForm setCustomData(Map<String, String> customData) { // this.customData = customData; // return this; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // Path: sdk/src/test/java/com/stormpath/sdk/RegisterTest.java import com.stormpath.sdk.models.RegistrationForm; import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package com.stormpath.sdk; public class RegisterTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueResponse("stormpath-register-response.json");
RegistrationForm form = new RegistrationForm("[email protected]", "Test1234&");
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/RegisterTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/RegistrationForm.java // public class RegistrationForm implements Serializable { // @Json(name = "givenName") // private String givenName; // // @Json(name = "surname") // private String surname; // // @Json(name = "email") // private String email; // // @Json(name = "password") // private String password; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Map<String, String> customData; // // public RegistrationForm(String email, String password) { // this.email = email; // this.password = password; // } // // public String getGivenName() { // return givenName; // } // // public RegistrationForm setGivenName(String givenName) { // this.givenName = givenName; // return this; // } // // public String getSurname() { // return surname; // } // // public RegistrationForm setSurname(String surname) { // this.surname = surname; // return this; // } // // public String getEmail() { // return email; // } // // public RegistrationForm setEmail(String email) { // this.email = email; // return this; // } // // public String getPassword() { // return password; // } // // public RegistrationForm setPassword(String password) { // this.password = password; // return this; // } // // public String getUsername() { // return username; // } // // public RegistrationForm setUsername(String username) { // this.username = username; // return this; // } // // public Map<String, String> getCustomData() { // return customData; // } // // public RegistrationForm setCustomData(Map<String, String> customData) { // this.customData = customData; // return this; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // }
import com.stormpath.sdk.models.RegistrationForm; import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
form.setGivenName("John"); form.setSurname("Deere"); Stormpath.register(form, mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/register"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=utf-8"); assertThat(request.getBody().readUtf8()) .isEqualTo("{\"email\":\"[email protected]\",\"givenName\":\"John\",\"password\":\"Test1234&\",\"surname\":\"Deere\"}"); } @Test public void successfulRegistrationCallsSuccess() throws Exception { enqueueResponse("stormpath-register-response.json"); StormpathCallback<Void> callback = mock(StormpathCallback.class); RegistrationForm form = new RegistrationForm("[email protected]", "Test1234"); form.setGivenName("John"); form.setSurname("Deere"); Stormpath.register(form, callback); verify(callback).onSuccess(null); } @Test public void successfulRegistrationSavesTokens() throws Exception { MockResponse mockResponse = new MockResponse()
// Path: sdk/src/main/java/com/stormpath/sdk/models/RegistrationForm.java // public class RegistrationForm implements Serializable { // @Json(name = "givenName") // private String givenName; // // @Json(name = "surname") // private String surname; // // @Json(name = "email") // private String email; // // @Json(name = "password") // private String password; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Map<String, String> customData; // // public RegistrationForm(String email, String password) { // this.email = email; // this.password = password; // } // // public String getGivenName() { // return givenName; // } // // public RegistrationForm setGivenName(String givenName) { // this.givenName = givenName; // return this; // } // // public String getSurname() { // return surname; // } // // public RegistrationForm setSurname(String surname) { // this.surname = surname; // return this; // } // // public String getEmail() { // return email; // } // // public RegistrationForm setEmail(String email) { // this.email = email; // return this; // } // // public String getPassword() { // return password; // } // // public RegistrationForm setPassword(String password) { // this.password = password; // return this; // } // // public String getUsername() { // return username; // } // // public RegistrationForm setUsername(String username) { // this.username = username; // return this; // } // // public Map<String, String> getCustomData() { // return customData; // } // // public RegistrationForm setCustomData(Map<String, String> customData) { // this.customData = customData; // return this; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // Path: sdk/src/test/java/com/stormpath/sdk/RegisterTest.java import com.stormpath.sdk.models.RegistrationForm; import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; form.setGivenName("John"); form.setSurname("Deere"); Stormpath.register(form, mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/register"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=utf-8"); assertThat(request.getBody().readUtf8()) .isEqualTo("{\"email\":\"[email protected]\",\"givenName\":\"John\",\"password\":\"Test1234&\",\"surname\":\"Deere\"}"); } @Test public void successfulRegistrationCallsSuccess() throws Exception { enqueueResponse("stormpath-register-response.json"); StormpathCallback<Void> callback = mock(StormpathCallback.class); RegistrationForm form = new RegistrationForm("[email protected]", "Test1234"); form.setGivenName("John"); form.setSurname("Deere"); Stormpath.register(form, callback); verify(callback).onSuccess(null); } @Test public void successfulRegistrationSavesTokens() throws Exception { MockResponse mockResponse = new MockResponse()
.setBody(ResourceUtils.readFromFile("stormpath-register-response.json"))
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/PreferenceStoreTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/android/SharedPrefsStore.java // public class SharedPrefsStore implements PreferenceStore { // // public static final String KEY_ACCESS_TOKEN = "stormpath-access-token"; // // public static final String KEY_REFRESH_TOKEN = "stormpath-refresh-token"; // // private final SharedPreferences sharedPreferences; // // public SharedPrefsStore(Context appContext) { // sharedPreferences = appContext.getSharedPreferences("stormpath-shared-prefs", Context.MODE_PRIVATE); // } // // @SuppressLint("CommitPrefEdits") // private void saveStringPreference(String key, String value) { // sharedPreferences.edit().putString(key, value).commit(); // } // // @SuppressLint("CommitPrefEdits") // private void removeStringPreference(String key) { // sharedPreferences.edit().remove(key).commit(); // } // // @Override // public void setAccessToken(String accessToken) { // saveStringPreference(KEY_ACCESS_TOKEN, accessToken); // } // // @Override // public String getAccessToken() { // return sharedPreferences.getString(KEY_ACCESS_TOKEN, null); // } // // @Override // public void clearAccessToken() { // removeStringPreference(KEY_ACCESS_TOKEN); // } // // @Override // public void setRefreshToken(String refreshToken) { // saveStringPreference(KEY_REFRESH_TOKEN, refreshToken); // } // // @Override // public String getRefreshToken() { // return sharedPreferences.getString(KEY_REFRESH_TOKEN, null); // } // // @Override // public void clearRefreshToken() { // removeStringPreference(KEY_REFRESH_TOKEN); // } // }
import com.stormpath.sdk.android.SharedPrefsStore; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import static org.assertj.core.api.Assertions.assertThat;
package com.stormpath.sdk; @RunWith(RobolectricGradleTestRunner.class) public class PreferenceStoreTest extends BaseTest { private PreferenceStore preferenceStore; @Before public void setUp() {
// Path: sdk/src/main/java/com/stormpath/sdk/android/SharedPrefsStore.java // public class SharedPrefsStore implements PreferenceStore { // // public static final String KEY_ACCESS_TOKEN = "stormpath-access-token"; // // public static final String KEY_REFRESH_TOKEN = "stormpath-refresh-token"; // // private final SharedPreferences sharedPreferences; // // public SharedPrefsStore(Context appContext) { // sharedPreferences = appContext.getSharedPreferences("stormpath-shared-prefs", Context.MODE_PRIVATE); // } // // @SuppressLint("CommitPrefEdits") // private void saveStringPreference(String key, String value) { // sharedPreferences.edit().putString(key, value).commit(); // } // // @SuppressLint("CommitPrefEdits") // private void removeStringPreference(String key) { // sharedPreferences.edit().remove(key).commit(); // } // // @Override // public void setAccessToken(String accessToken) { // saveStringPreference(KEY_ACCESS_TOKEN, accessToken); // } // // @Override // public String getAccessToken() { // return sharedPreferences.getString(KEY_ACCESS_TOKEN, null); // } // // @Override // public void clearAccessToken() { // removeStringPreference(KEY_ACCESS_TOKEN); // } // // @Override // public void setRefreshToken(String refreshToken) { // saveStringPreference(KEY_REFRESH_TOKEN, refreshToken); // } // // @Override // public String getRefreshToken() { // return sharedPreferences.getString(KEY_REFRESH_TOKEN, null); // } // // @Override // public void clearRefreshToken() { // removeStringPreference(KEY_REFRESH_TOKEN); // } // } // Path: sdk/src/test/java/com/stormpath/sdk/PreferenceStoreTest.java import com.stormpath.sdk.android.SharedPrefsStore; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import static org.assertj.core.api.Assertions.assertThat; package com.stormpath.sdk; @RunWith(RobolectricGradleTestRunner.class) public class PreferenceStoreTest extends BaseTest { private PreferenceStore preferenceStore; @Before public void setUp() {
preferenceStore = new SharedPrefsStore(RuntimeEnvironment.application);
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/UserProfileTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/Account.java // public class Account implements Serializable { // // @Json(name = "href") // private String href; // // @Json(name = "email") // private String email; // // @Json(name = "givenName") // private String givenName; // // @Json(name = "middleName") // private String middleName; // // @Json(name = "surname") // private String surname; // // @Json(name = "fullName") // private String fullName; // // @Json(name = "status") // private String status; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Object customData; // // public String getHref() { // return href; // } // // public String getEmail() { // return email; // } // // public String getGivenName() { // return givenName; // } // // public String getMiddleName() { // return middleName; // } // // public String getSurname() { // return surname; // } // // public String getFullName() { // return fullName; // } // // public String getStatus() { // return status; // } // // public String getUsername() { // return username; // } // // public Object getCustomData() { // return customData; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.Account; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify;
package com.stormpath.sdk; public class UserProfileTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { String accessToken = "eyJraWQiOiI2WjA3NEJBQzhTM0tGWE5KOVhFTldEVUhGIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiIzQjlEclh4NG9RdFR6VWU0dFhCR0d5I" + "iwiaWF0IjoxNDU1MjE4Mzg0LCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy8yUnJxS25UaW91M1F3Tm50RTN0Y0VHI" + "iwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy81TXNRVEE0UVI5c0hZNnlRQlFFSXlLIiwiZXhwIjoxNDYwNDAyMzg0fQ.lt" + "Fz1735IRnD0vIgdeKC4oInxe8K0KzhDJ95RgRuqmA"; stub(mockPlatform().preferenceStore().getAccessToken()).toReturn(accessToken); enqueueResponse("stormpath-user-profile-response.json"); Stormpath.getAccount(mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/me"); assertThat(request.getHeader("Authorization")).isEqualTo("Bearer " + accessToken); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulFetchCallsSuccess() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); enqueueResponse("stormpath-user-profile-response.json");
// Path: sdk/src/main/java/com/stormpath/sdk/models/Account.java // public class Account implements Serializable { // // @Json(name = "href") // private String href; // // @Json(name = "email") // private String email; // // @Json(name = "givenName") // private String givenName; // // @Json(name = "middleName") // private String middleName; // // @Json(name = "surname") // private String surname; // // @Json(name = "fullName") // private String fullName; // // @Json(name = "status") // private String status; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Object customData; // // public String getHref() { // return href; // } // // public String getEmail() { // return email; // } // // public String getGivenName() { // return givenName; // } // // public String getMiddleName() { // return middleName; // } // // public String getSurname() { // return surname; // } // // public String getFullName() { // return fullName; // } // // public String getStatus() { // return status; // } // // public String getUsername() { // return username; // } // // public Object getCustomData() { // return customData; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/UserProfileTest.java import com.stormpath.sdk.models.Account; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify; package com.stormpath.sdk; public class UserProfileTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { String accessToken = "eyJraWQiOiI2WjA3NEJBQzhTM0tGWE5KOVhFTldEVUhGIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiIzQjlEclh4NG9RdFR6VWU0dFhCR0d5I" + "iwiaWF0IjoxNDU1MjE4Mzg0LCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy8yUnJxS25UaW91M1F3Tm50RTN0Y0VHI" + "iwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy81TXNRVEE0UVI5c0hZNnlRQlFFSXlLIiwiZXhwIjoxNDYwNDAyMzg0fQ.lt" + "Fz1735IRnD0vIgdeKC4oInxe8K0KzhDJ95RgRuqmA"; stub(mockPlatform().preferenceStore().getAccessToken()).toReturn(accessToken); enqueueResponse("stormpath-user-profile-response.json"); Stormpath.getAccount(mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getPath()).isEqualTo("/me"); assertThat(request.getHeader("Authorization")).isEqualTo("Bearer " + accessToken); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); } @Test public void successfulFetchCallsSuccess() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); enqueueResponse("stormpath-user-profile-response.json");
StormpathCallback<Account> callback = mock(StormpathCallback.class);
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/UserProfileTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/Account.java // public class Account implements Serializable { // // @Json(name = "href") // private String href; // // @Json(name = "email") // private String email; // // @Json(name = "givenName") // private String givenName; // // @Json(name = "middleName") // private String middleName; // // @Json(name = "surname") // private String surname; // // @Json(name = "fullName") // private String fullName; // // @Json(name = "status") // private String status; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Object customData; // // public String getHref() { // return href; // } // // public String getEmail() { // return email; // } // // public String getGivenName() { // return givenName; // } // // public String getMiddleName() { // return middleName; // } // // public String getSurname() { // return surname; // } // // public String getFullName() { // return fullName; // } // // public String getStatus() { // return status; // } // // public String getUsername() { // return username; // } // // public Object getCustomData() { // return customData; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.Account; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify;
Stormpath.getAccount(callback); verify(callback).onSuccess(any(Account.class)); } @Test public void successfulFetchReturnsCorrectData() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); UserProfileCallback callback = new UserProfileCallback(); enqueueResponse("stormpath-user-profile-response.json"); Stormpath.getAccount(callback); assertThat(callback.account.getEmail()).isEqualTo("[email protected]"); assertThat(callback.account.getUsername()).isEqualTo("[email protected]"); assertThat(callback.account.getGivenName()).isEqualTo("John"); assertThat(callback.account.getMiddleName()).isNull(); assertThat(callback.account.getSurname()).isEqualTo("Deere"); assertThat(callback.account.getFullName()).isEqualTo("John Deere"); assertThat(callback.account.getStatus()).isEqualTo("ENABLED"); } @Test public void failedFetchCallsFailure() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Account> callback = mock(StormpathCallback.class); Stormpath.getAccount(callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/Account.java // public class Account implements Serializable { // // @Json(name = "href") // private String href; // // @Json(name = "email") // private String email; // // @Json(name = "givenName") // private String givenName; // // @Json(name = "middleName") // private String middleName; // // @Json(name = "surname") // private String surname; // // @Json(name = "fullName") // private String fullName; // // @Json(name = "status") // private String status; // // @Json(name = "username") // private String username; // // @Json(name = "customData") // private Object customData; // // public String getHref() { // return href; // } // // public String getEmail() { // return email; // } // // public String getGivenName() { // return givenName; // } // // public String getMiddleName() { // return middleName; // } // // public String getSurname() { // return surname; // } // // public String getFullName() { // return fullName; // } // // public String getStatus() { // return status; // } // // public String getUsername() { // return username; // } // // public Object getCustomData() { // return customData; // } // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/UserProfileTest.java import com.stormpath.sdk.models.Account; import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify; Stormpath.getAccount(callback); verify(callback).onSuccess(any(Account.class)); } @Test public void successfulFetchReturnsCorrectData() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); UserProfileCallback callback = new UserProfileCallback(); enqueueResponse("stormpath-user-profile-response.json"); Stormpath.getAccount(callback); assertThat(callback.account.getEmail()).isEqualTo("[email protected]"); assertThat(callback.account.getUsername()).isEqualTo("[email protected]"); assertThat(callback.account.getGivenName()).isEqualTo("John"); assertThat(callback.account.getMiddleName()).isNull(); assertThat(callback.account.getSurname()).isEqualTo("Deere"); assertThat(callback.account.getFullName()).isEqualTo("John Deere"); assertThat(callback.account.getStatus()).isEqualTo("ENABLED"); } @Test public void failedFetchCallsFailure() throws Exception { stub(mockPlatform().preferenceStore().getAccessToken()).toReturn("abcdefghijklmnopqrstuvwyxz0123456789"); enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Account> callback = mock(StormpathCallback.class); Stormpath.getAccount(callback);
verify(callback).onFailure(any(StormpathError.class));
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/ResetPasswordTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package com.stormpath.sdk; public class ResetPasswordTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); Stormpath.resetPassword("[email protected]", mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/forgot"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=utf-8"); assertThat(request.getBody().readUtf8()).isEqualTo("{\"email\":\"[email protected]\"}"); } @Test public void successfulResetCallsSuccess() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resetPassword("[email protected]", callback); verify(callback).onSuccess(null); } @Test public void failedResetCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resetPassword("[email protected]", callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/ResetPasswordTest.java import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package com.stormpath.sdk; public class ResetPasswordTest extends BaseTest { @Override public void setUp() throws Exception { super.setUp(); initWithDefaults(); } @Test public void correctRequest() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); Stormpath.resetPassword("[email protected]", mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/forgot"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=utf-8"); assertThat(request.getBody().readUtf8()).isEqualTo("{\"email\":\"[email protected]\"}"); } @Test public void successfulResetCallsSuccess() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resetPassword("[email protected]", callback); verify(callback).onSuccess(null); } @Test public void failedResetCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resetPassword("[email protected]", callback);
verify(callback).onFailure(any(StormpathError.class));
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/RefreshTokenTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.StormpathError; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.EOFException; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify;
verify(mockPlatform().preferenceStore()).setAccessToken("eyJraWQiOiI2WjA3NEJBQzhTM0tGWE5KOVhFTldEVUhGIiwiYWxnIjoiSFMyNTYifQ.eyJqdGk" + "iOiI1aW5La0tGNzhTeFg4T2cxbnRwbjZJIiwiaWF0IjoxNDU1NTI1MTg1LCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9" + "ucy8yUnJxS25UaW91M1F3Tm50RTN0Y0VHIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy81TXNRVEE0UVI5c0hZNnlRQlF" + "FSXlLIiwiZXhwIjoxNDU1NTI4Nzg1LCJydGkiOiI1MVcwc015Z0h3THQyVElsTFhKaGgwIn0.OUDaWC5xMyidkDX8FELAvvwDWk7-pWmUiUWQimPX3lA"); verify(mockPlatform().preferenceStore()).setRefreshToken( "eyJraWQiOiI2WjA3NEJBQzhTM0tGWE5KOVhFTldEVUhGIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiI1MVcwc015Z0h3THQyVElsTFhKaGgwIiwiaWF0IjoxNDU" + "1NTI1MTQ3LCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy8yUnJxS25UaW91M1F3Tm50RTN0Y0VHIiwic3V" + "iIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy81TXNRVEE0UVI5c0hZNnlRQlFFSXlLIiwiZXhwIjoxNDYwNzA5MTQ3fQ." + "g15poTJqau1nluVSCr0j-xnlqrQwySFOVX30mD_jw5A"); } @Test public void successfulRefreshCallsSuccess() throws Exception { stub(mockPlatform().preferenceStore().getRefreshToken()).toReturn("abcdefghijklmnopqrstuwyxz0123456789"); enqueueResponse("stormpath-refresh-token-response.json"); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.refreshAccessToken(callback); verify(callback).onSuccess(null); } @Test public void failedRefreshCallsFailure() throws Exception { stub(mockPlatform().preferenceStore().getRefreshToken()).toReturn("abcdefghijklmnopqrstuwyxz0123456789"); enqueueResponse("stormpath-refresh-token-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.refreshAccessToken(callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/RefreshTokenTest.java import com.stormpath.sdk.models.StormpathError; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.EOFException; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.stub; import static org.mockito.Mockito.verify; verify(mockPlatform().preferenceStore()).setAccessToken("eyJraWQiOiI2WjA3NEJBQzhTM0tGWE5KOVhFTldEVUhGIiwiYWxnIjoiSFMyNTYifQ.eyJqdGk" + "iOiI1aW5La0tGNzhTeFg4T2cxbnRwbjZJIiwiaWF0IjoxNDU1NTI1MTg1LCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9" + "ucy8yUnJxS25UaW91M1F3Tm50RTN0Y0VHIiwic3ViIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy81TXNRVEE0UVI5c0hZNnlRQlF" + "FSXlLIiwiZXhwIjoxNDU1NTI4Nzg1LCJydGkiOiI1MVcwc015Z0h3THQyVElsTFhKaGgwIn0.OUDaWC5xMyidkDX8FELAvvwDWk7-pWmUiUWQimPX3lA"); verify(mockPlatform().preferenceStore()).setRefreshToken( "eyJraWQiOiI2WjA3NEJBQzhTM0tGWE5KOVhFTldEVUhGIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiI1MVcwc015Z0h3THQyVElsTFhKaGgwIiwiaWF0IjoxNDU" + "1NTI1MTQ3LCJpc3MiOiJodHRwczovL2FwaS5zdG9ybXBhdGguY29tL3YxL2FwcGxpY2F0aW9ucy8yUnJxS25UaW91M1F3Tm50RTN0Y0VHIiwic3V" + "iIjoiaHR0cHM6Ly9hcGkuc3Rvcm1wYXRoLmNvbS92MS9hY2NvdW50cy81TXNRVEE0UVI5c0hZNnlRQlFFSXlLIiwiZXhwIjoxNDYwNzA5MTQ3fQ." + "g15poTJqau1nluVSCr0j-xnlqrQwySFOVX30mD_jw5A"); } @Test public void successfulRefreshCallsSuccess() throws Exception { stub(mockPlatform().preferenceStore().getRefreshToken()).toReturn("abcdefghijklmnopqrstuwyxz0123456789"); enqueueResponse("stormpath-refresh-token-response.json"); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.refreshAccessToken(callback); verify(callback).onSuccess(null); } @Test public void failedRefreshCallsFailure() throws Exception { stub(mockPlatform().preferenceStore().getRefreshToken()).toReturn("abcdefghijklmnopqrstuwyxz0123456789"); enqueueResponse("stormpath-refresh-token-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.refreshAccessToken(callback);
verify(callback).onFailure(any(StormpathError.class));
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/utils/StormpathTestCallback.java
// Path: sdk/src/main/java/com/stormpath/sdk/StormpathCallback.java // public interface StormpathCallback<T> { // // void onSuccess(T t); // // void onFailure(StormpathError error); // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.StormpathCallback; import com.stormpath.sdk.models.StormpathError;
package com.stormpath.sdk.utils; public class StormpathTestCallback<T> implements StormpathCallback<T> { public T response;
// Path: sdk/src/main/java/com/stormpath/sdk/StormpathCallback.java // public interface StormpathCallback<T> { // // void onSuccess(T t); // // void onFailure(StormpathError error); // } // // Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/utils/StormpathTestCallback.java import com.stormpath.sdk.StormpathCallback; import com.stormpath.sdk.models.StormpathError; package com.stormpath.sdk.utils; public class StormpathTestCallback<T> implements StormpathCallback<T> { public T response;
public StormpathError error;
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/ResendVerificationEmailTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // }
import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
public void correctRequest() throws Exception { String email = "[email protected]"; enqueueEmptyResponse(HttpURLConnection.HTTP_OK); Stormpath.resendVerificationEmail(email, mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/verify"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/x-www-form-urlencoded"); assertThat(request.getBody().readUtf8()).isEqualTo("login=john.deere%40example.com"); } @Test public void successfulResendCallsSuccess() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resendVerificationEmail("[email protected]", callback); verify(callback).onSuccess(null); } @Test public void failedResendCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resendVerificationEmail("[email protected]", callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/ResendVerificationEmailTest.java import com.stormpath.sdk.models.StormpathError; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public void correctRequest() throws Exception { String email = "[email protected]"; enqueueEmptyResponse(HttpURLConnection.HTTP_OK); Stormpath.resendVerificationEmail(email, mock(StormpathCallback.class)); RecordedRequest request = takeLastRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/verify"); assertThat(request.getHeader("Accept")).isEqualTo("application/json"); assertThat(request.getHeader("Content-Type")).isEqualTo("application/x-www-form-urlencoded"); assertThat(request.getBody().readUtf8()).isEqualTo("login=john.deere%40example.com"); } @Test public void successfulResendCallsSuccess() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resendVerificationEmail("[email protected]", callback); verify(callback).onSuccess(null); } @Test public void failedResendCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_BAD_REQUEST); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.resendVerificationEmail("[email protected]", callback);
verify(callback).onFailure(any(StormpathError.class));
stormpath/stormpath-sdk-android
sdk/src/test/java/com/stormpath/sdk/SocialLoginTest.java
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/StormpathTestCallback.java // public class StormpathTestCallback<T> implements StormpathCallback<T> { // // public T response; // // public StormpathError error; // // @Override // public void onSuccess(T t) { // this.response = t; // } // // @Override // public void onFailure(StormpathError error) { // this.error = error; // } // }
import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import com.stormpath.sdk.utils.StormpathTestCallback; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
@Test public void failedLoginCallsFailure() throws Exception { enqueueResponse("stormpath-login-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.loginWithProvider("facebook", "1234", callback); assertThat(callback.error.code()).isEqualTo(7100); assertThat(callback.error.status()).isEqualTo(400); assertThat(callback.error.developerMessage()).isEqualTo("Login attempt failed because the specified password is incorrect."); assertThat(callback.error.message()).isEqualTo("Invalid username or password."); assertThat(callback.error.moreInfo()).isEqualTo("http://docs.stormpath.com/errors/7100"); } @Test public void failedDeserializationCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.loginWithProvider("facebook", "1234", callback); assertThat(callback.error.message()).isEqualTo("There was an unexpected error, please try again later."); assertThat(callback.error.throwable()).isNotNull(); } @Test public void missingAccessTokenCallsFailure() throws Exception { enqueueStringResponse("{}"); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.loginWithProvider("facebook", "1234", callback);
// Path: sdk/src/main/java/com/stormpath/sdk/models/StormpathError.java // public class StormpathError implements Serializable { // // @Json(name = "status") // private int status; // // @Json(name = "message") // private String message; // // @Json(name = "code") // private int code; // // @Json(name = "developerMessage") // private String developerMessage; // // @Json(name = "moreInfo") // private String moreInfo; // // @Nullable // private transient Throwable throwable; // // /** // * Constructor for manually building an error when a local exception happens. // * // * @param message a user-friendly message // * @param throwable the exception we caught // */ // public StormpathError(String message, @NonNull Throwable throwable) { // this.throwable = throwable; // this.message = message; // this.developerMessage = throwable.getMessage(); // this.status = -1; // this.code = -1; // } // // public int status() { // return status; // } // // /** // * @return an end-user error message // */ // public String message() { // return message; // } // // public int code() { // return code; // } // // public String developerMessage() { // return developerMessage; // } // // public String moreInfo() { // return moreInfo; // } // // /** // * @return the throwable which caused the error, or null if the error was returned by the API // */ // @Nullable // public Throwable throwable() { // return throwable; // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/ResourceUtils.java // public class ResourceUtils { // // private static final String MOCK_DATA_DIRECTORY = "mockdata/%s"; // // private ResourceUtils() { // } // // /** // * Converts InputStream to String. // */ // public static String convertStreamToString(InputStream is) { // Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // } // // /** // * Reads a resource file to <code>String</code>. // */ // public static String readFromFile(String filename) { // InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(String.format(MOCK_DATA_DIRECTORY, filename)); // return convertStreamToString(is); // } // } // // Path: sdk/src/test/java/com/stormpath/sdk/utils/StormpathTestCallback.java // public class StormpathTestCallback<T> implements StormpathCallback<T> { // // public T response; // // public StormpathError error; // // @Override // public void onSuccess(T t) { // this.response = t; // } // // @Override // public void onFailure(StormpathError error) { // this.error = error; // } // } // Path: sdk/src/test/java/com/stormpath/sdk/SocialLoginTest.java import com.stormpath.sdk.models.StormpathError; import com.stormpath.sdk.utils.ResourceUtils; import com.stormpath.sdk.utils.StormpathTestCallback; import org.junit.Test; import java.net.HttpURLConnection; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @Test public void failedLoginCallsFailure() throws Exception { enqueueResponse("stormpath-login-400.json", HttpURLConnection.HTTP_BAD_REQUEST); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.loginWithProvider("facebook", "1234", callback); assertThat(callback.error.code()).isEqualTo(7100); assertThat(callback.error.status()).isEqualTo(400); assertThat(callback.error.developerMessage()).isEqualTo("Login attempt failed because the specified password is incorrect."); assertThat(callback.error.message()).isEqualTo("Invalid username or password."); assertThat(callback.error.moreInfo()).isEqualTo("http://docs.stormpath.com/errors/7100"); } @Test public void failedDeserializationCallsFailure() throws Exception { enqueueEmptyResponse(HttpURLConnection.HTTP_OK); StormpathTestCallback<Void> callback = new StormpathTestCallback<>(); Stormpath.loginWithProvider("facebook", "1234", callback); assertThat(callback.error.message()).isEqualTo("There was an unexpected error, please try again later."); assertThat(callback.error.throwable()).isNotNull(); } @Test public void missingAccessTokenCallsFailure() throws Exception { enqueueStringResponse("{}"); StormpathCallback<Void> callback = mock(StormpathCallback.class); Stormpath.loginWithProvider("facebook", "1234", callback);
verify(callback).onFailure(any(StormpathError.class));
mhjabreel/FDTKit
src/fdt/fuzzy/measures/SugenoLambdaMeasure.java
// Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // }
import fdt.core.DecisionSet; import java.util.Arrays;
package fdt.fuzzy.measures; /** * To compute the fuzzy measure value using the Sugeno Lambda Measure method. * @author Mohammed Jabreel */ public class SugenoLambdaMeasure extends FuzzyMeasureBase { private static final long serialVersionUID = -3475896576086728079L; @Override
// Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // Path: src/fdt/fuzzy/measures/SugenoLambdaMeasure.java import fdt.core.DecisionSet; import java.util.Arrays; package fdt.fuzzy.measures; /** * To compute the fuzzy measure value using the Sugeno Lambda Measure method. * @author Mohammed Jabreel */ public class SugenoLambdaMeasure extends FuzzyMeasureBase { private static final long serialVersionUID = -3475896576086728079L; @Override
protected double evaluate(double[] singletones, DecisionSet universeSet) {
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/SugenoIntegral.java
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // }
import fdt.fuzzy.measures.FuzzyMeasure;
package fdt.fuzzy.integrals; /** * * @author Mohammed Jabreel */ public class SugenoIntegral extends FuzzyIntegralBase { private static final long serialVersionUID = 1093651719134261601L; /** * * @param fuzzyMeasure */
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // Path: src/fdt/fuzzy/integrals/SugenoIntegral.java import fdt.fuzzy.measures.FuzzyMeasure; package fdt.fuzzy.integrals; /** * * @author Mohammed Jabreel */ public class SugenoIntegral extends FuzzyIntegralBase { private static final long serialVersionUID = 1093651719134261601L; /** * * @param fuzzyMeasure */
public SugenoIntegral(FuzzyMeasure fuzzyMeasure) {
mhjabreel/FDTKit
src/fdt/utils/Random.java
// Path: src/fdt/utils/Utils.java // public static void swap(int[] x, int i, int j) { // int s = x[i]; // x[i] = x[j]; // x[j] = s; // }
import static fdt.utils.Utils.swap; import java.util.stream.IntStream;
package fdt.utils; /** * * @author Mohammed Jabreel */ public class Random extends java.util.Random { /** * */ public Random() { } /** * * @param seed */ public Random(long seed) { super(seed); } /** * * @param n * @return */ public int[] getPermutation(int n) { int[] p = IntStream.range(0, n).toArray(); permutate(p); return p; } /** * * @param a */ public void permutate(int[] a) { for (int i = 0; i < a.length; i++) { int j = i + nextInt(a.length - i);
// Path: src/fdt/utils/Utils.java // public static void swap(int[] x, int i, int j) { // int s = x[i]; // x[i] = x[j]; // x[j] = s; // } // Path: src/fdt/utils/Random.java import static fdt.utils.Utils.swap; import java.util.stream.IntStream; package fdt.utils; /** * * @author Mohammed Jabreel */ public class Random extends java.util.Random { /** * */ public Random() { } /** * * @param seed */ public Random(long seed) { super(seed); } /** * * @param n * @return */ public int[] getPermutation(int n) { int[] p = IntStream.range(0, n).toArray(); permutate(p); return p; } /** * * @param a */ public void permutate(int[] a) { for (int i = 0; i < a.length; i++) { int j = i + nextInt(a.length - i);
swap(a, i, j);
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/DefaultFuzzyValue.java
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/Edge.java // public class Edge extends EdgeBase { // // private static final long serialVersionUID = 7620880090977147378L; // // /** // * // */ // protected double value; // // /** // * // */ // protected double accValue; // // /** // * // */ // public Edge() { // } // // /** // * // * @param text // */ // public Edge(String text) { // this.text = text; // } // // /** // * // * @return // */ // public double getValue() { // return value; // } // // /** // * // * @param value // */ // public void setValue(double value) { // this.value = value; // } // // /** // * // * @return // */ // public double getAccValue() { // return accValue; // } // // /** // * // * @param accValue // */ // public void setAccValue(double accValue) { // this.accValue = accValue; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("--[%s(%.3f)]-->", text, value); // } // // // }
import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.Edge;
package fdt.fuzzy.integrals; /** * * To compute the fuzzy value from the decision nodes. * @author Mohammed Jabreel */ public class DefaultFuzzyValue implements FuzzyValue { private static final long serialVersionUID = -5520176508323712873L; /** * The default fuzzy value is obtained by multiplying the classification * support by the fuzzy membership value. * * @param item * @return the fuzzy value. */ @Override
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/Edge.java // public class Edge extends EdgeBase { // // private static final long serialVersionUID = 7620880090977147378L; // // /** // * // */ // protected double value; // // /** // * // */ // protected double accValue; // // /** // * // */ // public Edge() { // } // // /** // * // * @param text // */ // public Edge(String text) { // this.text = text; // } // // /** // * // * @return // */ // public double getValue() { // return value; // } // // /** // * // * @param value // */ // public void setValue(double value) { // this.value = value; // } // // /** // * // * @return // */ // public double getAccValue() { // return accValue; // } // // /** // * // * @param accValue // */ // public void setAccValue(double accValue) { // this.accValue = accValue; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("--[%s(%.3f)]-->", text, value); // } // // // } // Path: src/fdt/fuzzy/integrals/DefaultFuzzyValue.java import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.Edge; package fdt.fuzzy.integrals; /** * * To compute the fuzzy value from the decision nodes. * @author Mohammed Jabreel */ public class DefaultFuzzyValue implements FuzzyValue { private static final long serialVersionUID = -5520176508323712873L; /** * The default fuzzy value is obtained by multiplying the classification * support by the fuzzy membership value. * * @param item * @return the fuzzy value. */ @Override
public double evaluate(DecisionNode item) {
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/DefaultFuzzyValue.java
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/Edge.java // public class Edge extends EdgeBase { // // private static final long serialVersionUID = 7620880090977147378L; // // /** // * // */ // protected double value; // // /** // * // */ // protected double accValue; // // /** // * // */ // public Edge() { // } // // /** // * // * @param text // */ // public Edge(String text) { // this.text = text; // } // // /** // * // * @return // */ // public double getValue() { // return value; // } // // /** // * // * @param value // */ // public void setValue(double value) { // this.value = value; // } // // /** // * // * @return // */ // public double getAccValue() { // return accValue; // } // // /** // * // * @param accValue // */ // public void setAccValue(double accValue) { // this.accValue = accValue; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("--[%s(%.3f)]-->", text, value); // } // // // }
import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.Edge;
package fdt.fuzzy.integrals; /** * * To compute the fuzzy value from the decision nodes. * @author Mohammed Jabreel */ public class DefaultFuzzyValue implements FuzzyValue { private static final long serialVersionUID = -5520176508323712873L; /** * The default fuzzy value is obtained by multiplying the classification * support by the fuzzy membership value. * * @param item * @return the fuzzy value. */ @Override public double evaluate(DecisionNode item) {
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/Edge.java // public class Edge extends EdgeBase { // // private static final long serialVersionUID = 7620880090977147378L; // // /** // * // */ // protected double value; // // /** // * // */ // protected double accValue; // // /** // * // */ // public Edge() { // } // // /** // * // * @param text // */ // public Edge(String text) { // this.text = text; // } // // /** // * // * @return // */ // public double getValue() { // return value; // } // // /** // * // * @param value // */ // public void setValue(double value) { // this.value = value; // } // // /** // * // * @return // */ // public double getAccValue() { // return accValue; // } // // /** // * // * @param accValue // */ // public void setAccValue(double accValue) { // this.accValue = accValue; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("--[%s(%.3f)]-->", text, value); // } // // // } // Path: src/fdt/fuzzy/integrals/DefaultFuzzyValue.java import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.Edge; package fdt.fuzzy.integrals; /** * * To compute the fuzzy value from the decision nodes. * @author Mohammed Jabreel */ public class DefaultFuzzyValue implements FuzzyValue { private static final long serialVersionUID = -5520176508323712873L; /** * The default fuzzy value is obtained by multiplying the classification * support by the fuzzy membership value. * * @param item * @return the fuzzy value. */ @Override public double evaluate(DecisionNode item) {
return item.getSupport() * ((Edge) item.getEdge()).getAccValue();
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/DefaultFuzzyValue.java
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/Edge.java // public class Edge extends EdgeBase { // // private static final long serialVersionUID = 7620880090977147378L; // // /** // * // */ // protected double value; // // /** // * // */ // protected double accValue; // // /** // * // */ // public Edge() { // } // // /** // * // * @param text // */ // public Edge(String text) { // this.text = text; // } // // /** // * // * @return // */ // public double getValue() { // return value; // } // // /** // * // * @param value // */ // public void setValue(double value) { // this.value = value; // } // // /** // * // * @return // */ // public double getAccValue() { // return accValue; // } // // /** // * // * @param accValue // */ // public void setAccValue(double accValue) { // this.accValue = accValue; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("--[%s(%.3f)]-->", text, value); // } // // // }
import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.Edge;
package fdt.fuzzy.integrals; /** * * To compute the fuzzy value from the decision nodes. * @author Mohammed Jabreel */ public class DefaultFuzzyValue implements FuzzyValue { private static final long serialVersionUID = -5520176508323712873L; /** * The default fuzzy value is obtained by multiplying the classification * support by the fuzzy membership value. * * @param item * @return the fuzzy value. */ @Override public double evaluate(DecisionNode item) { return item.getSupport() * ((Edge) item.getEdge()).getAccValue(); } /** * To get the fuzzy value from the decision node given the decision set in which that node is a member of. * @param item * @param universeSet * @return */ @Override
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/Edge.java // public class Edge extends EdgeBase { // // private static final long serialVersionUID = 7620880090977147378L; // // /** // * // */ // protected double value; // // /** // * // */ // protected double accValue; // // /** // * // */ // public Edge() { // } // // /** // * // * @param text // */ // public Edge(String text) { // this.text = text; // } // // /** // * // * @return // */ // public double getValue() { // return value; // } // // /** // * // * @param value // */ // public void setValue(double value) { // this.value = value; // } // // /** // * // * @return // */ // public double getAccValue() { // return accValue; // } // // /** // * // * @param accValue // */ // public void setAccValue(double accValue) { // this.accValue = accValue; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("--[%s(%.3f)]-->", text, value); // } // // // } // Path: src/fdt/fuzzy/integrals/DefaultFuzzyValue.java import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.Edge; package fdt.fuzzy.integrals; /** * * To compute the fuzzy value from the decision nodes. * @author Mohammed Jabreel */ public class DefaultFuzzyValue implements FuzzyValue { private static final long serialVersionUID = -5520176508323712873L; /** * The default fuzzy value is obtained by multiplying the classification * support by the fuzzy membership value. * * @param item * @return the fuzzy value. */ @Override public double evaluate(DecisionNode item) { return item.getSupport() * ((Edge) item.getEdge()).getAccValue(); } /** * To get the fuzzy value from the decision node given the decision set in which that node is a member of. * @param item * @param universeSet * @return */ @Override
public double evaluate(DecisionNode item, DecisionSet universeSet) {
mhjabreel/FDTKit
src/fdt/fuzzy/measures/FuzzyMeasureBase.java
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/IntermediateNode.java // public class IntermediateNode extends IntermediateNodeBase { // // private static final long serialVersionUID = -1668837612685717472L; // // // private final HashMap<String, Double> classesLambdas = new HashMap<>(); // // private Nullable<Double> lambda = Nullable.empty(); // // /** // * // * @return // */ // public double getLambda() { // return lambda.orElse(0.0); // } // // /** // * // * @param lambda // */ // public void setLambda(double lambda) { // this.lambda = Nullable.of(lambda); // } // // /** // * // * @param className // * @return // */ // public boolean hasLambda(String className) { // return this.classesLambdas.containsKey(className); // } // // /** // * // * @return // */ // public boolean hasLambda() { // return lambda.isPresent(); // } // // /** // * // * @param className // * @return // */ // public double getLambda(String className) { // return this.classesLambdas.get(className); // } // // /** // * // * @param className // * @param lambda // */ // public void setLambda(String className, double lambda) { // this.classesLambdas.put(className, lambda); // } // // }
import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.IntermediateNode; import java.util.List;
package fdt.fuzzy.measures; /** * * A base class for the fuzzy measure methods. * * @author Mohammed Jabreel */ public abstract class FuzzyMeasureBase implements FuzzyMeasure { private static final long serialVersionUID = 692379574106832903L; @Override
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/IntermediateNode.java // public class IntermediateNode extends IntermediateNodeBase { // // private static final long serialVersionUID = -1668837612685717472L; // // // private final HashMap<String, Double> classesLambdas = new HashMap<>(); // // private Nullable<Double> lambda = Nullable.empty(); // // /** // * // * @return // */ // public double getLambda() { // return lambda.orElse(0.0); // } // // /** // * // * @param lambda // */ // public void setLambda(double lambda) { // this.lambda = Nullable.of(lambda); // } // // /** // * // * @param className // * @return // */ // public boolean hasLambda(String className) { // return this.classesLambdas.containsKey(className); // } // // /** // * // * @return // */ // public boolean hasLambda() { // return lambda.isPresent(); // } // // /** // * // * @param className // * @return // */ // public double getLambda(String className) { // return this.classesLambdas.get(className); // } // // /** // * // * @param className // * @param lambda // */ // public void setLambda(String className, double lambda) { // this.classesLambdas.put(className, lambda); // } // // } // Path: src/fdt/fuzzy/measures/FuzzyMeasureBase.java import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.IntermediateNode; import java.util.List; package fdt.fuzzy.measures; /** * * A base class for the fuzzy measure methods. * * @author Mohammed Jabreel */ public abstract class FuzzyMeasureBase implements FuzzyMeasure { private static final long serialVersionUID = 692379574106832903L; @Override
public double evaluate(List<DecisionNode> subset, DecisionSet universeSet) {
mhjabreel/FDTKit
src/fdt/fuzzy/measures/FuzzyMeasureBase.java
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/IntermediateNode.java // public class IntermediateNode extends IntermediateNodeBase { // // private static final long serialVersionUID = -1668837612685717472L; // // // private final HashMap<String, Double> classesLambdas = new HashMap<>(); // // private Nullable<Double> lambda = Nullable.empty(); // // /** // * // * @return // */ // public double getLambda() { // return lambda.orElse(0.0); // } // // /** // * // * @param lambda // */ // public void setLambda(double lambda) { // this.lambda = Nullable.of(lambda); // } // // /** // * // * @param className // * @return // */ // public boolean hasLambda(String className) { // return this.classesLambdas.containsKey(className); // } // // /** // * // * @return // */ // public boolean hasLambda() { // return lambda.isPresent(); // } // // /** // * // * @param className // * @return // */ // public double getLambda(String className) { // return this.classesLambdas.get(className); // } // // /** // * // * @param className // * @param lambda // */ // public void setLambda(String className, double lambda) { // this.classesLambdas.put(className, lambda); // } // // }
import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.IntermediateNode; import java.util.List;
package fdt.fuzzy.measures; /** * * A base class for the fuzzy measure methods. * * @author Mohammed Jabreel */ public abstract class FuzzyMeasureBase implements FuzzyMeasure { private static final long serialVersionUID = 692379574106832903L; @Override
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/core/IntermediateNode.java // public class IntermediateNode extends IntermediateNodeBase { // // private static final long serialVersionUID = -1668837612685717472L; // // // private final HashMap<String, Double> classesLambdas = new HashMap<>(); // // private Nullable<Double> lambda = Nullable.empty(); // // /** // * // * @return // */ // public double getLambda() { // return lambda.orElse(0.0); // } // // /** // * // * @param lambda // */ // public void setLambda(double lambda) { // this.lambda = Nullable.of(lambda); // } // // /** // * // * @param className // * @return // */ // public boolean hasLambda(String className) { // return this.classesLambdas.containsKey(className); // } // // /** // * // * @return // */ // public boolean hasLambda() { // return lambda.isPresent(); // } // // /** // * // * @param className // * @return // */ // public double getLambda(String className) { // return this.classesLambdas.get(className); // } // // /** // * // * @param className // * @param lambda // */ // public void setLambda(String className, double lambda) { // this.classesLambdas.put(className, lambda); // } // // } // Path: src/fdt/fuzzy/measures/FuzzyMeasureBase.java import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.core.IntermediateNode; import java.util.List; package fdt.fuzzy.measures; /** * * A base class for the fuzzy measure methods. * * @author Mohammed Jabreel */ public abstract class FuzzyMeasureBase implements FuzzyMeasure { private static final long serialVersionUID = 692379574106832903L; @Override
public double evaluate(List<DecisionNode> subset, DecisionSet universeSet) {
mhjabreel/FDTKit
src/fdt/fuzzy/measures/DistortedProbabilitiesMeasure.java
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // }
import fdt.core.DecisionNode; import fdt.core.DecisionSet;
package fdt.fuzzy.measures; /** * * To compute the fuzzy measure value using the Distorted Probability method. * * * @author Mohammed Jabreel */ public class DistortedProbabilitiesMeasure extends FuzzyMeasureBase { private static final long serialVersionUID = 5248213971134859082L; /** * */ protected double tau; /** * */ public DistortedProbabilitiesMeasure() { this(1); } /** * * @param tau */ public DistortedProbabilitiesMeasure(double tau) { this.tau = tau; } @Override
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // Path: src/fdt/fuzzy/measures/DistortedProbabilitiesMeasure.java import fdt.core.DecisionNode; import fdt.core.DecisionSet; package fdt.fuzzy.measures; /** * * To compute the fuzzy measure value using the Distorted Probability method. * * * @author Mohammed Jabreel */ public class DistortedProbabilitiesMeasure extends FuzzyMeasureBase { private static final long serialVersionUID = 5248213971134859082L; /** * */ protected double tau; /** * */ public DistortedProbabilitiesMeasure() { this(1); } /** * * @param tau */ public DistortedProbabilitiesMeasure(double tau) { this.tau = tau; } @Override
protected double evaluate(double[] singletones, DecisionSet universeSet) {
mhjabreel/FDTKit
src/fdt/data/Term.java
// Path: src/fdt/fuzzy/FuzzySet.java // public interface FuzzySet { // // /** // * // * @param x // * @return // */ // double getMembership(double x); // } // // Path: src/fdt/fuzzy/IdentityFuzzySet.java // public class IdentityFuzzySet implements FuzzySet { // // /** // * // * @param x // * @return // */ // @Override // public double getMembership(double x) { // return x; // } // // }
import fdt.fuzzy.FuzzySet; import fdt.fuzzy.IdentityFuzzySet; import java.util.ArrayList; import java.util.List; import java.util.Objects;
package fdt.data; /** * * To represent a linguistic term, e.g. Old. * * @author Mohammed Jabreel */ public class Term { /** * The list of the fuzzy values. */ private final List<Double> storage = new ArrayList<>(); /** * The term name. */ private final String name; /** * The fuzzy set of the term that will be used to convert the crisp value into a fuzzy membership value. */
// Path: src/fdt/fuzzy/FuzzySet.java // public interface FuzzySet { // // /** // * // * @param x // * @return // */ // double getMembership(double x); // } // // Path: src/fdt/fuzzy/IdentityFuzzySet.java // public class IdentityFuzzySet implements FuzzySet { // // /** // * // * @param x // * @return // */ // @Override // public double getMembership(double x) { // return x; // } // // } // Path: src/fdt/data/Term.java import fdt.fuzzy.FuzzySet; import fdt.fuzzy.IdentityFuzzySet; import java.util.ArrayList; import java.util.List; import java.util.Objects; package fdt.data; /** * * To represent a linguistic term, e.g. Old. * * @author Mohammed Jabreel */ public class Term { /** * The list of the fuzzy values. */ private final List<Double> storage = new ArrayList<>(); /** * The term name. */ private final String name; /** * The fuzzy set of the term that will be used to convert the crisp value into a fuzzy membership value. */
private FuzzySet fuzzySet = new IdentityFuzzySet();
mhjabreel/FDTKit
src/fdt/data/Term.java
// Path: src/fdt/fuzzy/FuzzySet.java // public interface FuzzySet { // // /** // * // * @param x // * @return // */ // double getMembership(double x); // } // // Path: src/fdt/fuzzy/IdentityFuzzySet.java // public class IdentityFuzzySet implements FuzzySet { // // /** // * // * @param x // * @return // */ // @Override // public double getMembership(double x) { // return x; // } // // }
import fdt.fuzzy.FuzzySet; import fdt.fuzzy.IdentityFuzzySet; import java.util.ArrayList; import java.util.List; import java.util.Objects;
package fdt.data; /** * * To represent a linguistic term, e.g. Old. * * @author Mohammed Jabreel */ public class Term { /** * The list of the fuzzy values. */ private final List<Double> storage = new ArrayList<>(); /** * The term name. */ private final String name; /** * The fuzzy set of the term that will be used to convert the crisp value into a fuzzy membership value. */
// Path: src/fdt/fuzzy/FuzzySet.java // public interface FuzzySet { // // /** // * // * @param x // * @return // */ // double getMembership(double x); // } // // Path: src/fdt/fuzzy/IdentityFuzzySet.java // public class IdentityFuzzySet implements FuzzySet { // // /** // * // * @param x // * @return // */ // @Override // public double getMembership(double x) { // return x; // } // // } // Path: src/fdt/data/Term.java import fdt.fuzzy.FuzzySet; import fdt.fuzzy.IdentityFuzzySet; import java.util.ArrayList; import java.util.List; import java.util.Objects; package fdt.data; /** * * To represent a linguistic term, e.g. Old. * * @author Mohammed Jabreel */ public class Term { /** * The list of the fuzzy values. */ private final List<Double> storage = new ArrayList<>(); /** * The term name. */ private final String name; /** * The fuzzy set of the term that will be used to convert the crisp value into a fuzzy membership value. */
private FuzzySet fuzzySet = new IdentityFuzzySet();
mhjabreel/FDTKit
src/fdt/infer/IntegralBasedVotingStrategy.java
// Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/fuzzy/integrals/FuzzyIntegral.java // public interface FuzzyIntegral extends Serializable { // // /** // * Given a decision set, get the aggregated value of the values of // * decision nodes (based on @FuzzyValue and @FuzzyMeasure methods). // * // * @param set // * @return // */ // double evaluate(DecisionSet set); // }
import fdt.core.DecisionSet; import fdt.fuzzy.integrals.FuzzyIntegral; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
package fdt.infer; /** * * Fuzzy Integral-based voting strategy. * We get the prediction from the set of the rules in a FDT in this voting * strategy by aggregating these decisions using a fuzzy integral method. * * @author Mohammed Jabreel */ public class IntegralBasedVotingStrategy extends DefaultVotingStrategy { private static final long serialVersionUID = -8771986175920175509L; /** * */
// Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/fuzzy/integrals/FuzzyIntegral.java // public interface FuzzyIntegral extends Serializable { // // /** // * Given a decision set, get the aggregated value of the values of // * decision nodes (based on @FuzzyValue and @FuzzyMeasure methods). // * // * @param set // * @return // */ // double evaluate(DecisionSet set); // } // Path: src/fdt/infer/IntegralBasedVotingStrategy.java import fdt.core.DecisionSet; import fdt.fuzzy.integrals.FuzzyIntegral; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; package fdt.infer; /** * * Fuzzy Integral-based voting strategy. * We get the prediction from the set of the rules in a FDT in this voting * strategy by aggregating these decisions using a fuzzy integral method. * * @author Mohammed Jabreel */ public class IntegralBasedVotingStrategy extends DefaultVotingStrategy { private static final long serialVersionUID = -8771986175920175509L; /** * */
protected FuzzyIntegral fuzzyIntegral;
mhjabreel/FDTKit
src/fdt/infer/IntegralBasedVotingStrategy.java
// Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/fuzzy/integrals/FuzzyIntegral.java // public interface FuzzyIntegral extends Serializable { // // /** // * Given a decision set, get the aggregated value of the values of // * decision nodes (based on @FuzzyValue and @FuzzyMeasure methods). // * // * @param set // * @return // */ // double evaluate(DecisionSet set); // }
import fdt.core.DecisionSet; import fdt.fuzzy.integrals.FuzzyIntegral; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
package fdt.infer; /** * * Fuzzy Integral-based voting strategy. * We get the prediction from the set of the rules in a FDT in this voting * strategy by aggregating these decisions using a fuzzy integral method. * * @author Mohammed Jabreel */ public class IntegralBasedVotingStrategy extends DefaultVotingStrategy { private static final long serialVersionUID = -8771986175920175509L; /** * */ protected FuzzyIntegral fuzzyIntegral; /** * */ protected double delta = 0; /** * * @param fuzzyIntegral */ public IntegralBasedVotingStrategy(FuzzyIntegral fuzzyIntegral) { this.fuzzyIntegral = fuzzyIntegral; } /** * */ public IntegralBasedVotingStrategy() { } /** * * @param fuzzyIntegral * @param aggregationType */ public IntegralBasedVotingStrategy(FuzzyIntegral fuzzyIntegral, AggregationType aggregationType) { super(aggregationType); this.fuzzyIntegral = fuzzyIntegral; } /** * * @param decisionSets * @return */ @Override
// Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/fuzzy/integrals/FuzzyIntegral.java // public interface FuzzyIntegral extends Serializable { // // /** // * Given a decision set, get the aggregated value of the values of // * decision nodes (based on @FuzzyValue and @FuzzyMeasure methods). // * // * @param set // * @return // */ // double evaluate(DecisionSet set); // } // Path: src/fdt/infer/IntegralBasedVotingStrategy.java import fdt.core.DecisionSet; import fdt.fuzzy.integrals.FuzzyIntegral; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; package fdt.infer; /** * * Fuzzy Integral-based voting strategy. * We get the prediction from the set of the rules in a FDT in this voting * strategy by aggregating these decisions using a fuzzy integral method. * * @author Mohammed Jabreel */ public class IntegralBasedVotingStrategy extends DefaultVotingStrategy { private static final long serialVersionUID = -8771986175920175509L; /** * */ protected FuzzyIntegral fuzzyIntegral; /** * */ protected double delta = 0; /** * * @param fuzzyIntegral */ public IntegralBasedVotingStrategy(FuzzyIntegral fuzzyIntegral) { this.fuzzyIntegral = fuzzyIntegral; } /** * */ public IntegralBasedVotingStrategy() { } /** * * @param fuzzyIntegral * @param aggregationType */ public IntegralBasedVotingStrategy(FuzzyIntegral fuzzyIntegral, AggregationType aggregationType) { super(aggregationType); this.fuzzyIntegral = fuzzyIntegral; } /** * * @param decisionSets * @return */ @Override
public PredictionResult vote(List<DecisionSet> decisionSets) {
mhjabreel/FDTKit
src/fdt/data/Attribute.java
// Path: src/fdt/fuzzy/FuzzySet.java // public interface FuzzySet { // // /** // * // * @param x // * @return // */ // double getMembership(double x); // }
import fdt.fuzzy.FuzzySet; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.stream.Collectors;
package fdt.data; /** * * To create a fuzzy variable, e.g. Age. * * @author Mohammed Jabreel */ public class Attribute { /** * The name of the attribute. */ private final String name; /** * The index of the attribute in the dataset. */ int index; /** * The dictionary of the terms. */ private final HashMap<String, Term> nameToTerm = new LinkedHashMap<>(); /** * The list of the crisp values. */ private final List<Double> crispValues = new ArrayList<>(); /** * The list of the terms of the attribute. */ private final List<Term> terms = new ArrayList<>(); /** * * @param name */ public Attribute(String name) { this.name = name; } /** * * @return */ public String getName() { return name; } /** * * @param termName * @param fuzzySet */
// Path: src/fdt/fuzzy/FuzzySet.java // public interface FuzzySet { // // /** // * // * @param x // * @return // */ // double getMembership(double x); // } // Path: src/fdt/data/Attribute.java import fdt.fuzzy.FuzzySet; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.stream.Collectors; package fdt.data; /** * * To create a fuzzy variable, e.g. Age. * * @author Mohammed Jabreel */ public class Attribute { /** * The name of the attribute. */ private final String name; /** * The index of the attribute in the dataset. */ int index; /** * The dictionary of the terms. */ private final HashMap<String, Term> nameToTerm = new LinkedHashMap<>(); /** * The list of the crisp values. */ private final List<Double> crispValues = new ArrayList<>(); /** * The list of the terms of the attribute. */ private final List<Term> terms = new ArrayList<>(); /** * * @param name */ public Attribute(String name) { this.name = name; } /** * * @return */ public String getName() { return name; } /** * * @param termName * @param fuzzySet */
public void addTerm(String termName, FuzzySet fuzzySet) {
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/FuzzyIntegralBase.java
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // // Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/utils/Sorter.java // public class Sorter<T> { // // /** // * // * @param target // * @param source // * @return // */ // public List<T> sortBy(List<T> target, double[] source) { // // Tuple<Integer, Double>[] map = new Tuple[source.length]; // for (int i = 0; i < source.length; i++) { // map[i] = new Tuple<>(i, source[i]); // } // // Arrays.sort(map, (a, b) -> a.getSecond().compareTo(b.getSecond())); // // List<T> sortedTarget = new ArrayList<>(); // // for (int i = 0; i < target.size(); i++) { // sortedTarget.add(target.get(map[i].getFirst())); // } // // return sortedTarget; // } // }
import fdt.fuzzy.measures.FuzzyMeasure; import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.utils.Sorter; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package fdt.fuzzy.integrals; /** * * An abstract class for the fuzzy integral methods. * Each fuzzy integral needs a fuzzy measure method and a fuzzy value method. * * @author Mohammed Jabreel */ public abstract class FuzzyIntegralBase implements FuzzyIntegral { private static final long serialVersionUID = 3931734251442980554L; /** * The fuzzy measure method. */
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // // Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/utils/Sorter.java // public class Sorter<T> { // // /** // * // * @param target // * @param source // * @return // */ // public List<T> sortBy(List<T> target, double[] source) { // // Tuple<Integer, Double>[] map = new Tuple[source.length]; // for (int i = 0; i < source.length; i++) { // map[i] = new Tuple<>(i, source[i]); // } // // Arrays.sort(map, (a, b) -> a.getSecond().compareTo(b.getSecond())); // // List<T> sortedTarget = new ArrayList<>(); // // for (int i = 0; i < target.size(); i++) { // sortedTarget.add(target.get(map[i].getFirst())); // } // // return sortedTarget; // } // } // Path: src/fdt/fuzzy/integrals/FuzzyIntegralBase.java import fdt.fuzzy.measures.FuzzyMeasure; import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.utils.Sorter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package fdt.fuzzy.integrals; /** * * An abstract class for the fuzzy integral methods. * Each fuzzy integral needs a fuzzy measure method and a fuzzy value method. * * @author Mohammed Jabreel */ public abstract class FuzzyIntegralBase implements FuzzyIntegral { private static final long serialVersionUID = 3931734251442980554L; /** * The fuzzy measure method. */
protected FuzzyMeasure fuzzyMeasure;
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/FuzzyIntegralBase.java
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // // Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/utils/Sorter.java // public class Sorter<T> { // // /** // * // * @param target // * @param source // * @return // */ // public List<T> sortBy(List<T> target, double[] source) { // // Tuple<Integer, Double>[] map = new Tuple[source.length]; // for (int i = 0; i < source.length; i++) { // map[i] = new Tuple<>(i, source[i]); // } // // Arrays.sort(map, (a, b) -> a.getSecond().compareTo(b.getSecond())); // // List<T> sortedTarget = new ArrayList<>(); // // for (int i = 0; i < target.size(); i++) { // sortedTarget.add(target.get(map[i].getFirst())); // } // // return sortedTarget; // } // }
import fdt.fuzzy.measures.FuzzyMeasure; import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.utils.Sorter; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package fdt.fuzzy.integrals; /** * * An abstract class for the fuzzy integral methods. * Each fuzzy integral needs a fuzzy measure method and a fuzzy value method. * * @author Mohammed Jabreel */ public abstract class FuzzyIntegralBase implements FuzzyIntegral { private static final long serialVersionUID = 3931734251442980554L; /** * The fuzzy measure method. */ protected FuzzyMeasure fuzzyMeasure; /** * The fuzzy value method. The default is @DefaultFuzzyValue. */ protected FuzzyValue fuzzyValue; /** * Constructor to set the fuzzy measure that will be used in this integral. * @param fuzzyMeasure */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure) { this(fuzzyMeasure, new DefaultFuzzyValue()); } /** * Constructor to set the fuzzy measure and the fuzzy value that will be used in this integral. * @param fuzzyMeasure * @param fuzzyValue */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure, FuzzyValue fuzzyValue) { this.fuzzyMeasure = fuzzyMeasure; this.fuzzyValue = fuzzyValue; } /** * Implementation of the abstract evaluate method. * @param set * @return */ @Override
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // // Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/utils/Sorter.java // public class Sorter<T> { // // /** // * // * @param target // * @param source // * @return // */ // public List<T> sortBy(List<T> target, double[] source) { // // Tuple<Integer, Double>[] map = new Tuple[source.length]; // for (int i = 0; i < source.length; i++) { // map[i] = new Tuple<>(i, source[i]); // } // // Arrays.sort(map, (a, b) -> a.getSecond().compareTo(b.getSecond())); // // List<T> sortedTarget = new ArrayList<>(); // // for (int i = 0; i < target.size(); i++) { // sortedTarget.add(target.get(map[i].getFirst())); // } // // return sortedTarget; // } // } // Path: src/fdt/fuzzy/integrals/FuzzyIntegralBase.java import fdt.fuzzy.measures.FuzzyMeasure; import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.utils.Sorter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package fdt.fuzzy.integrals; /** * * An abstract class for the fuzzy integral methods. * Each fuzzy integral needs a fuzzy measure method and a fuzzy value method. * * @author Mohammed Jabreel */ public abstract class FuzzyIntegralBase implements FuzzyIntegral { private static final long serialVersionUID = 3931734251442980554L; /** * The fuzzy measure method. */ protected FuzzyMeasure fuzzyMeasure; /** * The fuzzy value method. The default is @DefaultFuzzyValue. */ protected FuzzyValue fuzzyValue; /** * Constructor to set the fuzzy measure that will be used in this integral. * @param fuzzyMeasure */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure) { this(fuzzyMeasure, new DefaultFuzzyValue()); } /** * Constructor to set the fuzzy measure and the fuzzy value that will be used in this integral. * @param fuzzyMeasure * @param fuzzyValue */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure, FuzzyValue fuzzyValue) { this.fuzzyMeasure = fuzzyMeasure; this.fuzzyValue = fuzzyValue; } /** * Implementation of the abstract evaluate method. * @param set * @return */ @Override
public double evaluate(DecisionSet set) {
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/FuzzyIntegralBase.java
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // // Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/utils/Sorter.java // public class Sorter<T> { // // /** // * // * @param target // * @param source // * @return // */ // public List<T> sortBy(List<T> target, double[] source) { // // Tuple<Integer, Double>[] map = new Tuple[source.length]; // for (int i = 0; i < source.length; i++) { // map[i] = new Tuple<>(i, source[i]); // } // // Arrays.sort(map, (a, b) -> a.getSecond().compareTo(b.getSecond())); // // List<T> sortedTarget = new ArrayList<>(); // // for (int i = 0; i < target.size(); i++) { // sortedTarget.add(target.get(map[i].getFirst())); // } // // return sortedTarget; // } // }
import fdt.fuzzy.measures.FuzzyMeasure; import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.utils.Sorter; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package fdt.fuzzy.integrals; /** * * An abstract class for the fuzzy integral methods. * Each fuzzy integral needs a fuzzy measure method and a fuzzy value method. * * @author Mohammed Jabreel */ public abstract class FuzzyIntegralBase implements FuzzyIntegral { private static final long serialVersionUID = 3931734251442980554L; /** * The fuzzy measure method. */ protected FuzzyMeasure fuzzyMeasure; /** * The fuzzy value method. The default is @DefaultFuzzyValue. */ protected FuzzyValue fuzzyValue; /** * Constructor to set the fuzzy measure that will be used in this integral. * @param fuzzyMeasure */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure) { this(fuzzyMeasure, new DefaultFuzzyValue()); } /** * Constructor to set the fuzzy measure and the fuzzy value that will be used in this integral. * @param fuzzyMeasure * @param fuzzyValue */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure, FuzzyValue fuzzyValue) { this.fuzzyMeasure = fuzzyMeasure; this.fuzzyValue = fuzzyValue; } /** * Implementation of the abstract evaluate method. * @param set * @return */ @Override public double evaluate(DecisionSet set) {
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // // Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // // Path: src/fdt/utils/Sorter.java // public class Sorter<T> { // // /** // * // * @param target // * @param source // * @return // */ // public List<T> sortBy(List<T> target, double[] source) { // // Tuple<Integer, Double>[] map = new Tuple[source.length]; // for (int i = 0; i < source.length; i++) { // map[i] = new Tuple<>(i, source[i]); // } // // Arrays.sort(map, (a, b) -> a.getSecond().compareTo(b.getSecond())); // // List<T> sortedTarget = new ArrayList<>(); // // for (int i = 0; i < target.size(); i++) { // sortedTarget.add(target.get(map[i].getFirst())); // } // // return sortedTarget; // } // } // Path: src/fdt/fuzzy/integrals/FuzzyIntegralBase.java import fdt.fuzzy.measures.FuzzyMeasure; import fdt.core.DecisionNode; import fdt.core.DecisionSet; import fdt.utils.Sorter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package fdt.fuzzy.integrals; /** * * An abstract class for the fuzzy integral methods. * Each fuzzy integral needs a fuzzy measure method and a fuzzy value method. * * @author Mohammed Jabreel */ public abstract class FuzzyIntegralBase implements FuzzyIntegral { private static final long serialVersionUID = 3931734251442980554L; /** * The fuzzy measure method. */ protected FuzzyMeasure fuzzyMeasure; /** * The fuzzy value method. The default is @DefaultFuzzyValue. */ protected FuzzyValue fuzzyValue; /** * Constructor to set the fuzzy measure that will be used in this integral. * @param fuzzyMeasure */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure) { this(fuzzyMeasure, new DefaultFuzzyValue()); } /** * Constructor to set the fuzzy measure and the fuzzy value that will be used in this integral. * @param fuzzyMeasure * @param fuzzyValue */ public FuzzyIntegralBase(FuzzyMeasure fuzzyMeasure, FuzzyValue fuzzyValue) { this.fuzzyMeasure = fuzzyMeasure; this.fuzzyValue = fuzzyValue; } /** * Implementation of the abstract evaluate method. * @param set * @return */ @Override public double evaluate(DecisionSet set) {
List<DecisionNode> filteredNodes = new ArrayList<>();
mhjabreel/FDTKit
src/fdt/fuzzy/TrapezoidalFuzzySet.java
// Path: src/fdt/utils/Tuple.java // public class Tuple<T1, T2> { // private T1 first; // private T2 second; // // /** // * // */ // public Tuple() { // } // // /** // * // * @param first // * @param second // */ // public Tuple(T1 first, T2 second) { // this.first = first; // this.second = second; // } // // /** // * // * @return // */ // public T1 getFirst() { // return first; // } // // /** // * // * @return // */ // public T2 getSecond() { // return second; // } // // /** // * // * @param first // */ // public void setFirst(T1 first) { // this.first = first; // } // // /** // * // * @param second // */ // public void setSecond(T2 second) { // this.second = second; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("(%s, %s)", first, second); // } // // // }
import fdt.utils.Tuple;
package fdt.fuzzy; /** * * @author Mohammed Jabreel * */ public class TrapezoidalFuzzySet extends PiecewiseLinearFunction { /** * * @param size */ public TrapezoidalFuzzySet(int size) {
// Path: src/fdt/utils/Tuple.java // public class Tuple<T1, T2> { // private T1 first; // private T2 second; // // /** // * // */ // public Tuple() { // } // // /** // * // * @param first // * @param second // */ // public Tuple(T1 first, T2 second) { // this.first = first; // this.second = second; // } // // /** // * // * @return // */ // public T1 getFirst() { // return first; // } // // /** // * // * @return // */ // public T2 getSecond() { // return second; // } // // /** // * // * @param first // */ // public void setFirst(T1 first) { // this.first = first; // } // // /** // * // * @param second // */ // public void setSecond(T2 second) { // this.second = second; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("(%s, %s)", first, second); // } // // // } // Path: src/fdt/fuzzy/TrapezoidalFuzzySet.java import fdt.utils.Tuple; package fdt.fuzzy; /** * * @author Mohammed Jabreel * */ public class TrapezoidalFuzzySet extends PiecewiseLinearFunction { /** * * @param size */ public TrapezoidalFuzzySet(int size) {
this.points = new Tuple[size];
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/ChoquetIntegral.java
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // }
import fdt.fuzzy.measures.FuzzyMeasure;
package fdt.fuzzy.integrals; /** * * @author Mohammed Jabreel */ public class ChoquetIntegral extends FuzzyIntegralBase { private static final long serialVersionUID = -6984666774235620648L; /** * * @param fuzzyMeasure */
// Path: src/fdt/fuzzy/measures/FuzzyMeasure.java // public interface FuzzyMeasure extends Serializable { // // /** // * To calculate the fuzzy measure of a decision nodes S_i that is a subset of S. // * @param subset S_i // * @param universeSet S // * @return the fuzzy measure value. // */ // double evaluate(List<DecisionNode> subset, DecisionSet universeSet); // // } // Path: src/fdt/fuzzy/integrals/ChoquetIntegral.java import fdt.fuzzy.measures.FuzzyMeasure; package fdt.fuzzy.integrals; /** * * @author Mohammed Jabreel */ public class ChoquetIntegral extends FuzzyIntegralBase { private static final long serialVersionUID = -6984666774235620648L; /** * * @param fuzzyMeasure */
public ChoquetIntegral(FuzzyMeasure fuzzyMeasure) {
mhjabreel/FDTKit
src/fdt/fuzzy/integrals/FuzzyValue.java
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // }
import fdt.core.DecisionNode; import fdt.core.DecisionSet; import java.io.Serializable;
package fdt.fuzzy.integrals; /** * * An interface to compute the fuzzy value from a decision node. * @see DefaultFuzzyValue * @author Mohammed Jabreel */ public interface FuzzyValue extends Serializable { /** * To get the fuzzy value from the decision node without any information about the decision set in which that node is a member of. * @param item * @return */ double evaluate(DecisionNode item); /** * To get the fuzzy value from the decision node given the decision set in which that node is a member of. * @param item * @param universeSet * @return */
// Path: src/fdt/core/DecisionNode.java // public class DecisionNode extends Node { // // private static final long serialVersionUID = 5241099508522414606L; // // private double support; // // /** // * // */ // public DecisionNode() { // } // // /** // * // * @param text // * @param support // */ // public DecisionNode(String text, double support) { // super(text); // this.support = support; // } // // /** // * // * @return // */ // public double getSupport() { // return support; // } // // /** // * // * @param support // */ // public void setSupport(double support) { // this.support = support; // } // // /** // * // * @return // */ // @Override // public boolean isLeaf() { // return true; // } // // } // // Path: src/fdt/core/DecisionSet.java // public class DecisionSet implements Serializable { // // private static final long serialVersionUID = -2414492555910250695L; // // private String name; // private final List<DecisionNode> decisionNodes = new ArrayList<>(); // private IntermediateNode estimator; // // private final List<Object> bag = new ArrayList<>(); // // /** // * // */ // public DecisionSet() { // } // // /** // * // * @param name // */ // public DecisionSet(String name) { // this.name = name; // } // // /** // * // * @param name // * @param estimator // */ // public DecisionSet(String name, IntermediateNode estimator) { // this.name = name; // this.estimator = estimator; // } // // /** // * // * @return // */ // public IntermediateNode getEstimator() { // return estimator; // } // // /** // * // * @param estimator // */ // public void setEstimator(IntermediateNode estimator) { // this.estimator = estimator; // } // // /** // * // * @return // */ // public String getName() { // return name; // } // // /** // * // * @param name // */ // public void setName(String name) { // this.name = name; // } // // /** // * // * @return // */ // @Override // public String toString() { // return name; // } // // /** // * // * @return // */ // public List<DecisionNode> getDecisionNodes() { // return decisionNodes; // } // // /** // * // * @param val // */ // public void addToBag(Object val) { // bag.add(val); // } // // /** // * // * @return // */ // public List<Object> getBag() { // return bag; // } // // /** // * // * @param obj // * @return // */ // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // // return super.equals(obj); //To change body of generated methods, choose Tools | Templates. // } // // } // Path: src/fdt/fuzzy/integrals/FuzzyValue.java import fdt.core.DecisionNode; import fdt.core.DecisionSet; import java.io.Serializable; package fdt.fuzzy.integrals; /** * * An interface to compute the fuzzy value from a decision node. * @see DefaultFuzzyValue * @author Mohammed Jabreel */ public interface FuzzyValue extends Serializable { /** * To get the fuzzy value from the decision node without any information about the decision set in which that node is a member of. * @param item * @return */ double evaluate(DecisionNode item); /** * To get the fuzzy value from the decision node given the decision set in which that node is a member of. * @param item * @param universeSet * @return */
double evaluate(DecisionNode item, DecisionSet universeSet);
mhjabreel/FDTKit
src/fdt/core/TrainableEdge.java
// Path: src/fdt/utils/Tuple.java // public class Tuple<T1, T2> { // private T1 first; // private T2 second; // // /** // * // */ // public Tuple() { // } // // /** // * // * @param first // * @param second // */ // public Tuple(T1 first, T2 second) { // this.first = first; // this.second = second; // } // // /** // * // * @return // */ // public T1 getFirst() { // return first; // } // // /** // * // * @return // */ // public T2 getSecond() { // return second; // } // // /** // * // * @param first // */ // public void setFirst(T1 first) { // this.first = first; // } // // /** // * // * @param second // */ // public void setSecond(T2 second) { // this.second = second; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("(%s, %s)", first, second); // } // // // }
import fdt.utils.Tuple; import java.util.HashMap;
package fdt.core; /** * * @author Mohammed Jabreel */ public class TrainableEdge extends EdgeBase { private static final long serialVersionUID = 1865428303994838795L; private double[] evidences; private HashMap<String, Double> classSupports = new HashMap<>(); /** * */ public TrainableEdge() { } /** * * @param edge */ public TrainableEdge(TrainableEdge edge) { this.evidences = edge.evidences; this.ambiguity = edge.ambiguity; this.classSupports = edge.classSupports; this.text = edge.text; } /** * * @param text */ public TrainableEdge(String text) { super(text); } /** * * @param className * @param support */ public void setClassSupport(String className, double support) { classSupports.put(className, support); } /** * * @return */ public HashMap<String, Double> getClassSupports() { return classSupports; } /** * * @return */
// Path: src/fdt/utils/Tuple.java // public class Tuple<T1, T2> { // private T1 first; // private T2 second; // // /** // * // */ // public Tuple() { // } // // /** // * // * @param first // * @param second // */ // public Tuple(T1 first, T2 second) { // this.first = first; // this.second = second; // } // // /** // * // * @return // */ // public T1 getFirst() { // return first; // } // // /** // * // * @return // */ // public T2 getSecond() { // return second; // } // // /** // * // * @param first // */ // public void setFirst(T1 first) { // this.first = first; // } // // /** // * // * @param second // */ // public void setSecond(T2 second) { // this.second = second; // } // // /** // * // * @return // */ // @Override // public String toString() { // return String.format("(%s, %s)", first, second); // } // // // } // Path: src/fdt/core/TrainableEdge.java import fdt.utils.Tuple; import java.util.HashMap; package fdt.core; /** * * @author Mohammed Jabreel */ public class TrainableEdge extends EdgeBase { private static final long serialVersionUID = 1865428303994838795L; private double[] evidences; private HashMap<String, Double> classSupports = new HashMap<>(); /** * */ public TrainableEdge() { } /** * * @param edge */ public TrainableEdge(TrainableEdge edge) { this.evidences = edge.evidences; this.ambiguity = edge.ambiguity; this.classSupports = edge.classSupports; this.text = edge.text; } /** * * @param text */ public TrainableEdge(String text) { super(text); } /** * * @param className * @param support */ public void setClassSupport(String className, double support) { classSupports.put(className, support); } /** * * @return */ public HashMap<String, Double> getClassSupports() { return classSupports; } /** * * @return */
public Tuple<String, Double> getBestClass() {
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/parser/simple/StraightForwardParser.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public interface ByteArraySource { // // ByteArrayChunk getNext() throws Exception; // // public abstract static class ReusableChunk { // // private final Runnable onFree; // private final AtomicInteger usageCount = new AtomicInteger(0); // // /** // * @param onFree - callback that will be called when usage count reaches zero // */ // protected ReusableChunk(Runnable onFree) { // this.onFree = onFree; // } // // public void incrementUseCount() { // usageCount.incrementAndGet(); // } // // public void decrementUseCount() { // int value = usageCount.decrementAndGet(); // if (value <= 0) onFree.run(); // } // } // // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParser.java // public interface CSVParser<T> { // // public default Stream<T> parse(File file) throws IOException { // InputStream is = new FileInputStream(file); // return parse(is).onClose(() -> IOUtils.closeQuietly(is)); // } // // public Stream<T> parse(InputStream is); // // public Stream<T> parse(ByteArraySource bas); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.function.Function; import java.util.stream.Stream; import uk.elementarysoftware.quickcsv.api.ByteArraySource; import uk.elementarysoftware.quickcsv.api.CSVParser; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.Field;
private Function<String[], CSVRecord> toCSVRecord() { return new Function<String[], CSVRecord>() { @Override public CSVRecord apply(String[] fields) { return new SimpleCSVRecord(fields); } }; } public static class SimpleCSVRecord implements CSVRecord { private String[] fields; private int index; public SimpleCSVRecord(String[] fields) { this.index = 0; this.fields = fields; } @Override public void skipField() { index++; } @Override public void skipFields(int nFields) { index+=nFields; } @Override
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public interface ByteArraySource { // // ByteArrayChunk getNext() throws Exception; // // public abstract static class ReusableChunk { // // private final Runnable onFree; // private final AtomicInteger usageCount = new AtomicInteger(0); // // /** // * @param onFree - callback that will be called when usage count reaches zero // */ // protected ReusableChunk(Runnable onFree) { // this.onFree = onFree; // } // // public void incrementUseCount() { // usageCount.incrementAndGet(); // } // // public void decrementUseCount() { // int value = usageCount.decrementAndGet(); // if (value <= 0) onFree.run(); // } // } // // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParser.java // public interface CSVParser<T> { // // public default Stream<T> parse(File file) throws IOException { // InputStream is = new FileInputStream(file); // return parse(is).onClose(() -> IOUtils.closeQuietly(is)); // } // // public Stream<T> parse(InputStream is); // // public Stream<T> parse(ByteArraySource bas); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // Path: src/test/java/uk/elementarysoftware/quickcsv/parser/simple/StraightForwardParser.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.function.Function; import java.util.stream.Stream; import uk.elementarysoftware.quickcsv.api.ByteArraySource; import uk.elementarysoftware.quickcsv.api.CSVParser; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.Field; private Function<String[], CSVRecord> toCSVRecord() { return new Function<String[], CSVRecord>() { @Override public CSVRecord apply(String[] fields) { return new SimpleCSVRecord(fields); } }; } public static class SimpleCSVRecord implements CSVRecord { private String[] fields; private int index; public SimpleCSVRecord(String[] fields) { this.index = 0; this.fields = fields; } @Override public void skipField() { index++; } @Override public void skipFields(int nFields) { index+=nFields; } @Override
public Field getNextField() {
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/parser/simple/StraightForwardParser.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public interface ByteArraySource { // // ByteArrayChunk getNext() throws Exception; // // public abstract static class ReusableChunk { // // private final Runnable onFree; // private final AtomicInteger usageCount = new AtomicInteger(0); // // /** // * @param onFree - callback that will be called when usage count reaches zero // */ // protected ReusableChunk(Runnable onFree) { // this.onFree = onFree; // } // // public void incrementUseCount() { // usageCount.incrementAndGet(); // } // // public void decrementUseCount() { // int value = usageCount.decrementAndGet(); // if (value <= 0) onFree.run(); // } // } // // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParser.java // public interface CSVParser<T> { // // public default Stream<T> parse(File file) throws IOException { // InputStream is = new FileInputStream(file); // return parse(is).onClose(() -> IOUtils.closeQuietly(is)); // } // // public Stream<T> parse(InputStream is); // // public Stream<T> parse(ByteArraySource bas); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.function.Function; import java.util.stream.Stream; import uk.elementarysoftware.quickcsv.api.ByteArraySource; import uk.elementarysoftware.quickcsv.api.CSVParser; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.Field;
return 0; } @Override public Field clone() { return this; } @Override public boolean isEmpty() { return value.length() == 0; } @Override public Double asBoxedDouble() { return asDouble(); } @Override public Integer asBoxedInt() { return asInt(); } } @Override public Stream<CSVRecord> parse(InputStream is) { throw new UnsupportedOperationException(); } @Override
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public interface ByteArraySource { // // ByteArrayChunk getNext() throws Exception; // // public abstract static class ReusableChunk { // // private final Runnable onFree; // private final AtomicInteger usageCount = new AtomicInteger(0); // // /** // * @param onFree - callback that will be called when usage count reaches zero // */ // protected ReusableChunk(Runnable onFree) { // this.onFree = onFree; // } // // public void incrementUseCount() { // usageCount.incrementAndGet(); // } // // public void decrementUseCount() { // int value = usageCount.decrementAndGet(); // if (value <= 0) onFree.run(); // } // } // // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParser.java // public interface CSVParser<T> { // // public default Stream<T> parse(File file) throws IOException { // InputStream is = new FileInputStream(file); // return parse(is).onClose(() -> IOUtils.closeQuietly(is)); // } // // public Stream<T> parse(InputStream is); // // public Stream<T> parse(ByteArraySource bas); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // Path: src/test/java/uk/elementarysoftware/quickcsv/parser/simple/StraightForwardParser.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.function.Function; import java.util.stream.Stream; import uk.elementarysoftware.quickcsv.api.ByteArraySource; import uk.elementarysoftware.quickcsv.api.CSVParser; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.Field; return 0; } @Override public Field clone() { return this; } @Override public boolean isEmpty() { return value.length() == 0; } @Override public Double asBoxedDouble() { return asDouble(); } @Override public Integer asBoxedInt() { return asInt(); } } @Override public Stream<CSVRecord> parse(InputStream is) { throw new UnsupportedOperationException(); } @Override
public Stream<CSVRecord> parse(ByteArraySource bas) {
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/sampledomain/City.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecordWithHeader.java // public interface CSVRecordWithHeader<K extends Enum<K>> { // // public Field getField(K field); // // public List<String> getHeader(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // }
import java.util.function.Function; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.CSVRecordWithHeader; import uk.elementarysoftware.quickcsv.api.Field;
package uk.elementarysoftware.quickcsv.sampledomain; public class City { public static final Function<CSVRecord, City> MAPPER = City::new; public static class HeaderAwareMapper { public static enum Fields { AccentCity, Latitude, Longitude, Population }
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecordWithHeader.java // public interface CSVRecordWithHeader<K extends Enum<K>> { // // public Field getField(K field); // // public List<String> getHeader(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // Path: src/test/java/uk/elementarysoftware/quickcsv/sampledomain/City.java import java.util.function.Function; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.CSVRecordWithHeader; import uk.elementarysoftware.quickcsv.api.Field; package uk.elementarysoftware.quickcsv.sampledomain; public class City { public static final Function<CSVRecord, City> MAPPER = City::new; public static class HeaderAwareMapper { public static enum Fields { AccentCity, Latitude, Longitude, Population }
public static final Function<CSVRecordWithHeader<Fields>, City> MAPPER = r -> {
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/sampledomain/City.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecordWithHeader.java // public interface CSVRecordWithHeader<K extends Enum<K>> { // // public Field getField(K field); // // public List<String> getHeader(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // }
import java.util.function.Function; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.CSVRecordWithHeader; import uk.elementarysoftware.quickcsv.api.Field;
} public static class HeaderAwareMapper2 { public static enum Fields { AccentCity, Population, Latitude, Longitude, Country, City } public static final Function<CSVRecordWithHeader<Fields>, City> MAPPER = r -> { return new City( r.getField(Fields.City).asString(), r.getField(Fields.Population).asInt(), r.getField(Fields.Latitude).asDouble(), r.getField(Fields.Longitude).asDouble(), r.getField(Fields.Population).asLong() ); }; } private static final int CITY_INDEX = 2; private final String city; private final int population; private final double latitude; private final double longitude; private final long populationL; public City(CSVRecord r) { r.skipFields(CITY_INDEX); this.city = r.getNextField().asString(); r.skipField();
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecordWithHeader.java // public interface CSVRecordWithHeader<K extends Enum<K>> { // // public Field getField(K field); // // public List<String> getHeader(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // Path: src/test/java/uk/elementarysoftware/quickcsv/sampledomain/City.java import java.util.function.Function; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.CSVRecordWithHeader; import uk.elementarysoftware.quickcsv.api.Field; } public static class HeaderAwareMapper2 { public static enum Fields { AccentCity, Population, Latitude, Longitude, Country, City } public static final Function<CSVRecordWithHeader<Fields>, City> MAPPER = r -> { return new City( r.getField(Fields.City).asString(), r.getField(Fields.Population).asInt(), r.getField(Fields.Latitude).asDouble(), r.getField(Fields.Longitude).asDouble(), r.getField(Fields.Population).asLong() ); }; } private static final int CITY_INDEX = 2; private final String city; private final int population; private final double latitude; private final double longitude; private final long populationL; public City(CSVRecord r) { r.skipFields(CITY_INDEX); this.city = r.getNextField().asString(); r.skipField();
Field popField = r.getNextField();
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParserTest.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParser.java // public interface DoubleParser { // public double parse(byte[] in, int startIndex, int length); // // default public double parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/JDKDoubleParserAdapter.java // public class JDKDoubleParserAdapter implements DoubleParser { // // public double parse(byte[] in, int startIndex, int length) { // return JDKDoubleParser.readJavaFormatString(in, startIndex, length).doubleValue(); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/QuickDoubleParser.java // public class QuickDoubleParser implements DoubleParser { // // private static final int RADIX = 10; // private static final int DOT = '.'-'0'; // // private JDKDoubleParserAdapter fallBack = new JDKDoubleParserAdapter(); // // public double parse(byte[] bytes, int offset, int length) { // if (bytes == null || length <=0) // throw new NumberFormatException("Empty input"); // long result = 0; // boolean isNegative = false; // int index = offset, dotIndex=offset+length-1, endIndex = offset+length; // // byte firstByte = bytes[index]; // if (firstByte < '0') { // if (firstByte == '-') { // isNegative = true; // } // index++; // } // int nDigits = 0; // while (index < endIndex) { // int digit = bytes[index] - '0'; // if (digit == DOT) { // dotIndex=index; // }else if (digit < 0 || digit>9) { // throw new NumberFormatException("For: "+new String(bytes, offset, length)); // } else { // result *= RADIX; // result -= digit; // nDigits++; // } // index++; // } // // double mantissa = -result; // int negExponent = length-(dotIndex-offset)-1; // // if (nDigits <= JDKDoubleParser.maxDecimalDigits) { // if (negExponent == 0 || mantissa == 0.0) { // return (isNegative) ? -mantissa : mantissa; // } // double rValue = mantissa / JDKDoubleParser.small10pow[negExponent]; // return (isNegative) ? -rValue : rValue; // } else { //harder case, use JDK implementation // return fallBack.parse(bytes, offset, length); // } // } // }
import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.junit.Test; import uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser; import uk.elementarysoftware.quickcsv.decoder.doubles.JDKDoubleParserAdapter; import uk.elementarysoftware.quickcsv.decoder.doubles.QuickDoubleParser;
package uk.elementarysoftware.quickcsv.decoder.doubles; public class DoubleParserTest { @Test public void testSimpleCases() {
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParser.java // public interface DoubleParser { // public double parse(byte[] in, int startIndex, int length); // // default public double parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/JDKDoubleParserAdapter.java // public class JDKDoubleParserAdapter implements DoubleParser { // // public double parse(byte[] in, int startIndex, int length) { // return JDKDoubleParser.readJavaFormatString(in, startIndex, length).doubleValue(); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/QuickDoubleParser.java // public class QuickDoubleParser implements DoubleParser { // // private static final int RADIX = 10; // private static final int DOT = '.'-'0'; // // private JDKDoubleParserAdapter fallBack = new JDKDoubleParserAdapter(); // // public double parse(byte[] bytes, int offset, int length) { // if (bytes == null || length <=0) // throw new NumberFormatException("Empty input"); // long result = 0; // boolean isNegative = false; // int index = offset, dotIndex=offset+length-1, endIndex = offset+length; // // byte firstByte = bytes[index]; // if (firstByte < '0') { // if (firstByte == '-') { // isNegative = true; // } // index++; // } // int nDigits = 0; // while (index < endIndex) { // int digit = bytes[index] - '0'; // if (digit == DOT) { // dotIndex=index; // }else if (digit < 0 || digit>9) { // throw new NumberFormatException("For: "+new String(bytes, offset, length)); // } else { // result *= RADIX; // result -= digit; // nDigits++; // } // index++; // } // // double mantissa = -result; // int negExponent = length-(dotIndex-offset)-1; // // if (nDigits <= JDKDoubleParser.maxDecimalDigits) { // if (negExponent == 0 || mantissa == 0.0) { // return (isNegative) ? -mantissa : mantissa; // } // double rValue = mantissa / JDKDoubleParser.small10pow[negExponent]; // return (isNegative) ? -rValue : rValue; // } else { //harder case, use JDK implementation // return fallBack.parse(bytes, offset, length); // } // } // } // Path: src/test/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParserTest.java import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.junit.Test; import uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser; import uk.elementarysoftware.quickcsv.decoder.doubles.JDKDoubleParserAdapter; import uk.elementarysoftware.quickcsv.decoder.doubles.QuickDoubleParser; package uk.elementarysoftware.quickcsv.decoder.doubles; public class DoubleParserTest { @Test public void testSimpleCases() {
doTestSimpleCases(new JDKDoubleParserAdapter());
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParserTest.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParser.java // public interface DoubleParser { // public double parse(byte[] in, int startIndex, int length); // // default public double parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/JDKDoubleParserAdapter.java // public class JDKDoubleParserAdapter implements DoubleParser { // // public double parse(byte[] in, int startIndex, int length) { // return JDKDoubleParser.readJavaFormatString(in, startIndex, length).doubleValue(); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/QuickDoubleParser.java // public class QuickDoubleParser implements DoubleParser { // // private static final int RADIX = 10; // private static final int DOT = '.'-'0'; // // private JDKDoubleParserAdapter fallBack = new JDKDoubleParserAdapter(); // // public double parse(byte[] bytes, int offset, int length) { // if (bytes == null || length <=0) // throw new NumberFormatException("Empty input"); // long result = 0; // boolean isNegative = false; // int index = offset, dotIndex=offset+length-1, endIndex = offset+length; // // byte firstByte = bytes[index]; // if (firstByte < '0') { // if (firstByte == '-') { // isNegative = true; // } // index++; // } // int nDigits = 0; // while (index < endIndex) { // int digit = bytes[index] - '0'; // if (digit == DOT) { // dotIndex=index; // }else if (digit < 0 || digit>9) { // throw new NumberFormatException("For: "+new String(bytes, offset, length)); // } else { // result *= RADIX; // result -= digit; // nDigits++; // } // index++; // } // // double mantissa = -result; // int negExponent = length-(dotIndex-offset)-1; // // if (nDigits <= JDKDoubleParser.maxDecimalDigits) { // if (negExponent == 0 || mantissa == 0.0) { // return (isNegative) ? -mantissa : mantissa; // } // double rValue = mantissa / JDKDoubleParser.small10pow[negExponent]; // return (isNegative) ? -rValue : rValue; // } else { //harder case, use JDK implementation // return fallBack.parse(bytes, offset, length); // } // } // }
import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.junit.Test; import uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser; import uk.elementarysoftware.quickcsv.decoder.doubles.JDKDoubleParserAdapter; import uk.elementarysoftware.quickcsv.decoder.doubles.QuickDoubleParser;
package uk.elementarysoftware.quickcsv.decoder.doubles; public class DoubleParserTest { @Test public void testSimpleCases() { doTestSimpleCases(new JDKDoubleParserAdapter());
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParser.java // public interface DoubleParser { // public double parse(byte[] in, int startIndex, int length); // // default public double parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/JDKDoubleParserAdapter.java // public class JDKDoubleParserAdapter implements DoubleParser { // // public double parse(byte[] in, int startIndex, int length) { // return JDKDoubleParser.readJavaFormatString(in, startIndex, length).doubleValue(); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/QuickDoubleParser.java // public class QuickDoubleParser implements DoubleParser { // // private static final int RADIX = 10; // private static final int DOT = '.'-'0'; // // private JDKDoubleParserAdapter fallBack = new JDKDoubleParserAdapter(); // // public double parse(byte[] bytes, int offset, int length) { // if (bytes == null || length <=0) // throw new NumberFormatException("Empty input"); // long result = 0; // boolean isNegative = false; // int index = offset, dotIndex=offset+length-1, endIndex = offset+length; // // byte firstByte = bytes[index]; // if (firstByte < '0') { // if (firstByte == '-') { // isNegative = true; // } // index++; // } // int nDigits = 0; // while (index < endIndex) { // int digit = bytes[index] - '0'; // if (digit == DOT) { // dotIndex=index; // }else if (digit < 0 || digit>9) { // throw new NumberFormatException("For: "+new String(bytes, offset, length)); // } else { // result *= RADIX; // result -= digit; // nDigits++; // } // index++; // } // // double mantissa = -result; // int negExponent = length-(dotIndex-offset)-1; // // if (nDigits <= JDKDoubleParser.maxDecimalDigits) { // if (negExponent == 0 || mantissa == 0.0) { // return (isNegative) ? -mantissa : mantissa; // } // double rValue = mantissa / JDKDoubleParser.small10pow[negExponent]; // return (isNegative) ? -rValue : rValue; // } else { //harder case, use JDK implementation // return fallBack.parse(bytes, offset, length); // } // } // } // Path: src/test/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParserTest.java import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.junit.Test; import uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser; import uk.elementarysoftware.quickcsv.decoder.doubles.JDKDoubleParserAdapter; import uk.elementarysoftware.quickcsv.decoder.doubles.QuickDoubleParser; package uk.elementarysoftware.quickcsv.decoder.doubles; public class DoubleParserTest { @Test public void testSimpleCases() { doTestSimpleCases(new JDKDoubleParserAdapter());
doTestSimpleCases(new QuickDoubleParser());
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParserTest.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParser.java // public interface DoubleParser { // public double parse(byte[] in, int startIndex, int length); // // default public double parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/JDKDoubleParserAdapter.java // public class JDKDoubleParserAdapter implements DoubleParser { // // public double parse(byte[] in, int startIndex, int length) { // return JDKDoubleParser.readJavaFormatString(in, startIndex, length).doubleValue(); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/QuickDoubleParser.java // public class QuickDoubleParser implements DoubleParser { // // private static final int RADIX = 10; // private static final int DOT = '.'-'0'; // // private JDKDoubleParserAdapter fallBack = new JDKDoubleParserAdapter(); // // public double parse(byte[] bytes, int offset, int length) { // if (bytes == null || length <=0) // throw new NumberFormatException("Empty input"); // long result = 0; // boolean isNegative = false; // int index = offset, dotIndex=offset+length-1, endIndex = offset+length; // // byte firstByte = bytes[index]; // if (firstByte < '0') { // if (firstByte == '-') { // isNegative = true; // } // index++; // } // int nDigits = 0; // while (index < endIndex) { // int digit = bytes[index] - '0'; // if (digit == DOT) { // dotIndex=index; // }else if (digit < 0 || digit>9) { // throw new NumberFormatException("For: "+new String(bytes, offset, length)); // } else { // result *= RADIX; // result -= digit; // nDigits++; // } // index++; // } // // double mantissa = -result; // int negExponent = length-(dotIndex-offset)-1; // // if (nDigits <= JDKDoubleParser.maxDecimalDigits) { // if (negExponent == 0 || mantissa == 0.0) { // return (isNegative) ? -mantissa : mantissa; // } // double rValue = mantissa / JDKDoubleParser.small10pow[negExponent]; // return (isNegative) ? -rValue : rValue; // } else { //harder case, use JDK implementation // return fallBack.parse(bytes, offset, length); // } // } // }
import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.junit.Test; import uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser; import uk.elementarysoftware.quickcsv.decoder.doubles.JDKDoubleParserAdapter; import uk.elementarysoftware.quickcsv.decoder.doubles.QuickDoubleParser;
package uk.elementarysoftware.quickcsv.decoder.doubles; public class DoubleParserTest { @Test public void testSimpleCases() { doTestSimpleCases(new JDKDoubleParserAdapter()); doTestSimpleCases(new QuickDoubleParser()); } @Test public void testBigBuffer() { doTestBigBuffer(new JDKDoubleParserAdapter()); doTestBigBuffer(new QuickDoubleParser()); } @Test public void testFile() throws Exception { doTestFile(new JDKDoubleParserAdapter()); doTestFile(new QuickDoubleParser()); }
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParser.java // public interface DoubleParser { // public double parse(byte[] in, int startIndex, int length); // // default public double parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/JDKDoubleParserAdapter.java // public class JDKDoubleParserAdapter implements DoubleParser { // // public double parse(byte[] in, int startIndex, int length) { // return JDKDoubleParser.readJavaFormatString(in, startIndex, length).doubleValue(); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/doubles/QuickDoubleParser.java // public class QuickDoubleParser implements DoubleParser { // // private static final int RADIX = 10; // private static final int DOT = '.'-'0'; // // private JDKDoubleParserAdapter fallBack = new JDKDoubleParserAdapter(); // // public double parse(byte[] bytes, int offset, int length) { // if (bytes == null || length <=0) // throw new NumberFormatException("Empty input"); // long result = 0; // boolean isNegative = false; // int index = offset, dotIndex=offset+length-1, endIndex = offset+length; // // byte firstByte = bytes[index]; // if (firstByte < '0') { // if (firstByte == '-') { // isNegative = true; // } // index++; // } // int nDigits = 0; // while (index < endIndex) { // int digit = bytes[index] - '0'; // if (digit == DOT) { // dotIndex=index; // }else if (digit < 0 || digit>9) { // throw new NumberFormatException("For: "+new String(bytes, offset, length)); // } else { // result *= RADIX; // result -= digit; // nDigits++; // } // index++; // } // // double mantissa = -result; // int negExponent = length-(dotIndex-offset)-1; // // if (nDigits <= JDKDoubleParser.maxDecimalDigits) { // if (negExponent == 0 || mantissa == 0.0) { // return (isNegative) ? -mantissa : mantissa; // } // double rValue = mantissa / JDKDoubleParser.small10pow[negExponent]; // return (isNegative) ? -rValue : rValue; // } else { //harder case, use JDK implementation // return fallBack.parse(bytes, offset, length); // } // } // } // Path: src/test/java/uk/elementarysoftware/quickcsv/decoder/doubles/DoubleParserTest.java import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.net.URL; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.junit.Test; import uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser; import uk.elementarysoftware.quickcsv.decoder.doubles.JDKDoubleParserAdapter; import uk.elementarysoftware.quickcsv.decoder.doubles.QuickDoubleParser; package uk.elementarysoftware.quickcsv.decoder.doubles; public class DoubleParserTest { @Test public void testSimpleCases() { doTestSimpleCases(new JDKDoubleParserAdapter()); doTestSimpleCases(new QuickDoubleParser()); } @Test public void testBigBuffer() { doTestBigBuffer(new JDKDoubleParserAdapter()); doTestBigBuffer(new QuickDoubleParser()); } @Test public void testFile() throws Exception { doTestFile(new JDKDoubleParserAdapter()); doTestFile(new QuickDoubleParser()); }
private void doTestSimpleCases(DoubleParser parser) {
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/FieldSubsetView.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata;
package uk.elementarysoftware.quickcsv.parser; /** * Provides view on the CSVRecord that focuses on particular subset of fields. * * Within the view fields can be accessed by index in order of the subset or by field enumeration K. * @param <K> - enum containing list of fields that form the subset */ public class FieldSubsetView<K extends Enum<K>> { private final HeaderSource headerSource; private final Class<K> fieldSubset; private boolean isFirstSlice = true; private int[] headerIndexesOfK; private int[] parseOrderToSourceOrder; private int[] fieldSkipSchedule; private FieldSubsetView(HeaderSource headerSource, Class<K> fieldSubset) { this.headerSource = headerSource; this.fieldSubset = fieldSubset; } public static <K extends Enum<K>> FieldSubsetView<K> forExplicitHeader(Class<K> fieldsToSource, String... header) { return new FieldSubsetView<>(new HeaderSource.ExplicitHeader(header), fieldsToSource); } public static <K extends Enum<K>> FieldSubsetView<K> forSourceSuppliedHeader(Class<K> fieldsToSource) { return forSourceSuppliedHeader(fieldsToSource, 0); } public static <K extends Enum<K>> FieldSubsetView<K> forSourceSuppliedHeader(Class<K> fieldsToSource, int headerRowIndexInFile) { return new FieldSubsetView<>(new HeaderSource.SourceSuppliedHeader(headerRowIndexInFile), fieldsToSource); }
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/FieldSubsetView.java import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; package uk.elementarysoftware.quickcsv.parser; /** * Provides view on the CSVRecord that focuses on particular subset of fields. * * Within the view fields can be accessed by index in order of the subset or by field enumeration K. * @param <K> - enum containing list of fields that form the subset */ public class FieldSubsetView<K extends Enum<K>> { private final HeaderSource headerSource; private final Class<K> fieldSubset; private boolean isFirstSlice = true; private int[] headerIndexesOfK; private int[] parseOrderToSourceOrder; private int[] fieldSkipSchedule; private FieldSubsetView(HeaderSource headerSource, Class<K> fieldSubset) { this.headerSource = headerSource; this.fieldSubset = fieldSubset; } public static <K extends Enum<K>> FieldSubsetView<K> forExplicitHeader(Class<K> fieldsToSource, String... header) { return new FieldSubsetView<>(new HeaderSource.ExplicitHeader(header), fieldsToSource); } public static <K extends Enum<K>> FieldSubsetView<K> forSourceSuppliedHeader(Class<K> fieldsToSource) { return forSourceSuppliedHeader(fieldsToSource, 0); } public static <K extends Enum<K>> FieldSubsetView<K> forSourceSuppliedHeader(Class<K> fieldsToSource, int headerRowIndexInFile) { return new FieldSubsetView<>(new HeaderSource.SourceSuppliedHeader(headerRowIndexInFile), fieldsToSource); }
public void onSlice(ByteSlice slice, CSVFileMetadata metadata) {
titorenko/quick-csv-streamer
src/jmh/java/uk/elementarysoftware/quickcsv/benchmarks/City.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecordWithHeader.java // public interface CSVRecordWithHeader<K extends Enum<K>> { // // public Field getField(K field); // // public List<String> getHeader(); // }
import java.util.function.Function; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.CSVRecordWithHeader;
package uk.elementarysoftware.quickcsv.benchmarks; public class City { public static final Function<CSVRecord, City> MAPPER = City::new; public static class EnumMapper { public static enum Fields { AccentCity, Population, Latitude, Longitude }
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecord.java // public interface CSVRecord { // public void skipField(); // public void skipFields(int nFields); // // public Field getNextField(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVRecordWithHeader.java // public interface CSVRecordWithHeader<K extends Enum<K>> { // // public Field getField(K field); // // public List<String> getHeader(); // } // Path: src/jmh/java/uk/elementarysoftware/quickcsv/benchmarks/City.java import java.util.function.Function; import uk.elementarysoftware.quickcsv.api.CSVRecord; import uk.elementarysoftware.quickcsv.api.CSVRecordWithHeader; package uk.elementarysoftware.quickcsv.benchmarks; public class City { public static final Function<CSVRecord, City> MAPPER = City::new; public static class EnumMapper { public static enum Fields { AccentCity, Population, Latitude, Longitude }
public static final Function<CSVRecordWithHeader<Fields>, City> MAPPER = r -> {
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT;
package uk.elementarysoftware.quickcsv.parser; public interface ByteSlice { static final byte CR = 0xD; static final byte LF = 0xA;
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT; package uk.elementarysoftware.quickcsv.parser; public interface ByteSlice { static final byte CR = 0xD; static final byte LF = 0xA;
public static ByteSlice wrap(ByteArrayChunk it, Charset charset) {
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT;
package uk.elementarysoftware.quickcsv.parser; public interface ByteSlice { static final byte CR = 0xD; static final byte LF = 0xA; public static ByteSlice wrap(ByteArrayChunk it, Charset charset) { return new SingleByteSlice(it, charset); } public static ByteSlice empty() { return wrap(ByteArrayChunk.EMPTY, null); } public static ByteSlice join(ByteSlice prefix, ByteSlice suffix) { return new CompositeByteSlice((SingleByteSlice) prefix, (SingleByteSlice) suffix); }
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT; package uk.elementarysoftware.quickcsv.parser; public interface ByteSlice { static final byte CR = 0xD; static final byte LF = 0xA; public static ByteSlice wrap(ByteArrayChunk it, Charset charset) { return new SingleByteSlice(it, charset); } public static ByteSlice empty() { return wrap(ByteArrayChunk.EMPTY, null); } public static ByteSlice join(ByteSlice prefix, ByteSlice suffix) { return new CompositeByteSlice((SingleByteSlice) prefix, (SingleByteSlice) suffix); }
public Pair<ByteSlice, ByteSlice> splitOnLastLineEnd();
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT;
if (currentIndex == end) { if (buffer[end-1] == q) endIndex = end - 1; else endIndex = end; } fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject;
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT; if (currentIndex == end) { if (buffer[end-1] == q) endIndex = end - 1; else endIndex = end; } fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject;
private FunCharToT<ByteArrayField> nextFieldFun;
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT;
if (buffer[end-1] == q) endIndex = end - 1; else endIndex = end; } fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject; private FunCharToT<ByteArrayField> nextFieldFun;
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT; if (buffer[end-1] == q) endIndex = end - 1; else endIndex = end; } fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject; private FunCharToT<ByteArrayField> nextFieldFun;
private FunBiCharToT<ByteArrayField> nextFieldFunQuoted;
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT;
} fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject; private FunCharToT<ByteArrayField> nextFieldFun; private FunBiCharToT<ByteArrayField> nextFieldFunQuoted;
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT; } fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject; private FunCharToT<ByteArrayField> nextFieldFun; private FunBiCharToT<ByteArrayField> nextFieldFunQuoted;
private FunCharToBoolean skipUntilFun;
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT;
fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject; private FunCharToT<ByteArrayField> nextFieldFun; private FunBiCharToT<ByteArrayField> nextFieldFunQuoted; private FunCharToBoolean skipUntilFun;
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParserBuilder.java // public static class CSVFileMetadata { // // public static CSVFileMetadata RFC_4180 = new CSVFileMetadata(',', Optional.of('"')); // public static CSVFileMetadata TABS = new CSVFileMetadata('\t', Optional.empty()); // // public final char separator; // public final Optional<Character> quote; // // public CSVFileMetadata(char separator, Optional<Character> quote) { // this.separator = separator; // this.quote = quote; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToBoolean { // public boolean apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunBiCharToT<T> { // public T apply(char c, char q); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToBoolean { // public boolean apply(char c); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/PrimitiveFunctions.java // @FunctionalInterface // public static interface FunCharToT<T> { // public T apply(char c); // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/ByteSlice.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.CSVParserBuilder.CSVFileMetadata; import uk.elementarysoftware.quickcsv.functional.Pair; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunBiCharToT; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToBoolean; import uk.elementarysoftware.quickcsv.functional.PrimitiveFunctions.FunCharToT; fieldTemplateObject.modifyBounds(startIndex, endIndex, q); return fieldTemplateObject; } @Override public String toString() { return new String(buffer, start, size()); } @Override public void incrementUse() { src.incrementUseCount(); } @Override public void decremenentUse() { src.decrementUseCount(); } } final class CompositeByteSlice implements ByteSlice { private final SingleByteSlice prefix; private final SingleByteSlice suffix; private final ByteArrayField prefixFieldTemplateObject; private final ByteArrayField suffixFieldTemplateObject; private FunCharToT<ByteArrayField> nextFieldFun; private FunBiCharToT<ByteArrayField> nextFieldFunQuoted; private FunCharToBoolean skipUntilFun;
private FunBiCharToBoolean skipUntilFunQuoted;
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/parser/ByteSliceTest.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Test; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.functional.Pair;
package uk.elementarysoftware.quickcsv.parser; public class ByteSliceTest { private static final String FIELDS22 = "field11,field12\nfield21,field22"; private static final String FIELDS33 = "field11,field12,field13\nfield21,field22,field23\nfield31,field32,field33"; private static final String QUOTED = "'field11','field12'\n'field21','field22'\n"; @Test public void testSplitOnLastLineEnd() { String content = "line1\nline2\nlastline"; ByteSlice slice = sliceFor(content.getBytes()); assertEquals(content, slice.toString());
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // Path: src/test/java/uk/elementarysoftware/quickcsv/parser/ByteSliceTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Test; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.functional.Pair; package uk.elementarysoftware.quickcsv.parser; public class ByteSliceTest { private static final String FIELDS22 = "field11,field12\nfield21,field22"; private static final String FIELDS33 = "field11,field12,field13\nfield21,field22,field23\nfield31,field32,field33"; private static final String QUOTED = "'field11','field12'\n'field21','field22'\n"; @Test public void testSplitOnLastLineEnd() { String content = "line1\nline2\nlastline"; ByteSlice slice = sliceFor(content.getBytes()); assertEquals(content, slice.toString());
Pair<ByteSlice, ByteSlice> sliced = slice.splitOnLastLineEnd();
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/parser/ByteSliceTest.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Test; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.functional.Pair;
package uk.elementarysoftware.quickcsv.parser; public class ByteSliceTest { private static final String FIELDS22 = "field11,field12\nfield21,field22"; private static final String FIELDS33 = "field11,field12,field13\nfield21,field22,field23\nfield31,field32,field33"; private static final String QUOTED = "'field11','field12'\n'field21','field22'\n"; @Test public void testSplitOnLastLineEnd() { String content = "line1\nline2\nlastline"; ByteSlice slice = sliceFor(content.getBytes()); assertEquals(content, slice.toString()); Pair<ByteSlice, ByteSlice> sliced = slice.splitOnLastLineEnd(); assertEquals("line1\nline2\n", sliced.first.toString()); assertEquals("lastline", sliced.second.toString()); } @Test public void testSplitOnLastLineEndWithSkip() { String content = "line1\nline2\nlastline"; ByteSlice slice = sliceFor(content.getBytes()); slice.nextLine(); Pair<ByteSlice, ByteSlice> sliced = slice.splitOnLastLineEnd(); assertEquals("line2\n", sliced.first.toString()); assertEquals("lastline", sliced.second.toString()); } @Test public void testSingleSlice() { ByteSlice slice = sliceFor(FIELDS22.getBytes()); assertEquals("field11,field12", slice.currentLine());
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // Path: src/test/java/uk/elementarysoftware/quickcsv/parser/ByteSliceTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Test; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.functional.Pair; package uk.elementarysoftware.quickcsv.parser; public class ByteSliceTest { private static final String FIELDS22 = "field11,field12\nfield21,field22"; private static final String FIELDS33 = "field11,field12,field13\nfield21,field22,field23\nfield31,field32,field33"; private static final String QUOTED = "'field11','field12'\n'field21','field22'\n"; @Test public void testSplitOnLastLineEnd() { String content = "line1\nline2\nlastline"; ByteSlice slice = sliceFor(content.getBytes()); assertEquals(content, slice.toString()); Pair<ByteSlice, ByteSlice> sliced = slice.splitOnLastLineEnd(); assertEquals("line1\nline2\n", sliced.first.toString()); assertEquals("lastline", sliced.second.toString()); } @Test public void testSplitOnLastLineEndWithSkip() { String content = "line1\nline2\nlastline"; ByteSlice slice = sliceFor(content.getBytes()); slice.nextLine(); Pair<ByteSlice, ByteSlice> sliced = slice.splitOnLastLineEnd(); assertEquals("line2\n", sliced.first.toString()); assertEquals("lastline", sliced.second.toString()); } @Test public void testSingleSlice() { ByteSlice slice = sliceFor(FIELDS22.getBytes()); assertEquals("field11,field12", slice.currentLine());
List<Field> fields = getFields(slice);
titorenko/quick-csv-streamer
src/test/java/uk/elementarysoftware/quickcsv/parser/ByteSliceTest.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Test; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.functional.Pair;
for (int splitIndex = 0; splitIndex < content.length(); splitIndex++) { String prefix = content.substring(0, splitIndex); String suffix = content.substring(splitIndex); ByteSlice join = ByteSlice.join(sliceFor(prefix.getBytes()), sliceFor(suffix.getBytes())); assertTrue(join.skipUntil(',')); assertEquals("field12", join.nextField(',').asString()); assertTrue(join.nextLine()); assertEquals("field21", join.nextField(',').asString()); assertTrue(join.skipUntil(',')); assertEquals("field23", join.nextField(',').asString()); } } @Test public void testMultiSliceFieldSplitQuoted() { String content = QUOTED; for (int splitIndex = 0; splitIndex < content.length(); splitIndex++) { String prefix = content.substring(0, splitIndex); String suffix = content.substring(splitIndex); ByteSlice join = ByteSlice.join(sliceFor(prefix.getBytes()), sliceFor(suffix.getBytes())); assertEquals(content, join.toString()); List<Field> fields = getFieldsQuoted(join, '\''); assertArrayEquals( "Failed on split index "+splitIndex, new String[] {"field11","field12","field21","field22"}, fields.stream().map(f -> f.asString()).toArray()); } } private ByteSlice sliceFor(byte[] bytes) {
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/ByteArraySource.java // public static class ByteArrayChunk extends ReusableChunk { // public static final ByteArrayChunk EMPTY = new ByteArrayChunk(new byte[0], 0, false, (b) -> {}); // // private final byte[] data; // private final int length; // private final boolean isLast; // // /** // * @param data - underlying content // * @param length - content length // * @param isLast - is this chunk of is last // * @param onFree - callback that will be called when data from this chunk has been fully consumed. // */ // public ByteArrayChunk(byte[] data, int length, boolean isLast, Consumer<byte[]> onFree) { // super(() -> onFree.accept(data)); // this.data = data; // this.length = length; // this.isLast = isLast; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return length; // } // // public boolean isLast() { // return isLast; // } // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/functional/Pair.java // public class Pair<F, S> { // // public final F first; // public final S second; // // /** // * Constructor for a Pair. // * // * @param first the first object in the Pair // * @param second the second object in the pair // */ // public Pair(F first, S second) { // this.first = first; // this.second = second; // } // // /** // * Checks the two objects for equality by delegating to their respective // * {@link Object#equals(Object)} methods. // * // * @param o the {@link Pair} to which this one is to be checked for equality // * @return true if the underlying objects of the Pair are both considered // * equal // */ // @Override // public boolean equals(Object o) { // if (!(o instanceof Pair)) { // return false; // } // Pair<?, ?> p = (Pair<?, ?>) o; // return Objects.equals(p.first, first) && Objects.equals(p.second, second); // } // // /** // * Compute a hash code using the hash codes of the underlying objects // * // * @return a hashcode of the Pair // */ // @Override // public int hashCode() { // return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); // } // // @Override // public String toString() { // return first+"="+second; // } // // /** // * Convenience method for creating an appropriately typed pair. // * @param a the first object in the Pair // * @param b the second object in the pair // * @param <A> type of left element // * @param <B> type of right element // * @return a Pair that is templatized with the types of a and b // */ // public static <A, B> Pair <A, B> of(A a, B b) { // return new Pair<A, B>(a, b); // } // } // Path: src/test/java/uk/elementarysoftware/quickcsv/parser/ByteSliceTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.junit.Test; import uk.elementarysoftware.quickcsv.api.ByteArraySource.ByteArrayChunk; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.functional.Pair; for (int splitIndex = 0; splitIndex < content.length(); splitIndex++) { String prefix = content.substring(0, splitIndex); String suffix = content.substring(splitIndex); ByteSlice join = ByteSlice.join(sliceFor(prefix.getBytes()), sliceFor(suffix.getBytes())); assertTrue(join.skipUntil(',')); assertEquals("field12", join.nextField(',').asString()); assertTrue(join.nextLine()); assertEquals("field21", join.nextField(',').asString()); assertTrue(join.skipUntil(',')); assertEquals("field23", join.nextField(',').asString()); } } @Test public void testMultiSliceFieldSplitQuoted() { String content = QUOTED; for (int splitIndex = 0; splitIndex < content.length(); splitIndex++) { String prefix = content.substring(0, splitIndex); String suffix = content.substring(splitIndex); ByteSlice join = ByteSlice.join(sliceFor(prefix.getBytes()), sliceFor(suffix.getBytes())); assertEquals(content, join.toString()); List<Field> fields = getFieldsQuoted(join, '\''); assertArrayEquals( "Failed on split index "+splitIndex, new String[] {"field11","field12","field21","field22"}, fields.stream().map(f -> f.asString()).toArray()); } } private ByteSlice sliceFor(byte[] bytes) {
return ByteSlice.wrap(new ByteArrayChunk(bytes, bytes.length, false, (b) -> {}), Charset.defaultCharset());
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/api/CSVParser.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/ioutils/IOUtils.java // public class IOUtils { // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ioe) { // // ignore // } // } // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.Stream; import uk.elementarysoftware.quickcsv.ioutils.IOUtils;
package uk.elementarysoftware.quickcsv.api; /** * CSV Parser can parse inputs such as {@link InputStream} or more generally {@link ByteArraySource} to Stream&lt;T&gt;. * * @param <T> - the type of the parsing result */ public interface CSVParser<T> { public default Stream<T> parse(File file) throws IOException { InputStream is = new FileInputStream(file);
// Path: src/main/java/uk/elementarysoftware/quickcsv/ioutils/IOUtils.java // public class IOUtils { // // public static void closeQuietly(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (IOException ioe) { // // ignore // } // } // } // Path: src/main/java/uk/elementarysoftware/quickcsv/api/CSVParser.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.Stream; import uk.elementarysoftware.quickcsv.ioutils.IOUtils; package uk.elementarysoftware.quickcsv.api; /** * CSV Parser can parse inputs such as {@link InputStream} or more generally {@link ByteArraySource} to Stream&lt;T&gt;. * * @param <T> - the type of the parsing result */ public interface CSVParser<T> { public default Stream<T> parse(File file) throws IOException { InputStream is = new FileInputStream(file);
return parse(is).onClose(() -> IOUtils.closeQuietly(is));
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/parser/ByteArrayField.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/Decoder.java // public class Decoder { // // private final uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser doubleParser; // private final Charset charset; // private final IntParser intParser; // private final LongParser longParser; // // public Decoder(Charset charset) { // this.charset = charset; // ParserFactory parserFactory = new ParserFactory(); // this.doubleParser = parserFactory.getDoubleParser(); // this.intParser = parserFactory.getIntParser(); // this.longParser = parserFactory.getLongParser(); // } // // public String decodeToString(byte[] buffer, int offset, int length) { // return new String(buffer, offset, length, charset); // } // // public double decodeToDouble(byte[] buffer, int offset, int length) { // if (length == 0) return 0.0; // return doubleParser.parse(buffer, offset, length); // } // // public int decodeToInt(byte[] buffer, int offset, int length) { // if (length == 0) return 0; // return intParser.parse(buffer, offset, length); // } // // public long decodeToLong(byte[] buffer, int offset, int length) { // if (length == 0) return 0L; // return longParser.parse(buffer, offset, length); // } // // public Charset getCharset() { // return charset; // } // }
import java.nio.ByteBuffer; import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.decoder.Decoder;
package uk.elementarysoftware.quickcsv.parser; public class ByteArrayField implements Field { public static final ByteArrayField EMPTY = new ByteArrayField(new byte[0], 0, 0, null);
// Path: src/main/java/uk/elementarysoftware/quickcsv/api/Field.java // public interface Field { // // public ByteBuffer raw(); // // public String asString(); // // public double asDouble(); // public byte asByte(); // public char asChar(); // public short asShort(); // public int asInt(); // public long asLong(); // // public Integer asBoxedInt(); // public Double asBoxedDouble(); // // public boolean isEmpty(); // // public Field clone(); // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/Decoder.java // public class Decoder { // // private final uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser doubleParser; // private final Charset charset; // private final IntParser intParser; // private final LongParser longParser; // // public Decoder(Charset charset) { // this.charset = charset; // ParserFactory parserFactory = new ParserFactory(); // this.doubleParser = parserFactory.getDoubleParser(); // this.intParser = parserFactory.getIntParser(); // this.longParser = parserFactory.getLongParser(); // } // // public String decodeToString(byte[] buffer, int offset, int length) { // return new String(buffer, offset, length, charset); // } // // public double decodeToDouble(byte[] buffer, int offset, int length) { // if (length == 0) return 0.0; // return doubleParser.parse(buffer, offset, length); // } // // public int decodeToInt(byte[] buffer, int offset, int length) { // if (length == 0) return 0; // return intParser.parse(buffer, offset, length); // } // // public long decodeToLong(byte[] buffer, int offset, int length) { // if (length == 0) return 0L; // return longParser.parse(buffer, offset, length); // } // // public Charset getCharset() { // return charset; // } // } // Path: src/main/java/uk/elementarysoftware/quickcsv/parser/ByteArrayField.java import java.nio.ByteBuffer; import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.api.Field; import uk.elementarysoftware.quickcsv.decoder.Decoder; package uk.elementarysoftware.quickcsv.parser; public class ByteArrayField implements Field { public static final ByteArrayField EMPTY = new ByteArrayField(new byte[0], 0, 0, null);
private final Decoder decoder;
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/decoder/Decoder.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/IntParser.java // public interface IntParser { // public int parse(byte[] in, int startIndex, int length); // // default public int parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/LongParser.java // public interface LongParser { // public long parse(byte[] in, int startIndex, int length); // // default public long parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.decoder.ints.IntParser; import uk.elementarysoftware.quickcsv.decoder.ints.LongParser;
package uk.elementarysoftware.quickcsv.decoder; public class Decoder { private final uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser doubleParser; private final Charset charset;
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/IntParser.java // public interface IntParser { // public int parse(byte[] in, int startIndex, int length); // // default public int parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/LongParser.java // public interface LongParser { // public long parse(byte[] in, int startIndex, int length); // // default public long parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/Decoder.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.decoder.ints.IntParser; import uk.elementarysoftware.quickcsv.decoder.ints.LongParser; package uk.elementarysoftware.quickcsv.decoder; public class Decoder { private final uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser doubleParser; private final Charset charset;
private final IntParser intParser;
titorenko/quick-csv-streamer
src/main/java/uk/elementarysoftware/quickcsv/decoder/Decoder.java
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/IntParser.java // public interface IntParser { // public int parse(byte[] in, int startIndex, int length); // // default public int parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/LongParser.java // public interface LongParser { // public long parse(byte[] in, int startIndex, int length); // // default public long parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // }
import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.decoder.ints.IntParser; import uk.elementarysoftware.quickcsv.decoder.ints.LongParser;
package uk.elementarysoftware.quickcsv.decoder; public class Decoder { private final uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser doubleParser; private final Charset charset; private final IntParser intParser;
// Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/IntParser.java // public interface IntParser { // public int parse(byte[] in, int startIndex, int length); // // default public int parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/ints/LongParser.java // public interface LongParser { // public long parse(byte[] in, int startIndex, int length); // // default public long parse(String s) { // return parse(s.getBytes(), 0, s.length()); // }; // } // Path: src/main/java/uk/elementarysoftware/quickcsv/decoder/Decoder.java import java.nio.charset.Charset; import uk.elementarysoftware.quickcsv.decoder.ints.IntParser; import uk.elementarysoftware.quickcsv.decoder.ints.LongParser; package uk.elementarysoftware.quickcsv.decoder; public class Decoder { private final uk.elementarysoftware.quickcsv.decoder.doubles.DoubleParser doubleParser; private final Charset charset; private final IntParser intParser;
private final LongParser longParser;
dogriffiths/hipster
src/dg/hipster/controller/FloatingPanelController.java
// Path: src/dg/hipster/view/FloatingPanel.java // public final class FloatingPanel extends JPanel { // /** // * 63 per cent transparent black. Used for background // * of the map area, and all over-laid panes. // */ // private static Color SHADED = new Color(0, 0, 0, 95); // /** // * Completely transparent. // */ // private static Color CLEAR = new Color(0, 0, 0, 0); // /** // * Section of the pane that content should be // * added to. // */ // private JPanel contentPane; // /** // * Text that will appear at the top of the panel. // */ // private JLabel caption; // /** // * Object handling the interaction logic of this // * panel. // */ // private FloatingPanelController controller; // /** // * Radius of the corners. // */ // private static int RADIUS = 20; // /** // * Edges of the panel. // */ // private Shape boundary; // // /** // * Default constructor. // */ // FloatingPanel() { // setBackground(new Color(0, 0, 0, 0)); // controller = new FloatingPanelController(this); // SpringLayout layout = new SpringLayout(); // this.setLayout(layout); // caption = new JLabel("Test"); // caption.setBackground(SHADED); // caption.setForeground(Color.WHITE); // this.add(caption); // contentPane = new JPanel(); // contentPane.setBackground(CLEAR); // contentPane.setForeground(Color.WHITE); // this.add(contentPane); // layout.putConstraint(SpringLayout.WEST, caption, 3, // SpringLayout.WEST, this); // layout.putConstraint(SpringLayout.NORTH, caption, 3, // SpringLayout.NORTH, this); // layout.putConstraint(SpringLayout.NORTH, contentPane, 3, // SpringLayout.SOUTH, caption); // layout.putConstraint(SpringLayout.WEST, contentPane, 3, // SpringLayout.WEST, this); // } // // /** // * Text that will appear at the top of the panel. // * @param text string to use at the top of the panel. // */ // public void setCaption(String text) { // caption.setText(text); // } // // /** // * Text that will appear at the top of the panel. // * @return text at the top of the panel. // */ // public String getCaption() { // return caption.getText(); // } // // /** // * Draw the component on the given graphics object. // * @param g object to draw on. // */ // public void paintComponent(Graphics g) { // if (getBoundary() != null) { // ((Graphics2D)g).clip(getBoundary()); // } // g.setColor(SHADED); // Dimension size = getSize(); // g.fillRect(0, 0, size.width, size.height); // g.setColor(Color.GRAY); // g.drawLine(0, 0, size.width, 0); // g.setColor(Color.BLACK); // g.drawLine(0, size.height - 1, size.width, size.height - 1); // } // // /** // * Resize the panel, depending upon the size // * of the content. // */ // public void auto() { // Dimension panSize = contentPane.getPreferredSize(); // setSize(panSize.width + 6, panSize.height + 25); // } // // /** // * Resize the panel. // * @param width new width. // * @param height new height. // */ // public void setSize(int width, int height) { // super.setSize(width, height); // boundary = new RoundRectangle2D.Double(0, 0, width, height, RADIUS, // RADIUS); // } // // /** // * Section of the pane that content should be // * added to. // * @return panel that component should be added to. // */ // public JPanel getContentPane() { // return contentPane; // } // // /** // * Outline boundary of the panel. // * @return boundary. // */ // public Shape getBoundary() { // return boundary; // } // }
import dg.hipster.view.FloatingPanel; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener;
/* * FloatingPanelController.java * * Created on October 4, 2006, 8:06 PM * * Copyright (c) 2006, David Griffiths * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this Vector of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this Vector of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the David Griffiths nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package dg.hipster.controller; /** * Object to control the interactions with a * floting panel. * @author davidg */ public final class FloatingPanelController implements MouseListener, MouseMotionListener { /** * Floating panel being controlled. */
// Path: src/dg/hipster/view/FloatingPanel.java // public final class FloatingPanel extends JPanel { // /** // * 63 per cent transparent black. Used for background // * of the map area, and all over-laid panes. // */ // private static Color SHADED = new Color(0, 0, 0, 95); // /** // * Completely transparent. // */ // private static Color CLEAR = new Color(0, 0, 0, 0); // /** // * Section of the pane that content should be // * added to. // */ // private JPanel contentPane; // /** // * Text that will appear at the top of the panel. // */ // private JLabel caption; // /** // * Object handling the interaction logic of this // * panel. // */ // private FloatingPanelController controller; // /** // * Radius of the corners. // */ // private static int RADIUS = 20; // /** // * Edges of the panel. // */ // private Shape boundary; // // /** // * Default constructor. // */ // FloatingPanel() { // setBackground(new Color(0, 0, 0, 0)); // controller = new FloatingPanelController(this); // SpringLayout layout = new SpringLayout(); // this.setLayout(layout); // caption = new JLabel("Test"); // caption.setBackground(SHADED); // caption.setForeground(Color.WHITE); // this.add(caption); // contentPane = new JPanel(); // contentPane.setBackground(CLEAR); // contentPane.setForeground(Color.WHITE); // this.add(contentPane); // layout.putConstraint(SpringLayout.WEST, caption, 3, // SpringLayout.WEST, this); // layout.putConstraint(SpringLayout.NORTH, caption, 3, // SpringLayout.NORTH, this); // layout.putConstraint(SpringLayout.NORTH, contentPane, 3, // SpringLayout.SOUTH, caption); // layout.putConstraint(SpringLayout.WEST, contentPane, 3, // SpringLayout.WEST, this); // } // // /** // * Text that will appear at the top of the panel. // * @param text string to use at the top of the panel. // */ // public void setCaption(String text) { // caption.setText(text); // } // // /** // * Text that will appear at the top of the panel. // * @return text at the top of the panel. // */ // public String getCaption() { // return caption.getText(); // } // // /** // * Draw the component on the given graphics object. // * @param g object to draw on. // */ // public void paintComponent(Graphics g) { // if (getBoundary() != null) { // ((Graphics2D)g).clip(getBoundary()); // } // g.setColor(SHADED); // Dimension size = getSize(); // g.fillRect(0, 0, size.width, size.height); // g.setColor(Color.GRAY); // g.drawLine(0, 0, size.width, 0); // g.setColor(Color.BLACK); // g.drawLine(0, size.height - 1, size.width, size.height - 1); // } // // /** // * Resize the panel, depending upon the size // * of the content. // */ // public void auto() { // Dimension panSize = contentPane.getPreferredSize(); // setSize(panSize.width + 6, panSize.height + 25); // } // // /** // * Resize the panel. // * @param width new width. // * @param height new height. // */ // public void setSize(int width, int height) { // super.setSize(width, height); // boundary = new RoundRectangle2D.Double(0, 0, width, height, RADIUS, // RADIUS); // } // // /** // * Section of the pane that content should be // * added to. // * @return panel that component should be added to. // */ // public JPanel getContentPane() { // return contentPane; // } // // /** // * Outline boundary of the panel. // * @return boundary. // */ // public Shape getBoundary() { // return boundary; // } // } // Path: src/dg/hipster/controller/FloatingPanelController.java import dg.hipster.view.FloatingPanel; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; /* * FloatingPanelController.java * * Created on October 4, 2006, 8:06 PM * * Copyright (c) 2006, David Griffiths * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this Vector of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this Vector of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the David Griffiths nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package dg.hipster.controller; /** * Object to control the interactions with a * floting panel. * @author davidg */ public final class FloatingPanelController implements MouseListener, MouseMotionListener { /** * Floating panel being controlled. */
private FloatingPanel floatingPanel;
dogriffiths/hipster
src/dg/hipster/io/ReaderFactory.java
// Path: src/dg/hipster/model/IdeaDocument.java // public class IdeaDocument extends AbstractModel implements IdeaListener { // /** // * Internationalization strings. // */ // protected static ResourceBundle resBundle = ResourceBundle.getBundle( // "dg/hipster/resource/strings"); // /** // * Undo controller. // */ // private UndoManager undoManager = new UndoManager(); // // private Idea idea; // private File currentFile; // private boolean dirty; // private String title; // private boolean needsAdjustment; // private Idea selected; // // public IdeaDocument() { // this.setCurrentFile(null); // setTitle("Untitled"); // this.setIdea(new Idea(this.getTitle())); // this.setDirty(false); // this.setSelected(this.getIdea()); // } // // public void setIdea(Idea newIdea) { // Idea oldIdea = this.idea; // if (oldIdea != null) { // oldIdea.removeIdeaListener(this); // } // this.idea = newIdea; // if (this.idea != null) { // newIdea.addIdeaListener(this); // } // undoManager.setIdea(newIdea); // firePropertyChange("idea", oldIdea, this.idea); // setSelected(newIdea); // } // // public Idea getIdea() { // return this.idea; // } // // public File getCurrentFile() { // return currentFile; // } // // public void setCurrentFile(File newCurrentFile) { // File oldFile = this.currentFile; // this.currentFile = newCurrentFile; // if (this.currentFile == null) { // this.setTitle(resBundle.getString("untitled")); // } else { // this.setTitle(newCurrentFile.getAbsolutePath()); // } // firePropertyChange("currentFile", oldFile, this.currentFile); // } // // public boolean isDirty() { // return dirty; // } // // public void setDirty(boolean dirty) { // boolean oldDirty = this.dirty; // this.dirty = dirty; // firePropertyChange("dirty", oldDirty, this.dirty); // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String newTitle) { // String oldTitle = this.title; // this.title = newTitle; // firePropertyChange("title", oldTitle, this.title); // } // // public void ideaChanged(IdeaEvent ideaEvent) { // this.setDirty(true); // if (this.currentFile == null) { // setTitle(this.getIdea().getText()); // } // setNeedsAdjustment(true); // } // // public void setNeedsAdjustment(boolean adjustment) { // this.needsAdjustment = adjustment; // } // // public boolean isNeedsAdjustment() { // return this.needsAdjustment; // } // // public Idea getSelected() { // return selected; // } // // public void setSelected(Idea newSelected) { // Idea oldSelected = this.selected; // if (this.selected != null) { // this.selected.setSelected(false); // } // this.selected = newSelected; // if (this.selected != null) { // this.selected.setSelected(true); // } // firePropertyChange("selected", oldSelected, this.selected); // } // // /** // * Delete the currently selected idea (and consequently // * its child ideas). // */ // public void deleteSelected() { // if (selected == null) { // return; // } // Idea parent = this.idea.getParentFor(selected); // if (parent == null) { // return; // } // if (selected instanceof IdeaLink) { // parent.removeLink((IdeaLink)selected); // this.setSelected(parent); // return; // } // Idea nextToSelect = null; // Idea nextSibling = getNextSibling(selected); // Idea previousSibling = getPreviousSibling(selected); // if (nextSibling != null) { // nextToSelect = nextSibling; // } else if (previousSibling != null) { // nextToSelect = previousSibling; // } else { // nextToSelect = parent; // } // parent.remove(selected); // this.setSelected(nextToSelect); // } // // public Idea getPreviousSibling(Idea i) { // return getSibling(i, -1); // } // // public Idea getNextSibling(Idea i) { // return getSibling(i, +1); // } // // public Idea getSibling(Idea i, int difference) { // Idea parent = idea.getParentFor(i); // if (parent == null) { // return null; // } // int pos = parent.getSubIdeas().indexOf(i); // int subCount = parent.getSubIdeas().size(); // int diff = difference % subCount; // int siblingPos = pos + diff; // if ((diff == 0) || (siblingPos < 0) || (siblingPos > (subCount - 1))) { // return null; // } // siblingPos = (siblingPos + subCount) % subCount; // return parent.getSubIdeas().get(siblingPos); // } // // /** // * Undo the last change. // */ // public void undo() { // if (undoManager != null) { // undoManager.undo(); // this.setSelected(null); // } // } // // /** // * Redo the last change undone. // */ // public void redo() { // if (undoManager != null) { // undoManager.redo(); // this.setSelected(null); // } // } // }
import dg.hipster.model.IdeaDocument; import java.io.File; import java.io.FileInputStream;
/* * ReaderFactory.java * * Created on August 27, 2006, 11:38 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package dg.hipster.io; /** * * @author davidg */ public final class ReaderFactory { private static ReaderFactory instance = new ReaderFactory(); /** Creates a new instance of ReaderFactory */ private ReaderFactory() { } public static ReaderFactory getInstance() { return instance; }
// Path: src/dg/hipster/model/IdeaDocument.java // public class IdeaDocument extends AbstractModel implements IdeaListener { // /** // * Internationalization strings. // */ // protected static ResourceBundle resBundle = ResourceBundle.getBundle( // "dg/hipster/resource/strings"); // /** // * Undo controller. // */ // private UndoManager undoManager = new UndoManager(); // // private Idea idea; // private File currentFile; // private boolean dirty; // private String title; // private boolean needsAdjustment; // private Idea selected; // // public IdeaDocument() { // this.setCurrentFile(null); // setTitle("Untitled"); // this.setIdea(new Idea(this.getTitle())); // this.setDirty(false); // this.setSelected(this.getIdea()); // } // // public void setIdea(Idea newIdea) { // Idea oldIdea = this.idea; // if (oldIdea != null) { // oldIdea.removeIdeaListener(this); // } // this.idea = newIdea; // if (this.idea != null) { // newIdea.addIdeaListener(this); // } // undoManager.setIdea(newIdea); // firePropertyChange("idea", oldIdea, this.idea); // setSelected(newIdea); // } // // public Idea getIdea() { // return this.idea; // } // // public File getCurrentFile() { // return currentFile; // } // // public void setCurrentFile(File newCurrentFile) { // File oldFile = this.currentFile; // this.currentFile = newCurrentFile; // if (this.currentFile == null) { // this.setTitle(resBundle.getString("untitled")); // } else { // this.setTitle(newCurrentFile.getAbsolutePath()); // } // firePropertyChange("currentFile", oldFile, this.currentFile); // } // // public boolean isDirty() { // return dirty; // } // // public void setDirty(boolean dirty) { // boolean oldDirty = this.dirty; // this.dirty = dirty; // firePropertyChange("dirty", oldDirty, this.dirty); // } // // public String getTitle() { // return this.title; // } // // public void setTitle(String newTitle) { // String oldTitle = this.title; // this.title = newTitle; // firePropertyChange("title", oldTitle, this.title); // } // // public void ideaChanged(IdeaEvent ideaEvent) { // this.setDirty(true); // if (this.currentFile == null) { // setTitle(this.getIdea().getText()); // } // setNeedsAdjustment(true); // } // // public void setNeedsAdjustment(boolean adjustment) { // this.needsAdjustment = adjustment; // } // // public boolean isNeedsAdjustment() { // return this.needsAdjustment; // } // // public Idea getSelected() { // return selected; // } // // public void setSelected(Idea newSelected) { // Idea oldSelected = this.selected; // if (this.selected != null) { // this.selected.setSelected(false); // } // this.selected = newSelected; // if (this.selected != null) { // this.selected.setSelected(true); // } // firePropertyChange("selected", oldSelected, this.selected); // } // // /** // * Delete the currently selected idea (and consequently // * its child ideas). // */ // public void deleteSelected() { // if (selected == null) { // return; // } // Idea parent = this.idea.getParentFor(selected); // if (parent == null) { // return; // } // if (selected instanceof IdeaLink) { // parent.removeLink((IdeaLink)selected); // this.setSelected(parent); // return; // } // Idea nextToSelect = null; // Idea nextSibling = getNextSibling(selected); // Idea previousSibling = getPreviousSibling(selected); // if (nextSibling != null) { // nextToSelect = nextSibling; // } else if (previousSibling != null) { // nextToSelect = previousSibling; // } else { // nextToSelect = parent; // } // parent.remove(selected); // this.setSelected(nextToSelect); // } // // public Idea getPreviousSibling(Idea i) { // return getSibling(i, -1); // } // // public Idea getNextSibling(Idea i) { // return getSibling(i, +1); // } // // public Idea getSibling(Idea i, int difference) { // Idea parent = idea.getParentFor(i); // if (parent == null) { // return null; // } // int pos = parent.getSubIdeas().indexOf(i); // int subCount = parent.getSubIdeas().size(); // int diff = difference % subCount; // int siblingPos = pos + diff; // if ((diff == 0) || (siblingPos < 0) || (siblingPos > (subCount - 1))) { // return null; // } // siblingPos = (siblingPos + subCount) % subCount; // return parent.getSubIdeas().get(siblingPos); // } // // /** // * Undo the last change. // */ // public void undo() { // if (undoManager != null) { // undoManager.undo(); // this.setSelected(null); // } // } // // /** // * Redo the last change undone. // */ // public void redo() { // if (undoManager != null) { // undoManager.redo(); // this.setSelected(null); // } // } // } // Path: src/dg/hipster/io/ReaderFactory.java import dg.hipster.model.IdeaDocument; import java.io.File; import java.io.FileInputStream; /* * ReaderFactory.java * * Created on August 27, 2006, 11:38 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package dg.hipster.io; /** * * @author davidg */ public final class ReaderFactory { private static ReaderFactory instance = new ReaderFactory(); /** Creates a new instance of ReaderFactory */ private ReaderFactory() { } public static ReaderFactory getInstance() { return instance; }
public IdeaDocument read(File f) throws ReaderException {
dogriffiths/hipster
src/dg/hipster/view/FloatingPanel.java
// Path: src/dg/hipster/controller/FloatingPanelController.java // public final class FloatingPanelController implements MouseListener, // MouseMotionListener { // /** // * Floating panel being controlled. // */ // private FloatingPanel floatingPanel; // /** // * Point where the mouse was last pressed. // */ // private Point downPoint; // /** // * Where the floating panel was positioned relative // * to its parent, when the mouse was first clicked. // */ // private Point start; // // /** // * Constructor for a controller of a given floating // * panel. // * @param aFloatingPanel panel to control. // */ // public FloatingPanelController(final FloatingPanel aFloatingPanel) { // this.floatingPanel = aFloatingPanel; // this.floatingPanel.addMouseListener(this); // this.floatingPanel.addMouseMotionListener(this); // } // // /** // * Called when a mouse enters the panel. // * @param evt mouse event describing the mouse entry. // */ // public void mouseEntered(final MouseEvent evt) { // } // // /** // * Called when a mouse exits the panel. // * @param evt mouse event describing the mouse exit. // */ // public void mouseExited(final MouseEvent evt) { // } // // /** // * Called when a mouse is pressed and released // * at a point on the panel. // * @param evt mouse event describing the mouse click. // */ // public void mouseClicked(final MouseEvent evt) { // } // // /** // * Called when a mouse moves over the panel. // * @param evt mouse event describing the mouse move. // */ // public void mouseMoved(final MouseEvent evt) { // } // // /** // * Called when a mouse is released over the panel. // * @param evt mouse event describing the mouse release. // */ // public void mouseReleased(final MouseEvent evt) { // downPoint = null; // } // // /** // * Called when a mouse is pressed on the panel. // * @param evt mouse event describing the mouse press. // */ // public void mousePressed(final MouseEvent evt) { // downPoint = evt.getPoint(); // if (!this.floatingPanel.getBoundary().contains(downPoint)) { // downPoint = null; // return; // } // start = this.floatingPanel.getLocation(); // downPoint.x += start.x; // downPoint.y += start.y; // } // // /** // * Called when a mouse is dragged over the panel. // * @param evt mouse event describing the mouse drag. // */ // public void mouseDragged(final MouseEvent evt) { // if (downPoint == null) { // return; // } // Point p = evt.getPoint(); // Point s = this.floatingPanel.getLocation(); // int xDiff = s.x + p.x - downPoint.x; // int yDiff = s.y + p.y - downPoint.y; // this.floatingPanel.setLocation(new Point(start.x + xDiff, // start.y + yDiff)); // } // }
import dg.hipster.controller.FloatingPanelController; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SpringLayout;
/* * FloatingPanel.java * * Created on October 4, 2006, 8:04 PM * * Copyright (c) 2006, David Griffiths * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this Vector of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this Vector of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the David Griffiths nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package dg.hipster.view; /** * Floating transparent panel that is used in the map area. * * @author davidg */ public final class FloatingPanel extends JPanel { /** * 63 per cent transparent black. Used for background * of the map area, and all over-laid panes. */ private static Color SHADED = new Color(0, 0, 0, 95); /** * Completely transparent. */ private static Color CLEAR = new Color(0, 0, 0, 0); /** * Section of the pane that content should be * added to. */ private JPanel contentPane; /** * Text that will appear at the top of the panel. */ private JLabel caption; /** * Object handling the interaction logic of this * panel. */
// Path: src/dg/hipster/controller/FloatingPanelController.java // public final class FloatingPanelController implements MouseListener, // MouseMotionListener { // /** // * Floating panel being controlled. // */ // private FloatingPanel floatingPanel; // /** // * Point where the mouse was last pressed. // */ // private Point downPoint; // /** // * Where the floating panel was positioned relative // * to its parent, when the mouse was first clicked. // */ // private Point start; // // /** // * Constructor for a controller of a given floating // * panel. // * @param aFloatingPanel panel to control. // */ // public FloatingPanelController(final FloatingPanel aFloatingPanel) { // this.floatingPanel = aFloatingPanel; // this.floatingPanel.addMouseListener(this); // this.floatingPanel.addMouseMotionListener(this); // } // // /** // * Called when a mouse enters the panel. // * @param evt mouse event describing the mouse entry. // */ // public void mouseEntered(final MouseEvent evt) { // } // // /** // * Called when a mouse exits the panel. // * @param evt mouse event describing the mouse exit. // */ // public void mouseExited(final MouseEvent evt) { // } // // /** // * Called when a mouse is pressed and released // * at a point on the panel. // * @param evt mouse event describing the mouse click. // */ // public void mouseClicked(final MouseEvent evt) { // } // // /** // * Called when a mouse moves over the panel. // * @param evt mouse event describing the mouse move. // */ // public void mouseMoved(final MouseEvent evt) { // } // // /** // * Called when a mouse is released over the panel. // * @param evt mouse event describing the mouse release. // */ // public void mouseReleased(final MouseEvent evt) { // downPoint = null; // } // // /** // * Called when a mouse is pressed on the panel. // * @param evt mouse event describing the mouse press. // */ // public void mousePressed(final MouseEvent evt) { // downPoint = evt.getPoint(); // if (!this.floatingPanel.getBoundary().contains(downPoint)) { // downPoint = null; // return; // } // start = this.floatingPanel.getLocation(); // downPoint.x += start.x; // downPoint.y += start.y; // } // // /** // * Called when a mouse is dragged over the panel. // * @param evt mouse event describing the mouse drag. // */ // public void mouseDragged(final MouseEvent evt) { // if (downPoint == null) { // return; // } // Point p = evt.getPoint(); // Point s = this.floatingPanel.getLocation(); // int xDiff = s.x + p.x - downPoint.x; // int yDiff = s.y + p.y - downPoint.y; // this.floatingPanel.setLocation(new Point(start.x + xDiff, // start.y + yDiff)); // } // } // Path: src/dg/hipster/view/FloatingPanel.java import dg.hipster.controller.FloatingPanelController; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SpringLayout; /* * FloatingPanel.java * * Created on October 4, 2006, 8:04 PM * * Copyright (c) 2006, David Griffiths * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this Vector of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this Vector of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the David Griffiths nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package dg.hipster.view; /** * Floating transparent panel that is used in the map area. * * @author davidg */ public final class FloatingPanel extends JPanel { /** * 63 per cent transparent black. Used for background * of the map area, and all over-laid panes. */ private static Color SHADED = new Color(0, 0, 0, 95); /** * Completely transparent. */ private static Color CLEAR = new Color(0, 0, 0, 0); /** * Section of the pane that content should be * added to. */ private JPanel contentPane; /** * Text that will appear at the top of the panel. */ private JLabel caption; /** * Object handling the interaction logic of this * panel. */
private FloatingPanelController controller;
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 2/28/16. */ public class SpacingAdapter extends SimpleRecyclerViewAdapter { public SpacingAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 2/28/16. */ public class SpacingAdapter extends SimpleRecyclerViewAdapter { public SpacingAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new FooterHolder(inflater, parent, R.layout.item_spacing);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 2/28/16. */ public class SpacingAdapter extends SimpleRecyclerViewAdapter { public SpacingAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.item_spacing); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 2/28/16. */ public class SpacingAdapter extends SimpleRecyclerViewAdapter { public SpacingAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.item_spacing); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new HeaderHolder(inflater, parent, R.layout.item_spacing);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/fragment/NestedWrapperAdapterFragment.java
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java // public class SpacingAdapter extends SimpleRecyclerViewAdapter { // // public SpacingAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.item_spacing); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.item_spacing); // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; import me.henrytao.sample.adapter.SpacingAdapter;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class NestedWrapperAdapterFragment extends Fragment { public static NestedWrapperAdapterFragment newInstance() { return new NestedWrapperAdapterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView;
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java // public class SpacingAdapter extends SimpleRecyclerViewAdapter { // // public SpacingAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.item_spacing); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.item_spacing); // } // } // Path: sample/src/main/java/me/henrytao/sample/fragment/NestedWrapperAdapterFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; import me.henrytao.sample.adapter.SpacingAdapter; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class NestedWrapperAdapterFragment extends Fragment { public static NestedWrapperAdapterFragment newInstance() { return new NestedWrapperAdapterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView;
private SimpleAdapter mSimpleAdapter;
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/fragment/NestedWrapperAdapterFragment.java
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java // public class SpacingAdapter extends SimpleRecyclerViewAdapter { // // public SpacingAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.item_spacing); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.item_spacing); // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; import me.henrytao.sample.adapter.SpacingAdapter;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class NestedWrapperAdapterFragment extends Fragment { public static NestedWrapperAdapterFragment newInstance() { return new NestedWrapperAdapterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView; private SimpleAdapter mSimpleAdapter; public NestedWrapperAdapterFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_simple, container, false); ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSimpleAdapter = new SimpleAdapter();
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java // public class SpacingAdapter extends SimpleRecyclerViewAdapter { // // public SpacingAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.item_spacing); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.item_spacing); // } // } // Path: sample/src/main/java/me/henrytao/sample/fragment/NestedWrapperAdapterFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; import me.henrytao.sample.adapter.SpacingAdapter; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class NestedWrapperAdapterFragment extends Fragment { public static NestedWrapperAdapterFragment newInstance() { return new NestedWrapperAdapterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView; private SimpleAdapter mSimpleAdapter; public NestedWrapperAdapterFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_simple, container, false); ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSimpleAdapter = new SimpleAdapter();
RecyclerView.Adapter adapter = new SpacingAdapter(new HeaderFooterAdapter(mSimpleAdapter));
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/fragment/NestedWrapperAdapterFragment.java
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java // public class SpacingAdapter extends SimpleRecyclerViewAdapter { // // public SpacingAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.item_spacing); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.item_spacing); // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; import me.henrytao.sample.adapter.SpacingAdapter;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class NestedWrapperAdapterFragment extends Fragment { public static NestedWrapperAdapterFragment newInstance() { return new NestedWrapperAdapterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView; private SimpleAdapter mSimpleAdapter; public NestedWrapperAdapterFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_simple, container, false); ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSimpleAdapter = new SimpleAdapter();
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SpacingAdapter.java // public class SpacingAdapter extends SimpleRecyclerViewAdapter { // // public SpacingAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.item_spacing); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.item_spacing); // } // } // Path: sample/src/main/java/me/henrytao/sample/fragment/NestedWrapperAdapterFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; import me.henrytao.sample.adapter.SpacingAdapter; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class NestedWrapperAdapterFragment extends Fragment { public static NestedWrapperAdapterFragment newInstance() { return new NestedWrapperAdapterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView; private SimpleAdapter mSimpleAdapter; public NestedWrapperAdapterFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_simple, container, false); ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSimpleAdapter = new SimpleAdapter();
RecyclerView.Adapter adapter = new SpacingAdapter(new HeaderFooterAdapter(mSimpleAdapter));
henrytao-me/recyclerview-multistate-section-endless-adapter
recyclerview/src/main/java/me/henrytao/recyclerview/adapter/MultiStateAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/config/Constants.java // public class Constants { // // public enum Type { // HEADER, FOOTER // } // }
import me.henrytao.recyclerview.config.Constants; import me.henrytao.recyclerview.config.Visibility;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.recyclerview.adapter; /** * Created by henrytao on 8/16/15. */ public interface MultiStateAdapter { void addOnVisibilityChanged(OnVisibilityChangedListener onVisibilityChangedListener); @Visibility int getVisibility(int position); @Visibility
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/config/Constants.java // public class Constants { // // public enum Type { // HEADER, FOOTER // } // } // Path: recyclerview/src/main/java/me/henrytao/recyclerview/adapter/MultiStateAdapter.java import me.henrytao.recyclerview.config.Constants; import me.henrytao.recyclerview.config.Visibility; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.recyclerview.adapter; /** * Created by henrytao on 8/16/15. */ public interface MultiStateAdapter { void addOnVisibilityChanged(OnVisibilityChangedListener onVisibilityChangedListener); @Visibility int getVisibility(int position); @Visibility
int getVisibility(int index, Constants.Type type);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
package me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; package me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new FooterHolder(inflater, parent, R.layout.holder_footer);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
package me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.holder_footer); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; package me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { super(baseAdapter); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.holder_footer); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new HeaderHolder(inflater, parent, R.layout.holder_header);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/MultiStateAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class MultiStateAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public MultiStateAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/MultiStateAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class MultiStateAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public MultiStateAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new FooterHolder(inflater, parent, R.layout.holder_footer);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/MultiStateAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class MultiStateAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public MultiStateAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.holder_footer); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/MultiStateAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class MultiStateAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public MultiStateAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.holder_footer); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new HeaderHolder(inflater, parent, R.layout.holder_header);
henrytao-me/recyclerview-multistate-section-endless-adapter
recyclerview/src/main/java/me/henrytao/recyclerview/MergeAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/adapter/BaseAdapterCallback.java // public interface BaseAdapterCallback { // // List<RecyclerView.Adapter> getBaseAdapters(); // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/adapter/ViewTypeManager.java // public class ViewTypeManager { // // private Map<String, Integer> mCache = new HashMap<>(); // // private Map<Integer, Pointer> mCacheReverse = new HashMap<>(); // // private int mCode = 0; // // public Pointer decode(int code) { // if (!mCacheReverse.containsKey(code)) { // return new Pointer(0, 0); // } // return mCacheReverse.get(code); // } // // public int encode(int type, int index) { // String key = String.format(Locale.US, "%d-%d", type, index); // int code; // if (!mCache.containsKey(key)) { // code = getCode(); // mCache.put(key, code); // mCacheReverse.put(code, new Pointer(type, index)); // } else { // code = mCache.get(key); // } // return code; // } // // private int getCode() { // return ++mCode; // } // // public static class Pointer { // // private final int mIndex; // // private final int mType; // // public Pointer(int type, int index) { // mType = type; // mIndex = index; // } // // public int getIndex() { // return mIndex; // } // // public int getType() { // return mType; // } // } // }
import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.henrytao.recyclerview.adapter.BaseAdapterCallback; import me.henrytao.recyclerview.adapter.ViewTypeManager;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.recyclerview; /** * Created by henrytao on 5/30/16. */ public class MergeAdapter extends RecyclerView.Adapter implements BaseAdapterCallback { private final List<AdapterDataObserver> mAdapterDataObservers = new ArrayList<>(); private final List<RecyclerView.Adapter> mAdapters = new ArrayList<>();
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/adapter/BaseAdapterCallback.java // public interface BaseAdapterCallback { // // List<RecyclerView.Adapter> getBaseAdapters(); // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/adapter/ViewTypeManager.java // public class ViewTypeManager { // // private Map<String, Integer> mCache = new HashMap<>(); // // private Map<Integer, Pointer> mCacheReverse = new HashMap<>(); // // private int mCode = 0; // // public Pointer decode(int code) { // if (!mCacheReverse.containsKey(code)) { // return new Pointer(0, 0); // } // return mCacheReverse.get(code); // } // // public int encode(int type, int index) { // String key = String.format(Locale.US, "%d-%d", type, index); // int code; // if (!mCache.containsKey(key)) { // code = getCode(); // mCache.put(key, code); // mCacheReverse.put(code, new Pointer(type, index)); // } else { // code = mCache.get(key); // } // return code; // } // // private int getCode() { // return ++mCode; // } // // public static class Pointer { // // private final int mIndex; // // private final int mType; // // public Pointer(int type, int index) { // mType = type; // mIndex = index; // } // // public int getIndex() { // return mIndex; // } // // public int getType() { // return mType; // } // } // } // Path: recyclerview/src/main/java/me/henrytao/recyclerview/MergeAdapter.java import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import me.henrytao.recyclerview.adapter.BaseAdapterCallback; import me.henrytao.recyclerview.adapter.ViewTypeManager; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.recyclerview; /** * Created by henrytao on 5/30/16. */ public class MergeAdapter extends RecyclerView.Adapter implements BaseAdapterCallback { private final List<AdapterDataObserver> mAdapterDataObservers = new ArrayList<>(); private final List<RecyclerView.Adapter> mAdapters = new ArrayList<>();
private final ViewTypeManager mViewTypeManager = new ViewTypeManager();
henrytao-me/recyclerview-multistate-section-endless-adapter
recyclerview/src/main/java/me/henrytao/recyclerview/adapter/BaseAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/BlankHolder.java // public class BlankHolder extends BaseHolder { // // public BlankHolder(View itemView) { // super(itemView); // } // // public BlankHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public BlankHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Collections; import java.util.List; import me.henrytao.recyclerview.holder.BlankHolder;
return position >= getItemCount(); } public boolean isFooterView(int position) { return getFooterViewIndex(position) >= 0; } public boolean isHeaderView(int position) { return getHeaderViewIndex(position) >= 0; } public boolean isItemView(int position) { return !isHeaderView(position) && !isFooterView(position) && !isBlankView(position); } public void notifyFooterChanged(int index) { int position = getFooterViewPosition(index); if (position >= 0) { notifyItemChanged(position); } } public void notifyHeaderChanged(int index) { int position = getHeaderViewPosition(index); if (position >= 0) { notifyItemChanged(position); } } public RecyclerView.ViewHolder onCreateBlankViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/BlankHolder.java // public class BlankHolder extends BaseHolder { // // public BlankHolder(View itemView) { // super(itemView); // } // // public BlankHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public BlankHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: recyclerview/src/main/java/me/henrytao/recyclerview/adapter/BaseAdapter.java import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Collections; import java.util.List; import me.henrytao.recyclerview.holder.BlankHolder; return position >= getItemCount(); } public boolean isFooterView(int position) { return getFooterViewIndex(position) >= 0; } public boolean isHeaderView(int position) { return getHeaderViewIndex(position) >= 0; } public boolean isItemView(int position) { return !isHeaderView(position) && !isFooterView(position) && !isBlankView(position); } public void notifyFooterChanged(int index) { int position = getFooterViewPosition(index); if (position >= 0) { notifyItemChanged(position); } } public void notifyHeaderChanged(int index) { int position = getHeaderViewPosition(index); if (position >= 0) { notifyItemChanged(position); } } public RecyclerView.ViewHolder onCreateBlankViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new BlankHolder(new View(parent.getContext()));
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/EndlessAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class EndlessAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public EndlessAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/EndlessAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class EndlessAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public EndlessAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new FooterHolder(inflater, parent, R.layout.holder_footer);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/adapter/EndlessAdapter.java
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder;
/* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class EndlessAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public EndlessAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.holder_footer); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
// Path: recyclerview/src/main/java/me/henrytao/recyclerview/SimpleRecyclerViewAdapter.java // public abstract class SimpleRecyclerViewAdapter extends RecyclerViewAdapter { // // public abstract RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent); // // public abstract RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent); // // public SimpleRecyclerViewAdapter(RecyclerView.Adapter baseAdapter) { // super(1, 1, baseAdapter); // } // // @Override // public void onBindFooterViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder, int index) { // // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateFooterViewHolder(inflater, parent); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent, int index) { // return onCreateHeaderViewHolder(inflater, parent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/FooterHolder.java // public class FooterHolder extends BaseHolder { // // public FooterHolder(View itemView) { // super(itemView); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public FooterHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // // Path: recyclerview/src/main/java/me/henrytao/recyclerview/holder/HeaderHolder.java // public class HeaderHolder extends BaseHolder { // // public HeaderHolder(View itemView) { // super(itemView); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId) { // super(inflater, parent, layoutId); // } // // public HeaderHolder(LayoutInflater inflater, ViewGroup parent, @LayoutRes int layoutId, boolean isFillParent) { // super(inflater, parent, layoutId, isFillParent); // } // } // Path: sample/src/main/java/me/henrytao/sample/adapter/EndlessAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.henrytao.me.sample.R; import me.henrytao.recyclerview.SimpleRecyclerViewAdapter; import me.henrytao.recyclerview.holder.FooterHolder; import me.henrytao.recyclerview.holder.HeaderHolder; /* * Copyright 2016 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.adapter; /** * Created by henrytao on 8/16/15. */ public class EndlessAdapter extends SimpleRecyclerViewAdapter { private final OnItemClickListener mOnItemClickListener; public EndlessAdapter(RecyclerView.Adapter baseAdapter, OnItemClickListener onItemClickListener) { super(baseAdapter); mOnItemClickListener = onItemClickListener; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { super.onBindViewHolder(holder, position); holder.itemView.setTag(R.id.tag_position, position); } @Override public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { return new FooterHolder(inflater, parent, R.layout.holder_footer); } @Override public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) {
return new HeaderHolder(inflater, parent, R.layout.holder_header);
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/fragment/HeaderFooterFragment.java
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter;
/* * Copyright 2015 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class HeaderFooterFragment extends Fragment { public static HeaderFooterFragment newInstance() { return new HeaderFooterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView;
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // Path: sample/src/main/java/me/henrytao/sample/fragment/HeaderFooterFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; /* * Copyright 2015 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class HeaderFooterFragment extends Fragment { public static HeaderFooterFragment newInstance() { return new HeaderFooterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView;
private SimpleAdapter mSimpleAdapter;
henrytao-me/recyclerview-multistate-section-endless-adapter
sample/src/main/java/me/henrytao/sample/fragment/HeaderFooterFragment.java
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter;
/* * Copyright 2015 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class HeaderFooterFragment extends Fragment { public static HeaderFooterFragment newInstance() { return new HeaderFooterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView; private SimpleAdapter mSimpleAdapter; public HeaderFooterFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_simple, container, false); ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSimpleAdapter = new SimpleAdapter();
// Path: sample/src/main/java/me/henrytao/sample/adapter/HeaderFooterAdapter.java // public class HeaderFooterAdapter extends SimpleRecyclerViewAdapter { // // public HeaderFooterAdapter(RecyclerView.Adapter baseAdapter) { // super(baseAdapter); // } // // @Override // public RecyclerView.ViewHolder onCreateFooterViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new FooterHolder(inflater, parent, R.layout.holder_footer); // } // // @Override // public RecyclerView.ViewHolder onCreateHeaderViewHolder(LayoutInflater inflater, ViewGroup parent) { // return new HeaderHolder(inflater, parent, R.layout.holder_header); // } // } // // Path: sample/src/main/java/me/henrytao/sample/adapter/SimpleAdapter.java // public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemHolder> { // // private List<Integer> mData; // // public SimpleAdapter() { // mData = new ArrayList<>(); // for (int i = 0; i < 50; i++) { // mData.add(i); // } // } // // public SimpleAdapter(int itemCount) { // mData = new ArrayList<>(); // for (int i = 0; i < itemCount; i++) { // mData.add(i); // } // } // // @Override // public int getItemCount() { // return mData.size(); // } // // @Override // public void onBindViewHolder(SimpleAdapter.ItemHolder holder, int position) { // holder.bind(mData.get(position)); // } // // @Override // public SimpleAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main, parent, false)); // } // // public void addMoreItems(int numOfItems) { // int n = getItemCount(); // for (int i = 0; i < numOfItems; i++) { // mData.add(n++); // } // notifyDataSetChanged(); // } // // public static class ItemHolder extends RecyclerView.ViewHolder { // // @Bind(R.id.title) // TextView vTitle; // // public ItemHolder(View itemView) { // super(itemView); // ButterKnife.bind(this, itemView); // } // // public void bind(int data) { // vTitle.setText(String.format(Locale.US, "Item %d", data)); // } // } // } // Path: sample/src/main/java/me/henrytao/sample/fragment/HeaderFooterFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.Bind; import butterknife.ButterKnife; import me.henrytao.me.sample.R; import me.henrytao.sample.adapter.HeaderFooterAdapter; import me.henrytao.sample.adapter.SimpleAdapter; /* * Copyright 2015 "Henry Tao <[email protected]>" * * 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 me.henrytao.sample.fragment; public class HeaderFooterFragment extends Fragment { public static HeaderFooterFragment newInstance() { return new HeaderFooterFragment(); } @Bind(android.R.id.list) RecyclerView vRecyclerView; private SimpleAdapter mSimpleAdapter; public HeaderFooterFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_simple, container, false); ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mSimpleAdapter = new SimpleAdapter();
RecyclerView.Adapter adapter = new HeaderFooterAdapter(mSimpleAdapter);
doanduyhai/killrvideo-java
src/main/java/killrvideo/entity/VideoRating.java
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // }
import java.io.Serializable; import java.util.Optional; import java.util.UUID; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.ratings.RatingsServiceOuterClass.GetRatingResponse; import killrvideo.utils.TypeConverter;
package killrvideo.entity; /** * Pojo representing DTO for table 'video_ratings'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS_RATINGS) public class VideoRating implements Serializable { /** Serial. */ private static final long serialVersionUID = -8874199914791405808L; @PartitionKey private UUID videoid; @Column(name = "rating_counter") private Long ratingCounter; @Column(name = "rating_total") private Long ratingTotal; /** * Mapping to generated GPRC beans. */ public GetRatingResponse toRatingResponse() { return GetRatingResponse.newBuilder()
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // } // Path: src/main/java/killrvideo/entity/VideoRating.java import java.io.Serializable; import java.util.Optional; import java.util.UUID; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.ratings.RatingsServiceOuterClass.GetRatingResponse; import killrvideo.utils.TypeConverter; package killrvideo.entity; /** * Pojo representing DTO for table 'video_ratings'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS_RATINGS) public class VideoRating implements Serializable { /** Serial. */ private static final long serialVersionUID = -8874199914791405808L; @PartitionKey private UUID videoid; @Column(name = "rating_counter") private Long ratingCounter; @Column(name = "rating_total") private Long ratingTotal; /** * Mapping to generated GPRC beans. */ public GetRatingResponse toRatingResponse() { return GetRatingResponse.newBuilder()
.setVideoId(TypeConverter.uuidToUuid(videoid))
doanduyhai/killrvideo-java
src/main/java/killrvideo/entity/CommentsByVideo.java
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // }
import static java.util.UUID.fromString; import java.io.Serializable; import java.util.Date; import java.util.UUID; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Computed; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.comments.CommentsServiceOuterClass; import killrvideo.comments.CommentsServiceOuterClass.CommentOnVideoRequest; import killrvideo.utils.TypeConverter;
package killrvideo.entity; /** * Pojo representing DTO for table 'comments_by_video' * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_COMMENTS_BY_VIDEO) public class CommentsByVideo implements Serializable { /** Serial. */ private static final long serialVersionUID = -6365600205169278881L; @PartitionKey private UUID videoid; @ClusteringColumn private UUID commentid; @NotNull @Column private UUID userid; @Length(min = 1, message = "The comment must not be empty") @Column private String comment; /** * In order to properly use the @Computed annotation for dateOfComment * you must execute a query using the mapper with this entity, NOT QueryBuilder. * If QueryBuilder is used you must use a call to fcall() and pass the CQL function * needed to it directly. Here is an example pulled from CommentsByVideo.getVideoComments(). * fcall("toTimestamp", QueryBuilder.column("commentid")).as("comment_timestamp") * This will execute the toTimeStamp() function against the commentid column and return the * result with an alias of comment_timestamp. Again, reference CommentService.getUserComments() * or CommentService.getVideoComments() for examples of how to implement. */ @NotNull @Computed("toTimestamp(commentid)") private Date dateOfComment; /** * Default constructor (reflection) */ public CommentsByVideo() {} /** * Constructor with all parameters. */ public CommentsByVideo(UUID videoid, UUID commentid, UUID userid, String comment) { this.videoid = videoid; this.commentid = commentid; this.userid = userid; this.comment = comment; } /** * Constructor from GRPC generated request. */ public CommentsByVideo(CommentOnVideoRequest request) { this.videoid = fromString(request.getVideoId().getValue()); this.commentid = fromString(request.getCommentId().getValue()); this.userid = fromString(request.getUserId().getValue()); this.comment = request.getComment(); } /** * Mapping to GRPC generated classes. */ public CommentsServiceOuterClass.VideoComment toVideoComment() { return CommentsServiceOuterClass.VideoComment .newBuilder() .setComment(comment)
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // } // Path: src/main/java/killrvideo/entity/CommentsByVideo.java import static java.util.UUID.fromString; import java.io.Serializable; import java.util.Date; import java.util.UUID; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Computed; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.comments.CommentsServiceOuterClass; import killrvideo.comments.CommentsServiceOuterClass.CommentOnVideoRequest; import killrvideo.utils.TypeConverter; package killrvideo.entity; /** * Pojo representing DTO for table 'comments_by_video' * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_COMMENTS_BY_VIDEO) public class CommentsByVideo implements Serializable { /** Serial. */ private static final long serialVersionUID = -6365600205169278881L; @PartitionKey private UUID videoid; @ClusteringColumn private UUID commentid; @NotNull @Column private UUID userid; @Length(min = 1, message = "The comment must not be empty") @Column private String comment; /** * In order to properly use the @Computed annotation for dateOfComment * you must execute a query using the mapper with this entity, NOT QueryBuilder. * If QueryBuilder is used you must use a call to fcall() and pass the CQL function * needed to it directly. Here is an example pulled from CommentsByVideo.getVideoComments(). * fcall("toTimestamp", QueryBuilder.column("commentid")).as("comment_timestamp") * This will execute the toTimeStamp() function against the commentid column and return the * result with an alias of comment_timestamp. Again, reference CommentService.getUserComments() * or CommentService.getVideoComments() for examples of how to implement. */ @NotNull @Computed("toTimestamp(commentid)") private Date dateOfComment; /** * Default constructor (reflection) */ public CommentsByVideo() {} /** * Constructor with all parameters. */ public CommentsByVideo(UUID videoid, UUID commentid, UUID userid, String comment) { this.videoid = videoid; this.commentid = commentid; this.userid = userid; this.comment = comment; } /** * Constructor from GRPC generated request. */ public CommentsByVideo(CommentOnVideoRequest request) { this.videoid = fromString(request.getVideoId().getValue()); this.commentid = fromString(request.getCommentId().getValue()); this.userid = fromString(request.getUserId().getValue()); this.comment = request.getComment(); } /** * Mapping to GRPC generated classes. */ public CommentsServiceOuterClass.VideoComment toVideoComment() { return CommentsServiceOuterClass.VideoComment .newBuilder() .setComment(comment)
.setCommentId(TypeConverter.uuidToTimeUuid(commentid))
doanduyhai/killrvideo-java
src/main/java/killrvideo/entity/Video.java
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // }
import java.util.Date; import java.util.Set; import java.util.UUID; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.search.SearchServiceOuterClass.SearchResultsVideoPreview; import killrvideo.search.SearchServiceOuterClass.SearchResultsVideoPreview.Builder; import killrvideo.suggested_videos.SuggestedVideosService.SuggestedVideoPreview; import killrvideo.utils.EmptyCollectionIfNull; import killrvideo.utils.TypeConverter; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.GetVideoResponse; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoLocationType; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoPreview;
package killrvideo.entity; /** * Pojo representing DTO for table 'videos'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS) public class Video extends AbstractVideo { /** Serial. */ private static final long serialVersionUID = 7035802926837646137L; @PartitionKey private UUID videoid; @NotNull @Column private UUID userid; @Length(min = 1, message = "description must not be empty") @Column private String description; @Length(min = 1, message = "location must not be empty") @Column private String location; @Column(name = "location_type") private int locationType; @Column @EmptyCollectionIfNull private Set<String> tags; @NotNull @Column(name = "added_date") private Date addedDate; /** * Default Constructor allowing reflection. */ public Video() {} /** * Constructor wihout location nor preview. */ public Video(UUID videoid, UUID userid, String name, String description, int locationType, Set<String> tags, Date addedDate) { this(videoid, userid, name, description, null, locationType, null, tags, addedDate); } /** * All attributes constructor. */ public Video(UUID videoid, UUID userid, String name, String description, String location, int locationType, String previewImageLocation, Set<String> tags, Date addedDate) { super(name, previewImageLocation); this.videoid = videoid; this.userid = userid; this.description = description; this.location = location; this.locationType = locationType; this.tags = tags; this.addedDate = addedDate; } /** * Mapping to generated GPRC beans (Full detailed) */ public GetVideoResponse toVideoResponse() { final GetVideoResponse videoResponse = GetVideoResponse .newBuilder()
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // } // Path: src/main/java/killrvideo/entity/Video.java import java.util.Date; import java.util.Set; import java.util.UUID; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.search.SearchServiceOuterClass.SearchResultsVideoPreview; import killrvideo.search.SearchServiceOuterClass.SearchResultsVideoPreview.Builder; import killrvideo.suggested_videos.SuggestedVideosService.SuggestedVideoPreview; import killrvideo.utils.EmptyCollectionIfNull; import killrvideo.utils.TypeConverter; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.GetVideoResponse; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoLocationType; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoPreview; package killrvideo.entity; /** * Pojo representing DTO for table 'videos'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS) public class Video extends AbstractVideo { /** Serial. */ private static final long serialVersionUID = 7035802926837646137L; @PartitionKey private UUID videoid; @NotNull @Column private UUID userid; @Length(min = 1, message = "description must not be empty") @Column private String description; @Length(min = 1, message = "location must not be empty") @Column private String location; @Column(name = "location_type") private int locationType; @Column @EmptyCollectionIfNull private Set<String> tags; @NotNull @Column(name = "added_date") private Date addedDate; /** * Default Constructor allowing reflection. */ public Video() {} /** * Constructor wihout location nor preview. */ public Video(UUID videoid, UUID userid, String name, String description, int locationType, Set<String> tags, Date addedDate) { this(videoid, userid, name, description, null, locationType, null, tags, addedDate); } /** * All attributes constructor. */ public Video(UUID videoid, UUID userid, String name, String description, String location, int locationType, String previewImageLocation, Set<String> tags, Date addedDate) { super(name, previewImageLocation); this.videoid = videoid; this.userid = userid; this.description = description; this.location = location; this.locationType = locationType; this.tags = tags; this.addedDate = addedDate; } /** * Mapping to generated GPRC beans (Full detailed) */ public GetVideoResponse toVideoResponse() { final GetVideoResponse videoResponse = GetVideoResponse .newBuilder()
.setAddedDate(TypeConverter.dateToTimestamp(addedDate))
doanduyhai/killrvideo-java
src/main/java/killrvideo/entity/LatestVideos.java
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // }
import java.util.Date; import java.util.Optional; import java.util.UUID; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.utils.TypeConverter; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoPreview;
package killrvideo.entity; /** * Pojo representing DTO for table 'latest_videos' * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_LATEST_VIDEOS) public class LatestVideos extends AbstractVideoList { /** Serial. */ private static final long serialVersionUID = -8527565276521920973L; @PartitionKey private String yyyymmdd; @Column private UUID userid; /** * Default constructor. */ public LatestVideos() {} /** * Constructor with all parameters. */ public LatestVideos(String yyyymmdd, UUID userid, UUID videoid, String name, String previewImageLocation, Date addedDate) { super(name, previewImageLocation, addedDate, videoid); this.yyyymmdd = yyyymmdd; this.userid = userid; } /** * Mapping to GRPC generated classes. */ public VideoPreview toVideoPreview() { return VideoPreview .newBuilder()
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // } // Path: src/main/java/killrvideo/entity/LatestVideos.java import java.util.Date; import java.util.Optional; import java.util.UUID; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.utils.TypeConverter; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoPreview; package killrvideo.entity; /** * Pojo representing DTO for table 'latest_videos' * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_LATEST_VIDEOS) public class LatestVideos extends AbstractVideoList { /** Serial. */ private static final long serialVersionUID = -8527565276521920973L; @PartitionKey private String yyyymmdd; @Column private UUID userid; /** * Default constructor. */ public LatestVideos() {} /** * Constructor with all parameters. */ public LatestVideos(String yyyymmdd, UUID userid, UUID videoid, String name, String previewImageLocation, Date addedDate) { super(name, previewImageLocation, addedDate, videoid); this.yyyymmdd = yyyymmdd; this.userid = userid; } /** * Mapping to GRPC generated classes. */ public VideoPreview toVideoPreview() { return VideoPreview .newBuilder()
.setAddedDate(TypeConverter.dateToTimestamp(getAddedDate()))
doanduyhai/killrvideo-java
src/main/java/killrvideo/entity/VideoRatingByUser.java
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // }
import java.io.Serializable; import java.util.UUID; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.ratings.RatingsServiceOuterClass.GetUserRatingResponse; import killrvideo.utils.TypeConverter;
package killrvideo.entity; /** * Pojo representing DTO for table 'video_ratings_by_user'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS_RATINGS_BYUSER) public class VideoRatingByUser implements Serializable { /** Serial. */ private static final long serialVersionUID = 7124040203261999049L; @PartitionKey private UUID videoid; @ClusteringColumn private UUID userid; @Column private int rating; /** * Default constructor (reflection) */ public VideoRatingByUser() {} /** * Constructor with all parameters. */ public VideoRatingByUser(UUID videoid, UUID userid, int rating) { this.videoid = videoid; this.userid = userid; this.rating = rating; } /** * Mapping to generated GPRC beans. */ public GetUserRatingResponse toUserRatingResponse() { return GetUserRatingResponse .newBuilder()
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // } // Path: src/main/java/killrvideo/entity/VideoRatingByUser.java import java.io.Serializable; import java.util.UUID; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.ratings.RatingsServiceOuterClass.GetUserRatingResponse; import killrvideo.utils.TypeConverter; package killrvideo.entity; /** * Pojo representing DTO for table 'video_ratings_by_user'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS_RATINGS_BYUSER) public class VideoRatingByUser implements Serializable { /** Serial. */ private static final long serialVersionUID = 7124040203261999049L; @PartitionKey private UUID videoid; @ClusteringColumn private UUID userid; @Column private int rating; /** * Default constructor (reflection) */ public VideoRatingByUser() {} /** * Constructor with all parameters. */ public VideoRatingByUser(UUID videoid, UUID userid, int rating) { this.videoid = videoid; this.userid = userid; this.rating = rating; } /** * Mapping to generated GPRC beans. */ public GetUserRatingResponse toUserRatingResponse() { return GetUserRatingResponse .newBuilder()
.setUserId(TypeConverter.uuidToUuid(userid))
doanduyhai/killrvideo-java
src/main/java/killrvideo/entity/UserVideos.java
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // }
import java.util.Date; import java.util.Optional; import java.util.UUID; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.utils.TypeConverter; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoPreview;
package killrvideo.entity; /** * Pojo representing DTO for table 'user_videos' * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_USER_VIDEOS) public class UserVideos extends AbstractVideoList { /** Serial. */ private static final long serialVersionUID = -4689177834790056936L; @PartitionKey private UUID userid; /** * Deafult Constructor allowing reflection. */ public UserVideos() {} /** * Constructor without preview. */ public UserVideos(UUID userid, UUID videoid, String name, Date addedDate) { this(userid, videoid, name, null, addedDate); } /** * Full set constructor. */ public UserVideos(UUID userid, UUID videoid, String name, String previewImageLocation, Date addedDate) { super(name, previewImageLocation, addedDate, videoid); this.userid = userid; } /** * Mapping to generated GPRC beans. */ public VideoPreview toVideoPreview() { return VideoPreview .newBuilder()
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // } // Path: src/main/java/killrvideo/entity/UserVideos.java import java.util.Date; import java.util.Optional; import java.util.UUID; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.utils.TypeConverter; import killrvideo.video_catalog.VideoCatalogServiceOuterClass.VideoPreview; package killrvideo.entity; /** * Pojo representing DTO for table 'user_videos' * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_USER_VIDEOS) public class UserVideos extends AbstractVideoList { /** Serial. */ private static final long serialVersionUID = -4689177834790056936L; @PartitionKey private UUID userid; /** * Deafult Constructor allowing reflection. */ public UserVideos() {} /** * Constructor without preview. */ public UserVideos(UUID userid, UUID videoid, String name, Date addedDate) { this(userid, videoid, name, null, addedDate); } /** * Full set constructor. */ public UserVideos(UUID userid, UUID videoid, String name, String previewImageLocation, Date addedDate) { super(name, previewImageLocation, addedDate, videoid); this.userid = userid; } /** * Mapping to generated GPRC beans. */ public VideoPreview toVideoPreview() { return VideoPreview .newBuilder()
.setAddedDate(TypeConverter.dateToTimestamp(getAddedDate()))
doanduyhai/killrvideo-java
src/main/java/killrvideo/entity/User.java
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // }
import java.util.Date; import java.util.UUID; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.user_management.UserManagementServiceOuterClass.UserProfile; import killrvideo.utils.TypeConverter;
package killrvideo.entity; /** * Pojo representing DTO for table 'users'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_USERS) public class User { @PartitionKey private UUID userid; @Length(min = 1, message = "firstName must not be empty") @Column private String firstname; @Length(min = 1, message = "lastname must not be empty") @Column private String lastname; @Length(min = 1, message = "email must not be empty") @Column private String email; @NotNull @Column(name = "created_date") private Date createdAt; /** * Default constructor (reflection) */ public User() {} /** * Constructor with all parameters. */ public User(UUID userid, String firstname, String lastname, String email, Date createdAt) { this.userid = userid; this.firstname = firstname; this.lastname = lastname; this.email = email; this.createdAt = createdAt; } /** * Mapping to GRPC generated classes. */ public UserProfile toUserProfile() { return UserProfile.newBuilder() .setEmail(email) .setFirstName(firstname) .setLastName(lastname)
// Path: src/main/java/killrvideo/utils/TypeConverter.java // public class TypeConverter { // // public static Timestamp instantToTimeStamp(Instant instant) { // return Timestamp.newBuilder() // .setSeconds(instant.getEpochSecond()) // .setNanos(instant.getNano()).build(); // } // // public static Timestamp epochTimeToTimeStamp(long epoch) { // return Timestamp.newBuilder().setSeconds(epoch).build(); // } // // public static Timestamp dateToTimestamp(Date date) { // return instantToTimeStamp(date.toInstant()); // } // // public static Date dateFromTimestamp(Timestamp timestamp) { // return Date.from(Instant.ofEpochSecond(timestamp.getSeconds())); // } // // public static TimeUuid uuidToTimeUuid(UUID uuid) { // return TimeUuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // public static Uuid uuidToUuid(UUID uuid) { // return Uuid.newBuilder() // .setValue(uuid.toString()) // .build(); // } // // /** // * This method is useful when debugging as an easy way to get a traversal // * string to use in gremlin or DSE Studio from bytecode. // * @param traversal // * @return // */ // public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) { // return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode()); // } // } // Path: src/main/java/killrvideo/entity/User.java import java.util.Date; import java.util.UUID; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import killrvideo.user_management.UserManagementServiceOuterClass.UserProfile; import killrvideo.utils.TypeConverter; package killrvideo.entity; /** * Pojo representing DTO for table 'users'. * * @author DataStax evangelist team. */ @Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_USERS) public class User { @PartitionKey private UUID userid; @Length(min = 1, message = "firstName must not be empty") @Column private String firstname; @Length(min = 1, message = "lastname must not be empty") @Column private String lastname; @Length(min = 1, message = "email must not be empty") @Column private String email; @NotNull @Column(name = "created_date") private Date createdAt; /** * Default constructor (reflection) */ public User() {} /** * Constructor with all parameters. */ public User(UUID userid, String firstname, String lastname, String email, Date createdAt) { this.userid = userid; this.firstname = firstname; this.lastname = lastname; this.email = email; this.createdAt = createdAt; } /** * Mapping to GRPC generated classes. */ public UserProfile toUserProfile() { return UserProfile.newBuilder() .setEmail(email) .setFirstName(firstname) .setLastName(lastname)
.setUserId(TypeConverter.uuidToUuid(userid))
doanduyhai/killrvideo-java
src/main/java/killrvideo/configuration/KillrVideoConfiguration.java
// Path: src/main/java/killrvideo/async/KillrVideoThreadFactory.java // public class KillrVideoThreadFactory implements ThreadFactory { // // /** Create dedicated logger to trace ERRORS. */ // private static final Logger LOGGER = LoggerFactory.getLogger("killrvideo-default-executor"); // // /** Counter keeping track of thread number in executor. */ // private final AtomicInteger threadNumber = new AtomicInteger(10); // // /** // * Default constructor required for reflection. // */ // public KillrVideoThreadFactory() { // } // // /** {@inheritDoc} */ // public Thread newThread(Runnable r) { // Thread thread = new Thread(r); // thread.setName("killrvideo-default-executor-" + this.threadNumber.incrementAndGet()); // thread.setDaemon(true); // thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler); // return thread; // } // // /** // * Overriding error handling providing logging. // */ // private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = (t, e) -> { // LOGGER.error("Uncaught asynchronous exception : " + e.getMessage(), e); // }; // // // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.validation.Validation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.common.eventbus.EventBus; import killrvideo.async.KillrVideoThreadFactory;
package killrvideo.configuration; /** * Configuration for KillrVideo application leveraging on DSE, ETCD and any external source. * * @author DataStax evangelist team. */ @Configuration public class KillrVideoConfiguration { // --- Global Infos @Value("${killrvideo.application.name:KillrVideo}") private String applicationName; @Value("${killrvideo.application.instance.id: 0}") private int applicationInstanceId; @Value("${killrvideo.server.port: 8899}") private int applicationPort; @Value("#{environment.KILLRVIDEO_HOST_IP}") private String applicationHost; @Value("${killrvideo.cassandra.mutation-error-log: /tmp/killrvideo-mutation-errors.log}") private String mutationErrorLog; // --- ThreadPool Settings @Value("${killrvideo.threadpool.min.threads:5}") private int minThreads; @Value("${killrvideo.threadpool.max.threads:10}") private int maxThreads; @Value("${killrvideo.thread.ttl.seconds:60}") private int threadsTTLSeconds; @Value("${killrvideo.thread.queue.size:1000}") private int threadPoolQueueSize; // --- Bean definition @Bean public EventBus createEventBus() { return new EventBus("killrvideo_event_bus"); } /** * Initialize the threadPool. * * @return * current executor for this */ @Bean(destroyMethod = "shutdownNow") public ExecutorService threadPool() { return new ThreadPoolExecutor(getMinThreads(), getMaxThreads(), getThreadsTTLSeconds(), TimeUnit.SECONDS, new LinkedBlockingQueue<>(getThreadPoolQueueSize()),
// Path: src/main/java/killrvideo/async/KillrVideoThreadFactory.java // public class KillrVideoThreadFactory implements ThreadFactory { // // /** Create dedicated logger to trace ERRORS. */ // private static final Logger LOGGER = LoggerFactory.getLogger("killrvideo-default-executor"); // // /** Counter keeping track of thread number in executor. */ // private final AtomicInteger threadNumber = new AtomicInteger(10); // // /** // * Default constructor required for reflection. // */ // public KillrVideoThreadFactory() { // } // // /** {@inheritDoc} */ // public Thread newThread(Runnable r) { // Thread thread = new Thread(r); // thread.setName("killrvideo-default-executor-" + this.threadNumber.incrementAndGet()); // thread.setDaemon(true); // thread.setUncaughtExceptionHandler(this.uncaughtExceptionHandler); // return thread; // } // // /** // * Overriding error handling providing logging. // */ // private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = (t, e) -> { // LOGGER.error("Uncaught asynchronous exception : " + e.getMessage(), e); // }; // // // } // Path: src/main/java/killrvideo/configuration/KillrVideoConfiguration.java import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.validation.Validation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.common.eventbus.EventBus; import killrvideo.async.KillrVideoThreadFactory; package killrvideo.configuration; /** * Configuration for KillrVideo application leveraging on DSE, ETCD and any external source. * * @author DataStax evangelist team. */ @Configuration public class KillrVideoConfiguration { // --- Global Infos @Value("${killrvideo.application.name:KillrVideo}") private String applicationName; @Value("${killrvideo.application.instance.id: 0}") private int applicationInstanceId; @Value("${killrvideo.server.port: 8899}") private int applicationPort; @Value("#{environment.KILLRVIDEO_HOST_IP}") private String applicationHost; @Value("${killrvideo.cassandra.mutation-error-log: /tmp/killrvideo-mutation-errors.log}") private String mutationErrorLog; // --- ThreadPool Settings @Value("${killrvideo.threadpool.min.threads:5}") private int minThreads; @Value("${killrvideo.threadpool.max.threads:10}") private int maxThreads; @Value("${killrvideo.thread.ttl.seconds:60}") private int threadsTTLSeconds; @Value("${killrvideo.thread.queue.size:1000}") private int threadPoolQueueSize; // --- Bean definition @Bean public EventBus createEventBus() { return new EventBus("killrvideo_event_bus"); } /** * Initialize the threadPool. * * @return * current executor for this */ @Bean(destroyMethod = "shutdownNow") public ExecutorService threadPool() { return new ThreadPoolExecutor(getMinThreads(), getMaxThreads(), getThreadsTTLSeconds(), TimeUnit.SECONDS, new LinkedBlockingQueue<>(getThreadPoolQueueSize()),
new KillrVideoThreadFactory());