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
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/ui/callback/ZhihuApi.java
// Path: app/src/main/java/com/tyq/jiemian/bean/NewsEntity.java // public class NewsEntity implements Parcelable { // // private String date; // // private ArrayList<StoriesEntity> stories; // // private List<TopStoriesEntity> top_stories; // // // public void setDate(String date) { // this.date = date; // } // // public void setStories(ArrayList<StoriesEntity> stories) { // this.stories = stories; // } // // public void setTop_stories(List<TopStoriesEntity> top_stories) { // this.top_stories = top_stories; // } // // public String getDate() { // return date; // } // // public ArrayList<StoriesEntity> getStories() { // return stories; // } // // public List<TopStoriesEntity> getTop_stories() { // return top_stories; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.date); // dest.writeList(this.stories); // dest.writeList(this.top_stories); // } // // public NewsEntity() { // } // // protected NewsEntity(Parcel in) { // this.date = in.readString(); // this.stories = new ArrayList<StoriesEntity>(); // in.readList(this.stories, List.class.getClassLoader()); // this.top_stories = new ArrayList<TopStoriesEntity>(); // in.readList(this.top_stories, List.class.getClassLoader()); // } // // public static final Creator<NewsEntity> CREATOR = new Creator<NewsEntity>() { // public NewsEntity createFromParcel(Parcel source) { // return new NewsEntity(source); // } // // public NewsEntity[] newArray(int size) { // return new NewsEntity[size]; // } // }; // // @Override // public String toString() { // return "NewsEntity{" + // "date='" + date + '\'' + // ", stories=" + stories + // ", top_stories=" + top_stories + // '}'; // } // } // // Path: app/src/main/java/com/tyq/jiemian/bean/StoryDetailsEntity.java // public class StoryDetailsEntity implements Parcelable { // // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private String ga_prefix; // private int type; // private int id; // private List<String> css; // // public void setBody(String body) { // this.body = body; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public void setTitle(String title) { // this.title = title; // } // // public void setImage(String image) { // this.image = image; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public void setType(int type) { // this.type = type; // } // // public void setId(int id) { // this.id = id; // } // // public void setCss(List<String> css) { // this.css = css; // } // // public String getBody() { // return body; // } // // public String getImage_source() { // return image_source; // } // // public String getTitle() { // return title; // } // // public String getImage() { // return image; // } // // public String getShare_url() { // return share_url; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public int getType() { // return type; // } // // public int getId() { // return id; // } // // public List<String> getCss() { // return css; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.body); // dest.writeString(this.image_source); // dest.writeString(this.title); // dest.writeString(this.image); // dest.writeString(this.share_url); // dest.writeString(this.ga_prefix); // dest.writeInt(this.type); // dest.writeInt(this.id); // dest.writeStringList(this.css); // } // // public StoryDetailsEntity() { // } // // protected StoryDetailsEntity(Parcel in) { // this.body = in.readString(); // this.image_source = in.readString(); // this.title = in.readString(); // this.image = in.readString(); // this.share_url = in.readString(); // this.ga_prefix = in.readString(); // this.type = in.readInt(); // this.id = in.readInt(); // this.css = in.createStringArrayList(); // } // // public static final Creator<StoryDetailsEntity> CREATOR = new Creator<StoryDetailsEntity>() { // public StoryDetailsEntity createFromParcel(Parcel source) { // return new StoryDetailsEntity(source); // } // // public StoryDetailsEntity[] newArray(int size) { // return new StoryDetailsEntity[size]; // } // }; // }
import com.tyq.jiemian.bean.NewsEntity; import com.tyq.jiemian.bean.StoryDetailsEntity; import retrofit2.http.GET; import retrofit2.http.Path; import rx.Observable;
package com.tyq.jiemian.ui.callback; /** * Created by diff on 2016/2/16. */ public interface ZhihuApi { @GET("api/4/news/latest") Observable<NewsEntity> getLastestNews(); @GET("api/4/news/before/{id}") Observable<NewsEntity> getBeforeNews(@Path("id") String id); @GET("api/4/news/{id}")
// Path: app/src/main/java/com/tyq/jiemian/bean/NewsEntity.java // public class NewsEntity implements Parcelable { // // private String date; // // private ArrayList<StoriesEntity> stories; // // private List<TopStoriesEntity> top_stories; // // // public void setDate(String date) { // this.date = date; // } // // public void setStories(ArrayList<StoriesEntity> stories) { // this.stories = stories; // } // // public void setTop_stories(List<TopStoriesEntity> top_stories) { // this.top_stories = top_stories; // } // // public String getDate() { // return date; // } // // public ArrayList<StoriesEntity> getStories() { // return stories; // } // // public List<TopStoriesEntity> getTop_stories() { // return top_stories; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.date); // dest.writeList(this.stories); // dest.writeList(this.top_stories); // } // // public NewsEntity() { // } // // protected NewsEntity(Parcel in) { // this.date = in.readString(); // this.stories = new ArrayList<StoriesEntity>(); // in.readList(this.stories, List.class.getClassLoader()); // this.top_stories = new ArrayList<TopStoriesEntity>(); // in.readList(this.top_stories, List.class.getClassLoader()); // } // // public static final Creator<NewsEntity> CREATOR = new Creator<NewsEntity>() { // public NewsEntity createFromParcel(Parcel source) { // return new NewsEntity(source); // } // // public NewsEntity[] newArray(int size) { // return new NewsEntity[size]; // } // }; // // @Override // public String toString() { // return "NewsEntity{" + // "date='" + date + '\'' + // ", stories=" + stories + // ", top_stories=" + top_stories + // '}'; // } // } // // Path: app/src/main/java/com/tyq/jiemian/bean/StoryDetailsEntity.java // public class StoryDetailsEntity implements Parcelable { // // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private String ga_prefix; // private int type; // private int id; // private List<String> css; // // public void setBody(String body) { // this.body = body; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public void setTitle(String title) { // this.title = title; // } // // public void setImage(String image) { // this.image = image; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public void setType(int type) { // this.type = type; // } // // public void setId(int id) { // this.id = id; // } // // public void setCss(List<String> css) { // this.css = css; // } // // public String getBody() { // return body; // } // // public String getImage_source() { // return image_source; // } // // public String getTitle() { // return title; // } // // public String getImage() { // return image; // } // // public String getShare_url() { // return share_url; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public int getType() { // return type; // } // // public int getId() { // return id; // } // // public List<String> getCss() { // return css; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this.body); // dest.writeString(this.image_source); // dest.writeString(this.title); // dest.writeString(this.image); // dest.writeString(this.share_url); // dest.writeString(this.ga_prefix); // dest.writeInt(this.type); // dest.writeInt(this.id); // dest.writeStringList(this.css); // } // // public StoryDetailsEntity() { // } // // protected StoryDetailsEntity(Parcel in) { // this.body = in.readString(); // this.image_source = in.readString(); // this.title = in.readString(); // this.image = in.readString(); // this.share_url = in.readString(); // this.ga_prefix = in.readString(); // this.type = in.readInt(); // this.id = in.readInt(); // this.css = in.createStringArrayList(); // } // // public static final Creator<StoryDetailsEntity> CREATOR = new Creator<StoryDetailsEntity>() { // public StoryDetailsEntity createFromParcel(Parcel source) { // return new StoryDetailsEntity(source); // } // // public StoryDetailsEntity[] newArray(int size) { // return new StoryDetailsEntity[size]; // } // }; // } // Path: app/src/main/java/com/tyq/jiemian/ui/callback/ZhihuApi.java import com.tyq.jiemian.bean.NewsEntity; import com.tyq.jiemian.bean.StoryDetailsEntity; import retrofit2.http.GET; import retrofit2.http.Path; import rx.Observable; package com.tyq.jiemian.ui.callback; /** * Created by diff on 2016/2/16. */ public interface ZhihuApi { @GET("api/4/news/latest") Observable<NewsEntity> getLastestNews(); @GET("api/4/news/before/{id}") Observable<NewsEntity> getBeforeNews(@Path("id") String id); @GET("api/4/news/{id}")
Observable<StoryDetailsEntity> getNewsDetails(@Path("id") int id);
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/ui/callback/TRApi.java
// Path: app/src/main/java/com/tyq/jiemian/bean/TREntity.java // public class TREntity implements Parcelable { // private int code; // private String text; // // public void setCode(int code) { // this.code = code; // } // // public void setText(String text) { // this.text = text; // } // // public int getCode() { // return code; // } // // public String getText() { // return text; // } // // @Override // public String toString() { // return "TREntity{" + // "code=" + code + // ", text='" + text + '\'' + // '}'; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.code); // dest.writeString(this.text); // } // // public TREntity() { // } // // protected TREntity(Parcel in) { // this.code = in.readInt(); // this.text = in.readString(); // } // // public static final Parcelable.Creator<TREntity> CREATOR = new Parcelable.Creator<TREntity>() { // public TREntity createFromParcel(Parcel source) { // return new TREntity(source); // } // // public TREntity[] newArray(int size) { // return new TREntity[size]; // } // }; // }
import com.tyq.jiemian.bean.TREntity; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST;
package com.tyq.jiemian.ui.callback; /** * Created by tyq on 2016/6/5. */ public interface TRApi { @FormUrlEncoded @POST("api")
// Path: app/src/main/java/com/tyq/jiemian/bean/TREntity.java // public class TREntity implements Parcelable { // private int code; // private String text; // // public void setCode(int code) { // this.code = code; // } // // public void setText(String text) { // this.text = text; // } // // public int getCode() { // return code; // } // // public String getText() { // return text; // } // // @Override // public String toString() { // return "TREntity{" + // "code=" + code + // ", text='" + text + '\'' + // '}'; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(this.code); // dest.writeString(this.text); // } // // public TREntity() { // } // // protected TREntity(Parcel in) { // this.code = in.readInt(); // this.text = in.readString(); // } // // public static final Parcelable.Creator<TREntity> CREATOR = new Parcelable.Creator<TREntity>() { // public TREntity createFromParcel(Parcel source) { // return new TREntity(source); // } // // public TREntity[] newArray(int size) { // return new TREntity[size]; // } // }; // } // Path: app/src/main/java/com/tyq/jiemian/ui/callback/TRApi.java import com.tyq.jiemian.bean.TREntity; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; package com.tyq.jiemian.ui.callback; /** * Created by tyq on 2016/6/5. */ public interface TRApi { @FormUrlEncoded @POST("api")
Call<TREntity> getTRResponse(@Field("key") String key, @Field("info") String info, @Field("userid") String userid);
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/TRClientAdapter.java
// Path: app/src/main/java/com/tyq/jiemian/bean/ChatBean.java // public class ChatBean { // private int type; // private String info; // // public ChatBean(int type, String info) { // this.type = type; // this.info = info; // } // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.tyq.jiemian.R; import com.tyq.jiemian.bean.ChatBean; import java.util.ArrayList; import java.util.List;
package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/5. */ public class TRClientAdapter extends BaseAdapter{ private static final int VIEW_TYPE = 2; public static final int TYPE_USER = 0; public static final int TYPE_ROBOT = 1;
// Path: app/src/main/java/com/tyq/jiemian/bean/ChatBean.java // public class ChatBean { // private int type; // private String info; // // public ChatBean(int type, String info) { // this.type = type; // this.info = info; // } // // public String getInfo() { // return info; // } // // public void setInfo(String info) { // this.info = info; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // } // Path: app/src/main/java/com/tyq/jiemian/adapter/TRClientAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.tyq.jiemian.R; import com.tyq.jiemian.bean.ChatBean; import java.util.ArrayList; import java.util.List; package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/5. */ public class TRClientAdapter extends BaseAdapter{ private static final int VIEW_TYPE = 2; public static final int TYPE_USER = 0; public static final int TYPE_ROBOT = 1;
private List<ChatBean> list;
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/presenter/ZhihuPresenter.java
// Path: app/src/main/java/com/tyq/jiemian/ui/callback/ZhihuApi.java // public interface ZhihuApi { // // @GET("api/4/news/latest") // Observable<NewsEntity> getLastestNews(); // // @GET("api/4/news/before/{id}") // Observable<NewsEntity> getBeforeNews(@Path("id") String id); // // @GET("api/4/news/{id}") // Observable<StoryDetailsEntity> getNewsDetails(@Path("id") int id); // } // // Path: app/src/main/java/com/tyq/jiemian/utils/Constant.java // public class Constant { // public static final String TITLE = "title"; // public static final String TECHNOLOGICAL_URL = "http://www.jiemian.com/lists/6.html"; // public static final String ENTERTAINMENT_URL = "http://www.jiemian.com/lists/25.html"; // public static final String NEWS_ITEM = "news_item"; // public static final String NEWS_TITLE = "news_title"; // public static final String Bmob_App_ID = "2cb3bdc19bf6e2240dbb8ae06a80cc24"; // public static final String BASE_ZHIHU_URL = "http://news-at.zhihu.com/"; // public static final String ITEM_ID = "item_id"; // public static final String DB_NAME = "news_db"; // public static final String NEWS_URL = "new_url"; // public static final String POPULAR_NEWS_URL = "http://apis.baidu.com/3023/weixin/channel"; // public static final String POPULAR_API_KEY = "891eeffe6f1b4652128542bb8c9971a2"; // public static final String TRC_ROBOT_REC = "嗨,我是智能聊天机器人小er,聊两块钱的"; // public static final String TRC_ROBOT_REST = "小er已经休息,请明天再聊。"; // public static final String TRC_ROBOT_FAILED = "暂时无法回应"; // public static final String TRC_KEY = "ae536b38aa743f17ecb5f0e65a8dfea9"; // public static final String TRC_USER_ID = "diffey"; // public static final String SEARCH_URL = "http://apis.baidu.com/songshuxiansheng/real_time/search_news"; // public static final String SEARCH_ITEM = "search_item"; // }
import android.content.Context; import com.tyq.jiemian.ui.callback.ZhihuApi; import com.tyq.jiemian.utils.Constant; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package com.tyq.jiemian.presenter; /** * Created by tyq on 2016/5/15. */ public class ZhihuPresenter extends BasePresenter { public ZhihuPresenter(Context context) { super(context); } private Retrofit retrofit = new Retrofit.Builder()
// Path: app/src/main/java/com/tyq/jiemian/ui/callback/ZhihuApi.java // public interface ZhihuApi { // // @GET("api/4/news/latest") // Observable<NewsEntity> getLastestNews(); // // @GET("api/4/news/before/{id}") // Observable<NewsEntity> getBeforeNews(@Path("id") String id); // // @GET("api/4/news/{id}") // Observable<StoryDetailsEntity> getNewsDetails(@Path("id") int id); // } // // Path: app/src/main/java/com/tyq/jiemian/utils/Constant.java // public class Constant { // public static final String TITLE = "title"; // public static final String TECHNOLOGICAL_URL = "http://www.jiemian.com/lists/6.html"; // public static final String ENTERTAINMENT_URL = "http://www.jiemian.com/lists/25.html"; // public static final String NEWS_ITEM = "news_item"; // public static final String NEWS_TITLE = "news_title"; // public static final String Bmob_App_ID = "2cb3bdc19bf6e2240dbb8ae06a80cc24"; // public static final String BASE_ZHIHU_URL = "http://news-at.zhihu.com/"; // public static final String ITEM_ID = "item_id"; // public static final String DB_NAME = "news_db"; // public static final String NEWS_URL = "new_url"; // public static final String POPULAR_NEWS_URL = "http://apis.baidu.com/3023/weixin/channel"; // public static final String POPULAR_API_KEY = "891eeffe6f1b4652128542bb8c9971a2"; // public static final String TRC_ROBOT_REC = "嗨,我是智能聊天机器人小er,聊两块钱的"; // public static final String TRC_ROBOT_REST = "小er已经休息,请明天再聊。"; // public static final String TRC_ROBOT_FAILED = "暂时无法回应"; // public static final String TRC_KEY = "ae536b38aa743f17ecb5f0e65a8dfea9"; // public static final String TRC_USER_ID = "diffey"; // public static final String SEARCH_URL = "http://apis.baidu.com/songshuxiansheng/real_time/search_news"; // public static final String SEARCH_ITEM = "search_item"; // } // Path: app/src/main/java/com/tyq/jiemian/presenter/ZhihuPresenter.java import android.content.Context; import com.tyq.jiemian.ui.callback.ZhihuApi; import com.tyq.jiemian.utils.Constant; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package com.tyq.jiemian.presenter; /** * Created by tyq on 2016/5/15. */ public class ZhihuPresenter extends BasePresenter { public ZhihuPresenter(Context context) { super(context); } private Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_ZHIHU_URL)
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/presenter/ZhihuPresenter.java
// Path: app/src/main/java/com/tyq/jiemian/ui/callback/ZhihuApi.java // public interface ZhihuApi { // // @GET("api/4/news/latest") // Observable<NewsEntity> getLastestNews(); // // @GET("api/4/news/before/{id}") // Observable<NewsEntity> getBeforeNews(@Path("id") String id); // // @GET("api/4/news/{id}") // Observable<StoryDetailsEntity> getNewsDetails(@Path("id") int id); // } // // Path: app/src/main/java/com/tyq/jiemian/utils/Constant.java // public class Constant { // public static final String TITLE = "title"; // public static final String TECHNOLOGICAL_URL = "http://www.jiemian.com/lists/6.html"; // public static final String ENTERTAINMENT_URL = "http://www.jiemian.com/lists/25.html"; // public static final String NEWS_ITEM = "news_item"; // public static final String NEWS_TITLE = "news_title"; // public static final String Bmob_App_ID = "2cb3bdc19bf6e2240dbb8ae06a80cc24"; // public static final String BASE_ZHIHU_URL = "http://news-at.zhihu.com/"; // public static final String ITEM_ID = "item_id"; // public static final String DB_NAME = "news_db"; // public static final String NEWS_URL = "new_url"; // public static final String POPULAR_NEWS_URL = "http://apis.baidu.com/3023/weixin/channel"; // public static final String POPULAR_API_KEY = "891eeffe6f1b4652128542bb8c9971a2"; // public static final String TRC_ROBOT_REC = "嗨,我是智能聊天机器人小er,聊两块钱的"; // public static final String TRC_ROBOT_REST = "小er已经休息,请明天再聊。"; // public static final String TRC_ROBOT_FAILED = "暂时无法回应"; // public static final String TRC_KEY = "ae536b38aa743f17ecb5f0e65a8dfea9"; // public static final String TRC_USER_ID = "diffey"; // public static final String SEARCH_URL = "http://apis.baidu.com/songshuxiansheng/real_time/search_news"; // public static final String SEARCH_ITEM = "search_item"; // }
import android.content.Context; import com.tyq.jiemian.ui.callback.ZhihuApi; import com.tyq.jiemian.utils.Constant; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package com.tyq.jiemian.presenter; /** * Created by tyq on 2016/5/15. */ public class ZhihuPresenter extends BasePresenter { public ZhihuPresenter(Context context) { super(context); } private Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.BASE_ZHIHU_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build();
// Path: app/src/main/java/com/tyq/jiemian/ui/callback/ZhihuApi.java // public interface ZhihuApi { // // @GET("api/4/news/latest") // Observable<NewsEntity> getLastestNews(); // // @GET("api/4/news/before/{id}") // Observable<NewsEntity> getBeforeNews(@Path("id") String id); // // @GET("api/4/news/{id}") // Observable<StoryDetailsEntity> getNewsDetails(@Path("id") int id); // } // // Path: app/src/main/java/com/tyq/jiemian/utils/Constant.java // public class Constant { // public static final String TITLE = "title"; // public static final String TECHNOLOGICAL_URL = "http://www.jiemian.com/lists/6.html"; // public static final String ENTERTAINMENT_URL = "http://www.jiemian.com/lists/25.html"; // public static final String NEWS_ITEM = "news_item"; // public static final String NEWS_TITLE = "news_title"; // public static final String Bmob_App_ID = "2cb3bdc19bf6e2240dbb8ae06a80cc24"; // public static final String BASE_ZHIHU_URL = "http://news-at.zhihu.com/"; // public static final String ITEM_ID = "item_id"; // public static final String DB_NAME = "news_db"; // public static final String NEWS_URL = "new_url"; // public static final String POPULAR_NEWS_URL = "http://apis.baidu.com/3023/weixin/channel"; // public static final String POPULAR_API_KEY = "891eeffe6f1b4652128542bb8c9971a2"; // public static final String TRC_ROBOT_REC = "嗨,我是智能聊天机器人小er,聊两块钱的"; // public static final String TRC_ROBOT_REST = "小er已经休息,请明天再聊。"; // public static final String TRC_ROBOT_FAILED = "暂时无法回应"; // public static final String TRC_KEY = "ae536b38aa743f17ecb5f0e65a8dfea9"; // public static final String TRC_USER_ID = "diffey"; // public static final String SEARCH_URL = "http://apis.baidu.com/songshuxiansheng/real_time/search_news"; // public static final String SEARCH_ITEM = "search_item"; // } // Path: app/src/main/java/com/tyq/jiemian/presenter/ZhihuPresenter.java import android.content.Context; import com.tyq.jiemian.ui.callback.ZhihuApi; import com.tyq.jiemian.utils.Constant; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package com.tyq.jiemian.presenter; /** * Created by tyq on 2016/5/15. */ public class ZhihuPresenter extends BasePresenter { public ZhihuPresenter(Context context) { super(context); } private Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.BASE_ZHIHU_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build();
public ZhihuApi createZhihuService() {
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java
// Path: app/src/main/java-gen/com/tyq/greendao/HaveRead.java // public class HaveRead { // // private Long id; // private String title; // private String imageUrl; // private String url; // // public HaveRead() { // } // // public HaveRead(Long id) { // this.id = id; // } // // public HaveRead(Long id, String title, String imageUrl, String url) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/IsReadAdapter.java // public class IsReadAdapter extends RecyclerView.Adapter{ // // private List<HaveRead> haveReads; // private Context context; // private LayoutInflater inflater; // public IsReadAdapter(Context context){ // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(List<HaveRead> data){ // this.haveReads = data; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ViewHolder(context,inflater.inflate(R.layout.item_have_read,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof ViewHolder){ // ((ViewHolder) holder).updateUi(haveReads.get(position)); // } // } // // @Override // public int getItemCount() { // return haveReads.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemHaveReadBinding dataBinding; // private Context context; // private HaveRead haveRead; // public ViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(HaveRead haveRead){ // this.haveRead = haveRead; // ImageLoader.getInstance().displayImage(haveRead.getImageUrl(),dataBinding.image); // dataBinding.setNews(haveRead); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,haveRead.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // }
import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.greendao.HaveRead; import com.tyq.jiemian.adapter.IsReadAdapter; import com.tyq.jiemian.databinding.ItemIsReadBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List;
package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/2. */ public class IsReadViewHolder extends RecyclerView.ViewHolder { private ItemIsReadBinding dataBinding;
// Path: app/src/main/java-gen/com/tyq/greendao/HaveRead.java // public class HaveRead { // // private Long id; // private String title; // private String imageUrl; // private String url; // // public HaveRead() { // } // // public HaveRead(Long id) { // this.id = id; // } // // public HaveRead(Long id, String title, String imageUrl, String url) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/IsReadAdapter.java // public class IsReadAdapter extends RecyclerView.Adapter{ // // private List<HaveRead> haveReads; // private Context context; // private LayoutInflater inflater; // public IsReadAdapter(Context context){ // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(List<HaveRead> data){ // this.haveReads = data; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ViewHolder(context,inflater.inflate(R.layout.item_have_read,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof ViewHolder){ // ((ViewHolder) holder).updateUi(haveReads.get(position)); // } // } // // @Override // public int getItemCount() { // return haveReads.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemHaveReadBinding dataBinding; // private Context context; // private HaveRead haveRead; // public ViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(HaveRead haveRead){ // this.haveRead = haveRead; // ImageLoader.getInstance().displayImage(haveRead.getImageUrl(),dataBinding.image); // dataBinding.setNews(haveRead); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,haveRead.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // } // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.greendao.HaveRead; import com.tyq.jiemian.adapter.IsReadAdapter; import com.tyq.jiemian.databinding.ItemIsReadBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List; package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/2. */ public class IsReadViewHolder extends RecyclerView.ViewHolder { private ItemIsReadBinding dataBinding;
private IsReadAdapter adapter;
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java
// Path: app/src/main/java-gen/com/tyq/greendao/HaveRead.java // public class HaveRead { // // private Long id; // private String title; // private String imageUrl; // private String url; // // public HaveRead() { // } // // public HaveRead(Long id) { // this.id = id; // } // // public HaveRead(Long id, String title, String imageUrl, String url) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/IsReadAdapter.java // public class IsReadAdapter extends RecyclerView.Adapter{ // // private List<HaveRead> haveReads; // private Context context; // private LayoutInflater inflater; // public IsReadAdapter(Context context){ // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(List<HaveRead> data){ // this.haveReads = data; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ViewHolder(context,inflater.inflate(R.layout.item_have_read,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof ViewHolder){ // ((ViewHolder) holder).updateUi(haveReads.get(position)); // } // } // // @Override // public int getItemCount() { // return haveReads.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemHaveReadBinding dataBinding; // private Context context; // private HaveRead haveRead; // public ViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(HaveRead haveRead){ // this.haveRead = haveRead; // ImageLoader.getInstance().displayImage(haveRead.getImageUrl(),dataBinding.image); // dataBinding.setNews(haveRead); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,haveRead.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // }
import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.greendao.HaveRead; import com.tyq.jiemian.adapter.IsReadAdapter; import com.tyq.jiemian.databinding.ItemIsReadBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List;
package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/2. */ public class IsReadViewHolder extends RecyclerView.ViewHolder { private ItemIsReadBinding dataBinding; private IsReadAdapter adapter; public IsReadViewHolder(Context context,View itemView) { super(itemView); dataBinding = DataBindingUtil.bind(itemView); LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); dataBinding.recyclerView.setHasFixedSize(true); dataBinding.recyclerView.setLayoutManager(manager); adapter = new IsReadAdapter(context);
// Path: app/src/main/java-gen/com/tyq/greendao/HaveRead.java // public class HaveRead { // // private Long id; // private String title; // private String imageUrl; // private String url; // // public HaveRead() { // } // // public HaveRead(Long id) { // this.id = id; // } // // public HaveRead(Long id, String title, String imageUrl, String url) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/IsReadAdapter.java // public class IsReadAdapter extends RecyclerView.Adapter{ // // private List<HaveRead> haveReads; // private Context context; // private LayoutInflater inflater; // public IsReadAdapter(Context context){ // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(List<HaveRead> data){ // this.haveReads = data; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ViewHolder(context,inflater.inflate(R.layout.item_have_read,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof ViewHolder){ // ((ViewHolder) holder).updateUi(haveReads.get(position)); // } // } // // @Override // public int getItemCount() { // return haveReads.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemHaveReadBinding dataBinding; // private Context context; // private HaveRead haveRead; // public ViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(HaveRead haveRead){ // this.haveRead = haveRead; // ImageLoader.getInstance().displayImage(haveRead.getImageUrl(),dataBinding.image); // dataBinding.setNews(haveRead); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,haveRead.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // } // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.greendao.HaveRead; import com.tyq.jiemian.adapter.IsReadAdapter; import com.tyq.jiemian.databinding.ItemIsReadBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List; package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/2. */ public class IsReadViewHolder extends RecyclerView.ViewHolder { private ItemIsReadBinding dataBinding; private IsReadAdapter adapter; public IsReadViewHolder(Context context,View itemView) { super(itemView); dataBinding = DataBindingUtil.bind(itemView); LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); dataBinding.recyclerView.setHasFixedSize(true); dataBinding.recyclerView.setLayoutManager(manager); adapter = new IsReadAdapter(context);
List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList();
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java
// Path: app/src/main/java-gen/com/tyq/greendao/HaveRead.java // public class HaveRead { // // private Long id; // private String title; // private String imageUrl; // private String url; // // public HaveRead() { // } // // public HaveRead(Long id) { // this.id = id; // } // // public HaveRead(Long id, String title, String imageUrl, String url) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/IsReadAdapter.java // public class IsReadAdapter extends RecyclerView.Adapter{ // // private List<HaveRead> haveReads; // private Context context; // private LayoutInflater inflater; // public IsReadAdapter(Context context){ // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(List<HaveRead> data){ // this.haveReads = data; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ViewHolder(context,inflater.inflate(R.layout.item_have_read,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof ViewHolder){ // ((ViewHolder) holder).updateUi(haveReads.get(position)); // } // } // // @Override // public int getItemCount() { // return haveReads.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemHaveReadBinding dataBinding; // private Context context; // private HaveRead haveRead; // public ViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(HaveRead haveRead){ // this.haveRead = haveRead; // ImageLoader.getInstance().displayImage(haveRead.getImageUrl(),dataBinding.image); // dataBinding.setNews(haveRead); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,haveRead.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // }
import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.greendao.HaveRead; import com.tyq.jiemian.adapter.IsReadAdapter; import com.tyq.jiemian.databinding.ItemIsReadBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List;
package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/2. */ public class IsReadViewHolder extends RecyclerView.ViewHolder { private ItemIsReadBinding dataBinding; private IsReadAdapter adapter; public IsReadViewHolder(Context context,View itemView) { super(itemView); dataBinding = DataBindingUtil.bind(itemView); LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); dataBinding.recyclerView.setHasFixedSize(true); dataBinding.recyclerView.setLayoutManager(manager); adapter = new IsReadAdapter(context);
// Path: app/src/main/java-gen/com/tyq/greendao/HaveRead.java // public class HaveRead { // // private Long id; // private String title; // private String imageUrl; // private String url; // // public HaveRead() { // } // // public HaveRead(Long id) { // this.id = id; // } // // public HaveRead(Long id, String title, String imageUrl, String url) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/IsReadAdapter.java // public class IsReadAdapter extends RecyclerView.Adapter{ // // private List<HaveRead> haveReads; // private Context context; // private LayoutInflater inflater; // public IsReadAdapter(Context context){ // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(List<HaveRead> data){ // this.haveReads = data; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new ViewHolder(context,inflater.inflate(R.layout.item_have_read,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof ViewHolder){ // ((ViewHolder) holder).updateUi(haveReads.get(position)); // } // } // // @Override // public int getItemCount() { // return haveReads.size(); // } // // static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemHaveReadBinding dataBinding; // private Context context; // private HaveRead haveRead; // public ViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(HaveRead haveRead){ // this.haveRead = haveRead; // ImageLoader.getInstance().displayImage(haveRead.getImageUrl(),dataBinding.image); // dataBinding.setNews(haveRead); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,haveRead.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // } // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.greendao.HaveRead; import com.tyq.jiemian.adapter.IsReadAdapter; import com.tyq.jiemian.databinding.ItemIsReadBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List; package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/2. */ public class IsReadViewHolder extends RecyclerView.ViewHolder { private ItemIsReadBinding dataBinding; private IsReadAdapter adapter; public IsReadViewHolder(Context context,View itemView) { super(itemView); dataBinding = DataBindingUtil.bind(itemView); LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); dataBinding.recyclerView.setHasFixedSize(true); dataBinding.recyclerView.setLayoutManager(manager); adapter = new IsReadAdapter(context);
List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList();
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/MainAdapter.java
// Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java // public class IsReadViewHolder extends RecyclerView.ViewHolder { // // private ItemIsReadBinding dataBinding; // private IsReadAdapter adapter; // public IsReadViewHolder(Context context,View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // adapter = new IsReadAdapter(context); // List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList(); // adapter.addAll(haveReadList); // dataBinding.recyclerView.setAdapter(adapter); // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java // public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { // private ItemPopularListBinding dataBinding; // private PopularListAdapter adapter; // private HomePresenter presenter; // // public PopularViewHolder(Context context, View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context); // manager.setOrientation(LinearLayoutManager.HORIZONTAL); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // presenter = new HomePresenter(context); // presenter.requestPopularList(this); // adapter = new PopularListAdapter(context); // dataBinding.recyclerView.setAdapter(adapter); // } // // @Override // public void onRequestPopularNewsSuccess(PopularNews news) { // adapter.addAll(news); // } // // @Override // public void onRequestPopularNewsFailed(String errMsg) { // // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/WelcomeViewHolder.java // public class WelcomeViewHolder extends RecyclerView.ViewHolder { // // private ItemWelcomeBinding dataBinding; // public WelcomeViewHolder(View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.SpanWatcher; import android.view.LayoutInflater; import android.view.ViewGroup; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.VH.IsReadViewHolder; import com.tyq.jiemian.adapter.VH.PopularViewHolder; import com.tyq.jiemian.adapter.VH.WelcomeViewHolder;
package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/1. */ public class MainAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater; private final static int WELCOME_VIEW = 0; private final static int ISREADED_VIEW = 1; private final static int POPULAR_VIEW = 2; private final static int HISTORY_VIEW = 3; public MainAdapter(Context context) { this.context = context; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType){ case WELCOME_VIEW:
// Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java // public class IsReadViewHolder extends RecyclerView.ViewHolder { // // private ItemIsReadBinding dataBinding; // private IsReadAdapter adapter; // public IsReadViewHolder(Context context,View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // adapter = new IsReadAdapter(context); // List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList(); // adapter.addAll(haveReadList); // dataBinding.recyclerView.setAdapter(adapter); // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java // public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { // private ItemPopularListBinding dataBinding; // private PopularListAdapter adapter; // private HomePresenter presenter; // // public PopularViewHolder(Context context, View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context); // manager.setOrientation(LinearLayoutManager.HORIZONTAL); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // presenter = new HomePresenter(context); // presenter.requestPopularList(this); // adapter = new PopularListAdapter(context); // dataBinding.recyclerView.setAdapter(adapter); // } // // @Override // public void onRequestPopularNewsSuccess(PopularNews news) { // adapter.addAll(news); // } // // @Override // public void onRequestPopularNewsFailed(String errMsg) { // // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/WelcomeViewHolder.java // public class WelcomeViewHolder extends RecyclerView.ViewHolder { // // private ItemWelcomeBinding dataBinding; // public WelcomeViewHolder(View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // } // } // Path: app/src/main/java/com/tyq/jiemian/adapter/MainAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.SpanWatcher; import android.view.LayoutInflater; import android.view.ViewGroup; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.VH.IsReadViewHolder; import com.tyq.jiemian.adapter.VH.PopularViewHolder; import com.tyq.jiemian.adapter.VH.WelcomeViewHolder; package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/1. */ public class MainAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater; private final static int WELCOME_VIEW = 0; private final static int ISREADED_VIEW = 1; private final static int POPULAR_VIEW = 2; private final static int HISTORY_VIEW = 3; public MainAdapter(Context context) { this.context = context; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType){ case WELCOME_VIEW:
return new WelcomeViewHolder(inflater.inflate(R.layout.item_welcome,parent,false));
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/MainAdapter.java
// Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java // public class IsReadViewHolder extends RecyclerView.ViewHolder { // // private ItemIsReadBinding dataBinding; // private IsReadAdapter adapter; // public IsReadViewHolder(Context context,View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // adapter = new IsReadAdapter(context); // List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList(); // adapter.addAll(haveReadList); // dataBinding.recyclerView.setAdapter(adapter); // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java // public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { // private ItemPopularListBinding dataBinding; // private PopularListAdapter adapter; // private HomePresenter presenter; // // public PopularViewHolder(Context context, View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context); // manager.setOrientation(LinearLayoutManager.HORIZONTAL); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // presenter = new HomePresenter(context); // presenter.requestPopularList(this); // adapter = new PopularListAdapter(context); // dataBinding.recyclerView.setAdapter(adapter); // } // // @Override // public void onRequestPopularNewsSuccess(PopularNews news) { // adapter.addAll(news); // } // // @Override // public void onRequestPopularNewsFailed(String errMsg) { // // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/WelcomeViewHolder.java // public class WelcomeViewHolder extends RecyclerView.ViewHolder { // // private ItemWelcomeBinding dataBinding; // public WelcomeViewHolder(View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.SpanWatcher; import android.view.LayoutInflater; import android.view.ViewGroup; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.VH.IsReadViewHolder; import com.tyq.jiemian.adapter.VH.PopularViewHolder; import com.tyq.jiemian.adapter.VH.WelcomeViewHolder;
package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/1. */ public class MainAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater; private final static int WELCOME_VIEW = 0; private final static int ISREADED_VIEW = 1; private final static int POPULAR_VIEW = 2; private final static int HISTORY_VIEW = 3; public MainAdapter(Context context) { this.context = context; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType){ case WELCOME_VIEW: return new WelcomeViewHolder(inflater.inflate(R.layout.item_welcome,parent,false)); case ISREADED_VIEW:
// Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java // public class IsReadViewHolder extends RecyclerView.ViewHolder { // // private ItemIsReadBinding dataBinding; // private IsReadAdapter adapter; // public IsReadViewHolder(Context context,View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // adapter = new IsReadAdapter(context); // List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList(); // adapter.addAll(haveReadList); // dataBinding.recyclerView.setAdapter(adapter); // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java // public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { // private ItemPopularListBinding dataBinding; // private PopularListAdapter adapter; // private HomePresenter presenter; // // public PopularViewHolder(Context context, View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context); // manager.setOrientation(LinearLayoutManager.HORIZONTAL); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // presenter = new HomePresenter(context); // presenter.requestPopularList(this); // adapter = new PopularListAdapter(context); // dataBinding.recyclerView.setAdapter(adapter); // } // // @Override // public void onRequestPopularNewsSuccess(PopularNews news) { // adapter.addAll(news); // } // // @Override // public void onRequestPopularNewsFailed(String errMsg) { // // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/WelcomeViewHolder.java // public class WelcomeViewHolder extends RecyclerView.ViewHolder { // // private ItemWelcomeBinding dataBinding; // public WelcomeViewHolder(View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // } // } // Path: app/src/main/java/com/tyq/jiemian/adapter/MainAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.SpanWatcher; import android.view.LayoutInflater; import android.view.ViewGroup; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.VH.IsReadViewHolder; import com.tyq.jiemian.adapter.VH.PopularViewHolder; import com.tyq.jiemian.adapter.VH.WelcomeViewHolder; package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/1. */ public class MainAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater; private final static int WELCOME_VIEW = 0; private final static int ISREADED_VIEW = 1; private final static int POPULAR_VIEW = 2; private final static int HISTORY_VIEW = 3; public MainAdapter(Context context) { this.context = context; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType){ case WELCOME_VIEW: return new WelcomeViewHolder(inflater.inflate(R.layout.item_welcome,parent,false)); case ISREADED_VIEW:
return new IsReadViewHolder(context,inflater.inflate(R.layout.item_is_read,parent,false));
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/MainAdapter.java
// Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java // public class IsReadViewHolder extends RecyclerView.ViewHolder { // // private ItemIsReadBinding dataBinding; // private IsReadAdapter adapter; // public IsReadViewHolder(Context context,View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // adapter = new IsReadAdapter(context); // List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList(); // adapter.addAll(haveReadList); // dataBinding.recyclerView.setAdapter(adapter); // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java // public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { // private ItemPopularListBinding dataBinding; // private PopularListAdapter adapter; // private HomePresenter presenter; // // public PopularViewHolder(Context context, View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context); // manager.setOrientation(LinearLayoutManager.HORIZONTAL); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // presenter = new HomePresenter(context); // presenter.requestPopularList(this); // adapter = new PopularListAdapter(context); // dataBinding.recyclerView.setAdapter(adapter); // } // // @Override // public void onRequestPopularNewsSuccess(PopularNews news) { // adapter.addAll(news); // } // // @Override // public void onRequestPopularNewsFailed(String errMsg) { // // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/WelcomeViewHolder.java // public class WelcomeViewHolder extends RecyclerView.ViewHolder { // // private ItemWelcomeBinding dataBinding; // public WelcomeViewHolder(View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.SpanWatcher; import android.view.LayoutInflater; import android.view.ViewGroup; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.VH.IsReadViewHolder; import com.tyq.jiemian.adapter.VH.PopularViewHolder; import com.tyq.jiemian.adapter.VH.WelcomeViewHolder;
package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/1. */ public class MainAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater; private final static int WELCOME_VIEW = 0; private final static int ISREADED_VIEW = 1; private final static int POPULAR_VIEW = 2; private final static int HISTORY_VIEW = 3; public MainAdapter(Context context) { this.context = context; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType){ case WELCOME_VIEW: return new WelcomeViewHolder(inflater.inflate(R.layout.item_welcome,parent,false)); case ISREADED_VIEW: return new IsReadViewHolder(context,inflater.inflate(R.layout.item_is_read,parent,false)); case POPULAR_VIEW:
// Path: app/src/main/java/com/tyq/jiemian/adapter/VH/IsReadViewHolder.java // public class IsReadViewHolder extends RecyclerView.ViewHolder { // // private ItemIsReadBinding dataBinding; // private IsReadAdapter adapter; // public IsReadViewHolder(Context context,View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,true); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // adapter = new IsReadAdapter(context); // List<HaveRead> haveReadList = DBUtils.getInstance(context).getHaveReadList(); // adapter.addAll(haveReadList); // dataBinding.recyclerView.setAdapter(adapter); // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java // public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { // private ItemPopularListBinding dataBinding; // private PopularListAdapter adapter; // private HomePresenter presenter; // // public PopularViewHolder(Context context, View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // LinearLayoutManager manager = new LinearLayoutManager(context); // manager.setOrientation(LinearLayoutManager.HORIZONTAL); // dataBinding.recyclerView.setHasFixedSize(true); // dataBinding.recyclerView.setLayoutManager(manager); // presenter = new HomePresenter(context); // presenter.requestPopularList(this); // adapter = new PopularListAdapter(context); // dataBinding.recyclerView.setAdapter(adapter); // } // // @Override // public void onRequestPopularNewsSuccess(PopularNews news) { // adapter.addAll(news); // } // // @Override // public void onRequestPopularNewsFailed(String errMsg) { // // } // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/WelcomeViewHolder.java // public class WelcomeViewHolder extends RecyclerView.ViewHolder { // // private ItemWelcomeBinding dataBinding; // public WelcomeViewHolder(View itemView) { // super(itemView); // dataBinding = DataBindingUtil.bind(itemView); // } // } // Path: app/src/main/java/com/tyq/jiemian/adapter/MainAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.SpanWatcher; import android.view.LayoutInflater; import android.view.ViewGroup; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.VH.IsReadViewHolder; import com.tyq.jiemian.adapter.VH.PopularViewHolder; import com.tyq.jiemian.adapter.VH.WelcomeViewHolder; package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/1. */ public class MainAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater; private final static int WELCOME_VIEW = 0; private final static int ISREADED_VIEW = 1; private final static int POPULAR_VIEW = 2; private final static int HISTORY_VIEW = 3; public MainAdapter(Context context) { this.context = context; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType){ case WELCOME_VIEW: return new WelcomeViewHolder(inflater.inflate(R.layout.item_welcome,parent,false)); case ISREADED_VIEW: return new IsReadViewHolder(context,inflater.inflate(R.layout.item_is_read,parent,false)); case POPULAR_VIEW:
return new PopularViewHolder(context,inflater.inflate(R.layout.item_popular_list,parent,false));
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/SearchResultAdapter.java
// Path: app/src/main/java/com/tyq/jiemian/bean/SearchItem.java // public class SearchItem implements Serializable{ // // private int return_count; // private int has_more; // private int offset; // // private List<DataEntity> data; // // public int getReturn_count() { // return return_count; // } // // public void setReturn_count(int return_count) { // this.return_count = return_count; // } // // public int getHas_more() { // return has_more; // } // // public void setHas_more(int has_more) { // this.has_more = has_more; // } // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public List<DataEntity> getData() { // return data; // } // // public void setData(List<DataEntity> data) { // this.data = data; // } // // public static class DataEntity implements Serializable{ // private String title; // @SerializedName("abstract") // private String abstractX; // private String url; // private String datetime; // private String img_url; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAbstractX() { // return abstractX; // } // // public void setAbstractX(String abstractX) { // this.abstractX = abstractX; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getImg_url() { // return img_url; // } // // public void setImg_url(String img_url) { // this.img_url = img_url; // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/Constant.java // public class Constant { // public static final String TITLE = "title"; // public static final String TECHNOLOGICAL_URL = "http://www.jiemian.com/lists/6.html"; // public static final String ENTERTAINMENT_URL = "http://www.jiemian.com/lists/25.html"; // public static final String NEWS_ITEM = "news_item"; // public static final String NEWS_TITLE = "news_title"; // public static final String Bmob_App_ID = "2cb3bdc19bf6e2240dbb8ae06a80cc24"; // public static final String BASE_ZHIHU_URL = "http://news-at.zhihu.com/"; // public static final String ITEM_ID = "item_id"; // public static final String DB_NAME = "news_db"; // public static final String NEWS_URL = "new_url"; // public static final String POPULAR_NEWS_URL = "http://apis.baidu.com/3023/weixin/channel"; // public static final String POPULAR_API_KEY = "891eeffe6f1b4652128542bb8c9971a2"; // public static final String TRC_ROBOT_REC = "嗨,我是智能聊天机器人小er,聊两块钱的"; // public static final String TRC_ROBOT_REST = "小er已经休息,请明天再聊。"; // public static final String TRC_ROBOT_FAILED = "暂时无法回应"; // public static final String TRC_KEY = "ae536b38aa743f17ecb5f0e65a8dfea9"; // public static final String TRC_USER_ID = "diffey"; // public static final String SEARCH_URL = "http://apis.baidu.com/songshuxiansheng/real_time/search_news"; // public static final String SEARCH_ITEM = "search_item"; // }
import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.nostra13.universalimageloader.core.ImageLoader; import com.tyq.jiemian.R; import com.tyq.jiemian.bean.SearchItem; import com.tyq.jiemian.databinding.ItemSearchResultBinding; import com.tyq.jiemian.utils.Constant; import java.util.List;
package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/15. */ public class SearchResultAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater;
// Path: app/src/main/java/com/tyq/jiemian/bean/SearchItem.java // public class SearchItem implements Serializable{ // // private int return_count; // private int has_more; // private int offset; // // private List<DataEntity> data; // // public int getReturn_count() { // return return_count; // } // // public void setReturn_count(int return_count) { // this.return_count = return_count; // } // // public int getHas_more() { // return has_more; // } // // public void setHas_more(int has_more) { // this.has_more = has_more; // } // // public int getOffset() { // return offset; // } // // public void setOffset(int offset) { // this.offset = offset; // } // // public List<DataEntity> getData() { // return data; // } // // public void setData(List<DataEntity> data) { // this.data = data; // } // // public static class DataEntity implements Serializable{ // private String title; // @SerializedName("abstract") // private String abstractX; // private String url; // private String datetime; // private String img_url; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAbstractX() { // return abstractX; // } // // public void setAbstractX(String abstractX) { // this.abstractX = abstractX; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getImg_url() { // return img_url; // } // // public void setImg_url(String img_url) { // this.img_url = img_url; // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/Constant.java // public class Constant { // public static final String TITLE = "title"; // public static final String TECHNOLOGICAL_URL = "http://www.jiemian.com/lists/6.html"; // public static final String ENTERTAINMENT_URL = "http://www.jiemian.com/lists/25.html"; // public static final String NEWS_ITEM = "news_item"; // public static final String NEWS_TITLE = "news_title"; // public static final String Bmob_App_ID = "2cb3bdc19bf6e2240dbb8ae06a80cc24"; // public static final String BASE_ZHIHU_URL = "http://news-at.zhihu.com/"; // public static final String ITEM_ID = "item_id"; // public static final String DB_NAME = "news_db"; // public static final String NEWS_URL = "new_url"; // public static final String POPULAR_NEWS_URL = "http://apis.baidu.com/3023/weixin/channel"; // public static final String POPULAR_API_KEY = "891eeffe6f1b4652128542bb8c9971a2"; // public static final String TRC_ROBOT_REC = "嗨,我是智能聊天机器人小er,聊两块钱的"; // public static final String TRC_ROBOT_REST = "小er已经休息,请明天再聊。"; // public static final String TRC_ROBOT_FAILED = "暂时无法回应"; // public static final String TRC_KEY = "ae536b38aa743f17ecb5f0e65a8dfea9"; // public static final String TRC_USER_ID = "diffey"; // public static final String SEARCH_URL = "http://apis.baidu.com/songshuxiansheng/real_time/search_news"; // public static final String SEARCH_ITEM = "search_item"; // } // Path: app/src/main/java/com/tyq/jiemian/adapter/SearchResultAdapter.java import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.nostra13.universalimageloader.core.ImageLoader; import com.tyq.jiemian.R; import com.tyq.jiemian.bean.SearchItem; import com.tyq.jiemian.databinding.ItemSearchResultBinding; import com.tyq.jiemian.utils.Constant; import java.util.List; package com.tyq.jiemian.adapter; /** * Created by tyq on 2016/6/15. */ public class SearchResultAdapter extends RecyclerView.Adapter { private Context context; private LayoutInflater inflater;
private SearchItem searchItem;
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java
// Path: app/src/main/java/com/tyq/jiemian/adapter/PopularListAdapter.java // public class PopularListAdapter extends RecyclerView.Adapter { // // private PopularNews popularNews; // private LayoutInflater inflater; // private Context context; // public PopularListAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(PopularNews popularNews){ // this.popularNews = popularNews; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new PopularViewHolder(context,inflater.inflate(R.layout.item_popular_news,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof PopularViewHolder){ // ((PopularViewHolder) holder).updateUi(popularNews.getArticle().get(position)); // } // } // // @Override // public int getItemCount() { // return popularNews == null ? 0 : popularNews.getArticle().size() > 10 ? 10 : popularNews.getArticle().size(); // } // // static class PopularViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemPopularNewsBinding dataBinding; // private PopularNews.ArticleEntity article; // private Context context; // // public PopularViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // public void updateUi(PopularNews.ArticleEntity article){ // this.article = article; // dataBinding.setArticle(article); // ImageLoader.getInstance().displayImage(article.getImg(),dataBinding.image); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,article.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/presenter/HomePresenter.java // public class HomePresenter extends BasePresenter { // private Context context; // // public HomePresenter(Context context) { // super(context); // this.context = context; // } // // public void requestPopularList(final HomeInterface homeInterface) { // Type type = new TypeToken<BaseVolleyResponse<PopularNews>>() { // }.getType(); // String url = Constant.POPULAR_NEWS_URL; // Map<String, Object> mParams = new HashMap<>(); // mParams.put("id", "recomm"); // mParams.put("page", "1"); // VolleyGetRequest<BaseVolleyResponse<PopularNews>> request = new VolleyGetRequest<BaseVolleyResponse<PopularNews>>(context, url, mParams, type, new Response.Listener<BaseVolleyResponse<PopularNews>>() { // @Override // public void onResponse(BaseVolleyResponse<PopularNews> response) { // homeInterface.onRequestPopularNewsSuccess(response.getData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // homeInterface.onRequestPopularNewsFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // // } // // public void requestSearchResult(String keyWord, final SearchInterface searchInterface){ // Type type = new TypeToken<BaseSearchResponse<SearchItem>>(){}.getType(); // String url = Constant.SEARCH_URL; // Map<String,Object> mParams = new HashMap<>(); // mParams.put("keyword",keyWord); // mParams.put("page",1); // mParams.put("count",20); // VolleyHttpRequest<BaseSearchResponse<SearchItem>> request = new VolleyGetRequest<BaseSearchResponse<SearchItem>>(context, url, mParams, type, new Response.Listener<BaseSearchResponse<SearchItem>>() { // @Override // public void onResponse(BaseSearchResponse<SearchItem> response) { // searchInterface.onSearchResultSuccess(response.getRetData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // searchInterface.onSearchResultFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // } // } // // Path: app/src/main/java/com/tyq/jiemian/ui/callback/HomeInterface.java // public interface HomeInterface { // void onRequestPopularNewsSuccess(PopularNews news); // // void onRequestPopularNewsFailed(String errMsg); // }
import android.content.Context; import android.databinding.DataBindingUtil; import android.databinding.tool.util.L; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.jiemian.adapter.PopularListAdapter; import com.tyq.jiemian.bean.PopularNews; import com.tyq.jiemian.databinding.ItemPopularListBinding; import com.tyq.jiemian.presenter.HomePresenter; import com.tyq.jiemian.ui.callback.HomeInterface;
package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/4. */ public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { private ItemPopularListBinding dataBinding;
// Path: app/src/main/java/com/tyq/jiemian/adapter/PopularListAdapter.java // public class PopularListAdapter extends RecyclerView.Adapter { // // private PopularNews popularNews; // private LayoutInflater inflater; // private Context context; // public PopularListAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(PopularNews popularNews){ // this.popularNews = popularNews; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new PopularViewHolder(context,inflater.inflate(R.layout.item_popular_news,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof PopularViewHolder){ // ((PopularViewHolder) holder).updateUi(popularNews.getArticle().get(position)); // } // } // // @Override // public int getItemCount() { // return popularNews == null ? 0 : popularNews.getArticle().size() > 10 ? 10 : popularNews.getArticle().size(); // } // // static class PopularViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemPopularNewsBinding dataBinding; // private PopularNews.ArticleEntity article; // private Context context; // // public PopularViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // public void updateUi(PopularNews.ArticleEntity article){ // this.article = article; // dataBinding.setArticle(article); // ImageLoader.getInstance().displayImage(article.getImg(),dataBinding.image); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,article.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/presenter/HomePresenter.java // public class HomePresenter extends BasePresenter { // private Context context; // // public HomePresenter(Context context) { // super(context); // this.context = context; // } // // public void requestPopularList(final HomeInterface homeInterface) { // Type type = new TypeToken<BaseVolleyResponse<PopularNews>>() { // }.getType(); // String url = Constant.POPULAR_NEWS_URL; // Map<String, Object> mParams = new HashMap<>(); // mParams.put("id", "recomm"); // mParams.put("page", "1"); // VolleyGetRequest<BaseVolleyResponse<PopularNews>> request = new VolleyGetRequest<BaseVolleyResponse<PopularNews>>(context, url, mParams, type, new Response.Listener<BaseVolleyResponse<PopularNews>>() { // @Override // public void onResponse(BaseVolleyResponse<PopularNews> response) { // homeInterface.onRequestPopularNewsSuccess(response.getData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // homeInterface.onRequestPopularNewsFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // // } // // public void requestSearchResult(String keyWord, final SearchInterface searchInterface){ // Type type = new TypeToken<BaseSearchResponse<SearchItem>>(){}.getType(); // String url = Constant.SEARCH_URL; // Map<String,Object> mParams = new HashMap<>(); // mParams.put("keyword",keyWord); // mParams.put("page",1); // mParams.put("count",20); // VolleyHttpRequest<BaseSearchResponse<SearchItem>> request = new VolleyGetRequest<BaseSearchResponse<SearchItem>>(context, url, mParams, type, new Response.Listener<BaseSearchResponse<SearchItem>>() { // @Override // public void onResponse(BaseSearchResponse<SearchItem> response) { // searchInterface.onSearchResultSuccess(response.getRetData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // searchInterface.onSearchResultFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // } // } // // Path: app/src/main/java/com/tyq/jiemian/ui/callback/HomeInterface.java // public interface HomeInterface { // void onRequestPopularNewsSuccess(PopularNews news); // // void onRequestPopularNewsFailed(String errMsg); // } // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java import android.content.Context; import android.databinding.DataBindingUtil; import android.databinding.tool.util.L; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.jiemian.adapter.PopularListAdapter; import com.tyq.jiemian.bean.PopularNews; import com.tyq.jiemian.databinding.ItemPopularListBinding; import com.tyq.jiemian.presenter.HomePresenter; import com.tyq.jiemian.ui.callback.HomeInterface; package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/4. */ public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { private ItemPopularListBinding dataBinding;
private PopularListAdapter adapter;
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java
// Path: app/src/main/java/com/tyq/jiemian/adapter/PopularListAdapter.java // public class PopularListAdapter extends RecyclerView.Adapter { // // private PopularNews popularNews; // private LayoutInflater inflater; // private Context context; // public PopularListAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(PopularNews popularNews){ // this.popularNews = popularNews; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new PopularViewHolder(context,inflater.inflate(R.layout.item_popular_news,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof PopularViewHolder){ // ((PopularViewHolder) holder).updateUi(popularNews.getArticle().get(position)); // } // } // // @Override // public int getItemCount() { // return popularNews == null ? 0 : popularNews.getArticle().size() > 10 ? 10 : popularNews.getArticle().size(); // } // // static class PopularViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemPopularNewsBinding dataBinding; // private PopularNews.ArticleEntity article; // private Context context; // // public PopularViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // public void updateUi(PopularNews.ArticleEntity article){ // this.article = article; // dataBinding.setArticle(article); // ImageLoader.getInstance().displayImage(article.getImg(),dataBinding.image); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,article.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/presenter/HomePresenter.java // public class HomePresenter extends BasePresenter { // private Context context; // // public HomePresenter(Context context) { // super(context); // this.context = context; // } // // public void requestPopularList(final HomeInterface homeInterface) { // Type type = new TypeToken<BaseVolleyResponse<PopularNews>>() { // }.getType(); // String url = Constant.POPULAR_NEWS_URL; // Map<String, Object> mParams = new HashMap<>(); // mParams.put("id", "recomm"); // mParams.put("page", "1"); // VolleyGetRequest<BaseVolleyResponse<PopularNews>> request = new VolleyGetRequest<BaseVolleyResponse<PopularNews>>(context, url, mParams, type, new Response.Listener<BaseVolleyResponse<PopularNews>>() { // @Override // public void onResponse(BaseVolleyResponse<PopularNews> response) { // homeInterface.onRequestPopularNewsSuccess(response.getData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // homeInterface.onRequestPopularNewsFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // // } // // public void requestSearchResult(String keyWord, final SearchInterface searchInterface){ // Type type = new TypeToken<BaseSearchResponse<SearchItem>>(){}.getType(); // String url = Constant.SEARCH_URL; // Map<String,Object> mParams = new HashMap<>(); // mParams.put("keyword",keyWord); // mParams.put("page",1); // mParams.put("count",20); // VolleyHttpRequest<BaseSearchResponse<SearchItem>> request = new VolleyGetRequest<BaseSearchResponse<SearchItem>>(context, url, mParams, type, new Response.Listener<BaseSearchResponse<SearchItem>>() { // @Override // public void onResponse(BaseSearchResponse<SearchItem> response) { // searchInterface.onSearchResultSuccess(response.getRetData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // searchInterface.onSearchResultFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // } // } // // Path: app/src/main/java/com/tyq/jiemian/ui/callback/HomeInterface.java // public interface HomeInterface { // void onRequestPopularNewsSuccess(PopularNews news); // // void onRequestPopularNewsFailed(String errMsg); // }
import android.content.Context; import android.databinding.DataBindingUtil; import android.databinding.tool.util.L; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.jiemian.adapter.PopularListAdapter; import com.tyq.jiemian.bean.PopularNews; import com.tyq.jiemian.databinding.ItemPopularListBinding; import com.tyq.jiemian.presenter.HomePresenter; import com.tyq.jiemian.ui.callback.HomeInterface;
package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/4. */ public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { private ItemPopularListBinding dataBinding; private PopularListAdapter adapter;
// Path: app/src/main/java/com/tyq/jiemian/adapter/PopularListAdapter.java // public class PopularListAdapter extends RecyclerView.Adapter { // // private PopularNews popularNews; // private LayoutInflater inflater; // private Context context; // public PopularListAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // public void addAll(PopularNews popularNews){ // this.popularNews = popularNews; // notifyDataSetChanged(); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new PopularViewHolder(context,inflater.inflate(R.layout.item_popular_news,parent,false)); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof PopularViewHolder){ // ((PopularViewHolder) holder).updateUi(popularNews.getArticle().get(position)); // } // } // // @Override // public int getItemCount() { // return popularNews == null ? 0 : popularNews.getArticle().size() > 10 ? 10 : popularNews.getArticle().size(); // } // // static class PopularViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { // private ItemPopularNewsBinding dataBinding; // private PopularNews.ArticleEntity article; // private Context context; // // public PopularViewHolder(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // public void updateUi(PopularNews.ArticleEntity article){ // this.article = article; // dataBinding.setArticle(article); // ImageLoader.getInstance().displayImage(article.getImg(),dataBinding.image); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,article.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/presenter/HomePresenter.java // public class HomePresenter extends BasePresenter { // private Context context; // // public HomePresenter(Context context) { // super(context); // this.context = context; // } // // public void requestPopularList(final HomeInterface homeInterface) { // Type type = new TypeToken<BaseVolleyResponse<PopularNews>>() { // }.getType(); // String url = Constant.POPULAR_NEWS_URL; // Map<String, Object> mParams = new HashMap<>(); // mParams.put("id", "recomm"); // mParams.put("page", "1"); // VolleyGetRequest<BaseVolleyResponse<PopularNews>> request = new VolleyGetRequest<BaseVolleyResponse<PopularNews>>(context, url, mParams, type, new Response.Listener<BaseVolleyResponse<PopularNews>>() { // @Override // public void onResponse(BaseVolleyResponse<PopularNews> response) { // homeInterface.onRequestPopularNewsSuccess(response.getData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // homeInterface.onRequestPopularNewsFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // // } // // public void requestSearchResult(String keyWord, final SearchInterface searchInterface){ // Type type = new TypeToken<BaseSearchResponse<SearchItem>>(){}.getType(); // String url = Constant.SEARCH_URL; // Map<String,Object> mParams = new HashMap<>(); // mParams.put("keyword",keyWord); // mParams.put("page",1); // mParams.put("count",20); // VolleyHttpRequest<BaseSearchResponse<SearchItem>> request = new VolleyGetRequest<BaseSearchResponse<SearchItem>>(context, url, mParams, type, new Response.Listener<BaseSearchResponse<SearchItem>>() { // @Override // public void onResponse(BaseSearchResponse<SearchItem> response) { // searchInterface.onSearchResultSuccess(response.getRetData()); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // searchInterface.onSearchResultFailed(handlerException(error)); // } // }); // httpClient.addToRequestQueue(request); // } // } // // Path: app/src/main/java/com/tyq/jiemian/ui/callback/HomeInterface.java // public interface HomeInterface { // void onRequestPopularNewsSuccess(PopularNews news); // // void onRequestPopularNewsFailed(String errMsg); // } // Path: app/src/main/java/com/tyq/jiemian/adapter/VH/PopularViewHolder.java import android.content.Context; import android.databinding.DataBindingUtil; import android.databinding.tool.util.L; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import com.tyq.jiemian.adapter.PopularListAdapter; import com.tyq.jiemian.bean.PopularNews; import com.tyq.jiemian.databinding.ItemPopularListBinding; import com.tyq.jiemian.presenter.HomePresenter; import com.tyq.jiemian.ui.callback.HomeInterface; package com.tyq.jiemian.adapter.VH; /** * Created by tyq on 2016/6/4. */ public class PopularViewHolder extends RecyclerView.ViewHolder implements HomeInterface { private ItemPopularListBinding dataBinding; private PopularListAdapter adapter;
private HomePresenter presenter;
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/ui/fragment/CollectFragment.java
// Path: app/src/main/java-gen/com/tyq/greendao/Collect.java // public class Collect { // // private Long id; // private String title; // private String imageUrl; // private String url; // private java.util.Date time; // // public Collect() { // } // // public Collect(Long id) { // this.id = id; // } // // public Collect(Long id, String title, String imageUrl, String url, java.util.Date time) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // this.time = time; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public java.util.Date getTime() { // return time; // } // // public void setTime(java.util.Date time) { // this.time = time; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/CollectAdapter.java // public class CollectAdapter extends RecyclerView.Adapter { // // private List<Collect> collectList; // private LayoutInflater inflater; // private Context context; // public CollectAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new CollectVH(context,inflater.inflate(R.layout.item_collect,parent,false)); // } // // public void addAll(List<Collect> collectList){ // this.collectList = collectList; // notifyDataSetChanged(); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof CollectVH){ // ((CollectVH) holder).updateUi(collectList.get(position)); // } // } // // @Override // public int getItemCount() { // return collectList.size(); // } // // static class CollectVH extends RecyclerView.ViewHolder implements View.OnClickListener { // // private ItemCollectBinding dataBinding; // private Collect collect; // private Context context; // public CollectVH(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(Collect collect){ // this.collect = collect; // ImageLoader.getInstance().displayImage(collect.getImageUrl(),dataBinding.image); // dataBinding.setTitle(collect.getTitle()); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,collect.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.tyq.greendao.Collect; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.CollectAdapter; import com.tyq.jiemian.databinding.FragmentCollectBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List;
package com.tyq.jiemian.ui.fragment; public class CollectFragment extends BaseFragment { private FragmentCollectBinding dataBinding;
// Path: app/src/main/java-gen/com/tyq/greendao/Collect.java // public class Collect { // // private Long id; // private String title; // private String imageUrl; // private String url; // private java.util.Date time; // // public Collect() { // } // // public Collect(Long id) { // this.id = id; // } // // public Collect(Long id, String title, String imageUrl, String url, java.util.Date time) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // this.time = time; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public java.util.Date getTime() { // return time; // } // // public void setTime(java.util.Date time) { // this.time = time; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/CollectAdapter.java // public class CollectAdapter extends RecyclerView.Adapter { // // private List<Collect> collectList; // private LayoutInflater inflater; // private Context context; // public CollectAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new CollectVH(context,inflater.inflate(R.layout.item_collect,parent,false)); // } // // public void addAll(List<Collect> collectList){ // this.collectList = collectList; // notifyDataSetChanged(); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof CollectVH){ // ((CollectVH) holder).updateUi(collectList.get(position)); // } // } // // @Override // public int getItemCount() { // return collectList.size(); // } // // static class CollectVH extends RecyclerView.ViewHolder implements View.OnClickListener { // // private ItemCollectBinding dataBinding; // private Collect collect; // private Context context; // public CollectVH(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(Collect collect){ // this.collect = collect; // ImageLoader.getInstance().displayImage(collect.getImageUrl(),dataBinding.image); // dataBinding.setTitle(collect.getTitle()); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,collect.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // } // Path: app/src/main/java/com/tyq/jiemian/ui/fragment/CollectFragment.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.tyq.greendao.Collect; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.CollectAdapter; import com.tyq.jiemian.databinding.FragmentCollectBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List; package com.tyq.jiemian.ui.fragment; public class CollectFragment extends BaseFragment { private FragmentCollectBinding dataBinding;
private CollectAdapter adapter;
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/ui/fragment/CollectFragment.java
// Path: app/src/main/java-gen/com/tyq/greendao/Collect.java // public class Collect { // // private Long id; // private String title; // private String imageUrl; // private String url; // private java.util.Date time; // // public Collect() { // } // // public Collect(Long id) { // this.id = id; // } // // public Collect(Long id, String title, String imageUrl, String url, java.util.Date time) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // this.time = time; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public java.util.Date getTime() { // return time; // } // // public void setTime(java.util.Date time) { // this.time = time; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/CollectAdapter.java // public class CollectAdapter extends RecyclerView.Adapter { // // private List<Collect> collectList; // private LayoutInflater inflater; // private Context context; // public CollectAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new CollectVH(context,inflater.inflate(R.layout.item_collect,parent,false)); // } // // public void addAll(List<Collect> collectList){ // this.collectList = collectList; // notifyDataSetChanged(); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof CollectVH){ // ((CollectVH) holder).updateUi(collectList.get(position)); // } // } // // @Override // public int getItemCount() { // return collectList.size(); // } // // static class CollectVH extends RecyclerView.ViewHolder implements View.OnClickListener { // // private ItemCollectBinding dataBinding; // private Collect collect; // private Context context; // public CollectVH(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(Collect collect){ // this.collect = collect; // ImageLoader.getInstance().displayImage(collect.getImageUrl(),dataBinding.image); // dataBinding.setTitle(collect.getTitle()); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,collect.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.tyq.greendao.Collect; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.CollectAdapter; import com.tyq.jiemian.databinding.FragmentCollectBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List;
package com.tyq.jiemian.ui.fragment; public class CollectFragment extends BaseFragment { private FragmentCollectBinding dataBinding; private CollectAdapter adapter; public CollectFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_collect, container, false); adapter = new CollectAdapter(getActivity()); dataBinding.recyclerView.setAdapter(adapter); return dataBinding.getRoot(); } public void onTabSelected() {
// Path: app/src/main/java-gen/com/tyq/greendao/Collect.java // public class Collect { // // private Long id; // private String title; // private String imageUrl; // private String url; // private java.util.Date time; // // public Collect() { // } // // public Collect(Long id) { // this.id = id; // } // // public Collect(Long id, String title, String imageUrl, String url, java.util.Date time) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // this.time = time; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public java.util.Date getTime() { // return time; // } // // public void setTime(java.util.Date time) { // this.time = time; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/CollectAdapter.java // public class CollectAdapter extends RecyclerView.Adapter { // // private List<Collect> collectList; // private LayoutInflater inflater; // private Context context; // public CollectAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new CollectVH(context,inflater.inflate(R.layout.item_collect,parent,false)); // } // // public void addAll(List<Collect> collectList){ // this.collectList = collectList; // notifyDataSetChanged(); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof CollectVH){ // ((CollectVH) holder).updateUi(collectList.get(position)); // } // } // // @Override // public int getItemCount() { // return collectList.size(); // } // // static class CollectVH extends RecyclerView.ViewHolder implements View.OnClickListener { // // private ItemCollectBinding dataBinding; // private Collect collect; // private Context context; // public CollectVH(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(Collect collect){ // this.collect = collect; // ImageLoader.getInstance().displayImage(collect.getImageUrl(),dataBinding.image); // dataBinding.setTitle(collect.getTitle()); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,collect.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // } // Path: app/src/main/java/com/tyq/jiemian/ui/fragment/CollectFragment.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.tyq.greendao.Collect; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.CollectAdapter; import com.tyq.jiemian.databinding.FragmentCollectBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List; package com.tyq.jiemian.ui.fragment; public class CollectFragment extends BaseFragment { private FragmentCollectBinding dataBinding; private CollectAdapter adapter; public CollectFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_collect, container, false); adapter = new CollectAdapter(getActivity()); dataBinding.recyclerView.setAdapter(adapter); return dataBinding.getRoot(); } public void onTabSelected() {
List<Collect> collects = DBUtils.getInstance(getActivity()).getCollectList();
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/ui/fragment/CollectFragment.java
// Path: app/src/main/java-gen/com/tyq/greendao/Collect.java // public class Collect { // // private Long id; // private String title; // private String imageUrl; // private String url; // private java.util.Date time; // // public Collect() { // } // // public Collect(Long id) { // this.id = id; // } // // public Collect(Long id, String title, String imageUrl, String url, java.util.Date time) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // this.time = time; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public java.util.Date getTime() { // return time; // } // // public void setTime(java.util.Date time) { // this.time = time; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/CollectAdapter.java // public class CollectAdapter extends RecyclerView.Adapter { // // private List<Collect> collectList; // private LayoutInflater inflater; // private Context context; // public CollectAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new CollectVH(context,inflater.inflate(R.layout.item_collect,parent,false)); // } // // public void addAll(List<Collect> collectList){ // this.collectList = collectList; // notifyDataSetChanged(); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof CollectVH){ // ((CollectVH) holder).updateUi(collectList.get(position)); // } // } // // @Override // public int getItemCount() { // return collectList.size(); // } // // static class CollectVH extends RecyclerView.ViewHolder implements View.OnClickListener { // // private ItemCollectBinding dataBinding; // private Collect collect; // private Context context; // public CollectVH(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(Collect collect){ // this.collect = collect; // ImageLoader.getInstance().displayImage(collect.getImageUrl(),dataBinding.image); // dataBinding.setTitle(collect.getTitle()); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,collect.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // }
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.tyq.greendao.Collect; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.CollectAdapter; import com.tyq.jiemian.databinding.FragmentCollectBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List;
package com.tyq.jiemian.ui.fragment; public class CollectFragment extends BaseFragment { private FragmentCollectBinding dataBinding; private CollectAdapter adapter; public CollectFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_collect, container, false); adapter = new CollectAdapter(getActivity()); dataBinding.recyclerView.setAdapter(adapter); return dataBinding.getRoot(); } public void onTabSelected() {
// Path: app/src/main/java-gen/com/tyq/greendao/Collect.java // public class Collect { // // private Long id; // private String title; // private String imageUrl; // private String url; // private java.util.Date time; // // public Collect() { // } // // public Collect(Long id) { // this.id = id; // } // // public Collect(Long id, String title, String imageUrl, String url, java.util.Date time) { // this.id = id; // this.title = title; // this.imageUrl = imageUrl; // this.url = url; // this.time = time; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public java.util.Date getTime() { // return time; // } // // public void setTime(java.util.Date time) { // this.time = time; // } // // } // // Path: app/src/main/java/com/tyq/jiemian/adapter/CollectAdapter.java // public class CollectAdapter extends RecyclerView.Adapter { // // private List<Collect> collectList; // private LayoutInflater inflater; // private Context context; // public CollectAdapter(Context context) { // this.context = context; // inflater = LayoutInflater.from(context); // } // // @Override // public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // return new CollectVH(context,inflater.inflate(R.layout.item_collect,parent,false)); // } // // public void addAll(List<Collect> collectList){ // this.collectList = collectList; // notifyDataSetChanged(); // } // // @Override // public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // if (holder instanceof CollectVH){ // ((CollectVH) holder).updateUi(collectList.get(position)); // } // } // // @Override // public int getItemCount() { // return collectList.size(); // } // // static class CollectVH extends RecyclerView.ViewHolder implements View.OnClickListener { // // private ItemCollectBinding dataBinding; // private Collect collect; // private Context context; // public CollectVH(Context context,View itemView) { // super(itemView); // this.context = context; // dataBinding = DataBindingUtil.bind(itemView); // itemView.setOnClickListener(this); // } // // public void updateUi(Collect collect){ // this.collect = collect; // ImageLoader.getInstance().displayImage(collect.getImageUrl(),dataBinding.image); // dataBinding.setTitle(collect.getTitle()); // } // // @Override // public void onClick(View v) { // Intent intent = new Intent(context, JmDetailActivity.class); // intent.putExtra(Constant.NEWS_URL,collect.getUrl()); // context.startActivity(intent); // } // } // } // // Path: app/src/main/java/com/tyq/jiemian/utils/DBUtils.java // public class DBUtils { // // private static DBUtils instance; // private HaveReadDao haveReadDao; // private CollectDao collectDao; // // public static DBUtils getInstance(Context context) { // if (instance == null) { // instance = new DBUtils(); // DaoSession daoSession = JMApplication.getDaoSession(context); // instance.haveReadDao = daoSession.getHaveReadDao(); // instance.collectDao = daoSession.getCollectDao(); // } // return instance; // } // // //添加数据(已读新闻) // public void addNewsToHaveRead(HaveRead haveRead) { // haveReadDao.insert(haveRead); // } // // public List<HaveRead> getHaveReadList() { // QueryBuilder<HaveRead> qb = haveReadDao.queryBuilder(); // return qb.list(); // } // // //插入收藏数据 // public void addNewsToCollect(Collect collect) { // collectDao.insert(collect); // } // // public List<Collect> getCollectList() { // QueryBuilder<Collect> qb = collectDao.queryBuilder(); // return qb.list(); // } // // public void delectNews(Collect collect){ // collectDao.delete(collect); // } // } // Path: app/src/main/java/com/tyq/jiemian/ui/fragment/CollectFragment.java import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.tyq.greendao.Collect; import com.tyq.jiemian.R; import com.tyq.jiemian.adapter.CollectAdapter; import com.tyq.jiemian.databinding.FragmentCollectBinding; import com.tyq.jiemian.utils.DBUtils; import java.util.List; package com.tyq.jiemian.ui.fragment; public class CollectFragment extends BaseFragment { private FragmentCollectBinding dataBinding; private CollectAdapter adapter; public CollectFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_collect, container, false); adapter = new CollectAdapter(getActivity()); dataBinding.recyclerView.setAdapter(adapter); return dataBinding.getRoot(); } public void onTabSelected() {
List<Collect> collects = DBUtils.getInstance(getActivity()).getCollectList();
Tangyingqi/Jiemian
app/src/main/java/com/tyq/jiemian/utils/UserProxy.java
// Path: app/src/main/java/com/tyq/jiemian/bean/User.java // public class User extends BmobUser { // // private String nickName; // private String sex; // private String signature; // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getSignature() { // return signature; // } // // public void setSignature(String signature) { // this.signature = signature; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // }
import android.content.Context; import android.util.Log; import com.tyq.jiemian.bean.User; import cn.bmob.v3.BmobUser; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener;
package com.tyq.jiemian.utils; /** * Created by tyq on 2015/11/25. */ public class UserProxy { public interface LoginAndRegisterInterface{ void onSuccess(); void onFailure(String msg); } public interface UpdateInfoInterface{ void onSuccess(); void onFailure(String msg); } public UpdateInfoInterface updateInfoInterface; public static void register(Context context,String username,String password, final LoginAndRegisterInterface loginAndRegisterInterface){
// Path: app/src/main/java/com/tyq/jiemian/bean/User.java // public class User extends BmobUser { // // private String nickName; // private String sex; // private String signature; // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getSignature() { // return signature; // } // // public void setSignature(String signature) { // this.signature = signature; // } // // public String getNickName() { // return nickName; // } // // public void setNickName(String nickName) { // this.nickName = nickName; // } // } // Path: app/src/main/java/com/tyq/jiemian/utils/UserProxy.java import android.content.Context; import android.util.Log; import com.tyq.jiemian.bean.User; import cn.bmob.v3.BmobUser; import cn.bmob.v3.listener.SaveListener; import cn.bmob.v3.listener.UpdateListener; package com.tyq.jiemian.utils; /** * Created by tyq on 2015/11/25. */ public class UserProxy { public interface LoginAndRegisterInterface{ void onSuccess(); void onFailure(String msg); } public interface UpdateInfoInterface{ void onSuccess(); void onFailure(String msg); } public UpdateInfoInterface updateInfoInterface; public static void register(Context context,String username,String password, final LoginAndRegisterInterface loginAndRegisterInterface){
User user = new User();
EpicEricEE/ShopChest
src/main/java/de/epiceric/shopchest/language/BookGenerationName.java
// Path: src/main/java/de/epiceric/shopchest/nms/CustomBookMeta.java // public class CustomBookMeta { // private static final OBCClassResolver obcClassResolver = new OBCClassResolver(); // // public enum Generation { // ORIGINAL, // COPY_OF_ORIGINAL, // COPY_OF_COPY, // TATTERED // } // // public static Generation getGeneration(ItemStack book) { // try { // Class<?> craftItemStackClass = obcClassResolver.resolveSilent("inventory.CraftItemStack"); // // if (craftItemStackClass == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: Could not find CraftItemStack class"); // return null; // } // // Object nmsStack = craftItemStackClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, book); // // Object nbtTagCompound = nmsStack.getClass().getMethod("getTag").invoke(nmsStack); // if (nbtTagCompound == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: getTag returned null"); // return null; // } // // Object generationObject = nbtTagCompound.getClass().getMethod("getInt", String.class).invoke(nbtTagCompound, "generation"); // if (generationObject == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: getInt returned null"); // return null; // } // // if (generationObject instanceof Integer) { // int generation = (Integer) generationObject; // // if (generation > 3) generation = 3; // // return Generation.values()[generation]; // } // // } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // ShopChest.getInstance().getLogger().severe("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug(e); // } // // return null; // } // // public static void setGeneration(ItemStack book, Generation generation) { // try { // Class<?> craftItemStackClass = obcClassResolver.resolveSilent("inventory.CraftItemStack"); // // if (craftItemStackClass == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: Could not find CraftItemStack class"); // return; // } // // Object nmsStack = craftItemStackClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, book); // // Object nbtTagCompound = nmsStack.getClass().getMethod("getTag").invoke(nmsStack); // if (nbtTagCompound == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: getTag returned null"); // return; // } // // nbtTagCompound.getClass().getMethod("setInt", String.class, int.class) // .invoke(nbtTagCompound, "generation", generation.ordinal()); // // nmsStack.getClass().getMethod("setTag", nbtTagCompound.getClass()).invoke(nmsStack, nbtTagCompound); // // } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // ShopChest.getInstance().getLogger().severe("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug(e); // } // } // // }
import de.epiceric.shopchest.nms.CustomBookMeta;
package de.epiceric.shopchest.language; public class BookGenerationName { private String localizedName;
// Path: src/main/java/de/epiceric/shopchest/nms/CustomBookMeta.java // public class CustomBookMeta { // private static final OBCClassResolver obcClassResolver = new OBCClassResolver(); // // public enum Generation { // ORIGINAL, // COPY_OF_ORIGINAL, // COPY_OF_COPY, // TATTERED // } // // public static Generation getGeneration(ItemStack book) { // try { // Class<?> craftItemStackClass = obcClassResolver.resolveSilent("inventory.CraftItemStack"); // // if (craftItemStackClass == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: Could not find CraftItemStack class"); // return null; // } // // Object nmsStack = craftItemStackClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, book); // // Object nbtTagCompound = nmsStack.getClass().getMethod("getTag").invoke(nmsStack); // if (nbtTagCompound == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: getTag returned null"); // return null; // } // // Object generationObject = nbtTagCompound.getClass().getMethod("getInt", String.class).invoke(nbtTagCompound, "generation"); // if (generationObject == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: getInt returned null"); // return null; // } // // if (generationObject instanceof Integer) { // int generation = (Integer) generationObject; // // if (generation > 3) generation = 3; // // return Generation.values()[generation]; // } // // } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // ShopChest.getInstance().getLogger().severe("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug(e); // } // // return null; // } // // public static void setGeneration(ItemStack book, Generation generation) { // try { // Class<?> craftItemStackClass = obcClassResolver.resolveSilent("inventory.CraftItemStack"); // // if (craftItemStackClass == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: Could not find CraftItemStack class"); // return; // } // // Object nmsStack = craftItemStackClass.getMethod("asNMSCopy", ItemStack.class).invoke(null, book); // // Object nbtTagCompound = nmsStack.getClass().getMethod("getTag").invoke(nmsStack); // if (nbtTagCompound == null) { // ShopChest.getInstance().debug("Failed to get NBTGeneration: getTag returned null"); // return; // } // // nbtTagCompound.getClass().getMethod("setInt", String.class, int.class) // .invoke(nbtTagCompound, "generation", generation.ordinal()); // // nmsStack.getClass().getMethod("setTag", nbtTagCompound.getClass()).invoke(nmsStack, nbtTagCompound); // // } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // ShopChest.getInstance().getLogger().severe("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug("Failed to get NBTEntityID with reflection"); // ShopChest.getInstance().debug(e); // } // } // // } // Path: src/main/java/de/epiceric/shopchest/language/BookGenerationName.java import de.epiceric.shopchest.nms.CustomBookMeta; package de.epiceric.shopchest.language; public class BookGenerationName { private String localizedName;
private CustomBookMeta.Generation generation;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry;
package com.wmz7year.synyed.parser.entry; /** * redis hash类型的对象 * * @Title: RedisHashObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午5:05:17 * @version V1.0 */ public class RedisHashObject extends RedisObject { private Map<RedisObject, RedisObject> elements = new HashMap<RedisObject, RedisObject>(); public RedisHashObject() { } /** * 添加元素的方法 * * @param field * field * @param value * value */ public void addElement(RedisObject field, RedisObject value) { if (!(field instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } if (!(value instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.put(field, value); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; package com.wmz7year.synyed.parser.entry; /** * redis hash类型的对象 * * @Title: RedisHashObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午5:05:17 * @version V1.0 */ public class RedisHashObject extends RedisObject { private Map<RedisObject, RedisObject> elements = new HashMap<RedisObject, RedisObject>(); public RedisHashObject() { } /** * 添加元素的方法 * * @param field * field * @param value * value */ public void addElement(RedisObject field, RedisObject value) { if (!(field instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } if (!(value instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.put(field, value); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
return REDIS_HASH;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry;
package com.wmz7year.synyed.parser.entry; /** * redis hash类型的对象 * * @Title: RedisHashObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午5:05:17 * @version V1.0 */ public class RedisHashObject extends RedisObject { private Map<RedisObject, RedisObject> elements = new HashMap<RedisObject, RedisObject>(); public RedisHashObject() { } /** * 添加元素的方法 * * @param field * field * @param value * value */ public void addElement(RedisObject field, RedisObject value) { if (!(field instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } if (!(value instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.put(field, value); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_HASH; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; package com.wmz7year.synyed.parser.entry; /** * redis hash类型的对象 * * @Title: RedisHashObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午5:05:17 * @version V1.0 */ public class RedisHashObject extends RedisObject { private Map<RedisObject, RedisObject> elements = new HashMap<RedisObject, RedisObject>(); public RedisHashObject() { } /** * 添加元素的方法 * * @param field * field * @param value * value */ public void addElement(RedisObject field, RedisObject value) { if (!(field instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } if (!(value instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.put(field, value); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_HASH; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
return REDIS_ENCODING_ZIPLIST;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // }
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException;
package com.wmz7year.synyed.parser.entry; /** * redis hash zipmap类型数据结构对象 * * @Title: RedisHashZipMap.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月18日 上午11:30:08 * @version V1.0 */ public class RedisHashZipMap extends RedisObject { /** * 空格占位符 */ private static final byte FREE = 0x00; /** * hash zipmap数据 */ private byte[] buffer; private ByteArrayInputStream bis = null; /** * zip map中的元素长度 */ private int zmLen = 0; /** * 当前所包含的元素数量 */ private int entryCount = 0; /** * 解析出的元素列表 */ private Map<String, String> elements = new HashMap<String, String>();
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException; package com.wmz7year.synyed.parser.entry; /** * redis hash zipmap类型数据结构对象 * * @Title: RedisHashZipMap.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月18日 上午11:30:08 * @version V1.0 */ public class RedisHashZipMap extends RedisObject { /** * 空格占位符 */ private static final byte FREE = 0x00; /** * hash zipmap数据 */ private byte[] buffer; private ByteArrayInputStream bis = null; /** * zip map中的元素长度 */ private int zmLen = 0; /** * 当前所包含的元素数量 */ private int entryCount = 0; /** * 解析出的元素列表 */ private Map<String, String> elements = new HashMap<String, String>();
public RedisHashZipMap(byte[] buffer) throws RedisRDBException {
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // }
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException;
return new String(buffer); } /** * 读取元素数量的方法 * * @return 包含的元素数量 * @throws RedisRDBException * 当解析发生问题时抛出该异常 */ private int readEntryLength() throws RedisRDBException { return readLength(); } /** * 读取长度的方法<br> * 先读取1个字节 如果该字节内容为0xFD 则接着向后读取4个字节转换为int作为长度 * * @return 读取到的长度 * @throws RedisRDBException * 当读取发生错误时抛出该异常 */ private int readLength() throws RedisRDBException { byte b = readByte(); if (b == 0xFD) { // 接着读取4个字节转换为int byte[] buffer = new byte[4]; if (!readBytes(buffer, 0, 4)) { throw new RedisRDBException("解析错误"); }
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException; return new String(buffer); } /** * 读取元素数量的方法 * * @return 包含的元素数量 * @throws RedisRDBException * 当解析发生问题时抛出该异常 */ private int readEntryLength() throws RedisRDBException { return readLength(); } /** * 读取长度的方法<br> * 先读取1个字节 如果该字节内容为0xFD 则接着向后读取4个字节转换为int作为长度 * * @return 读取到的长度 * @throws RedisRDBException * 当读取发生错误时抛出该异常 */ private int readLength() throws RedisRDBException { byte b = readByte(); if (b == 0xFD) { // 接着读取4个字节转换为int byte[] buffer = new byte[4]; if (!readBytes(buffer, 0, 4)) { throw new RedisRDBException("解析错误"); }
return byte2Int(buffer);
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // }
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException;
return readLength(); } /** * 读取长度的方法<br> * 先读取1个字节 如果该字节内容为0xFD 则接着向后读取4个字节转换为int作为长度 * * @return 读取到的长度 * @throws RedisRDBException * 当读取发生错误时抛出该异常 */ private int readLength() throws RedisRDBException { byte b = readByte(); if (b == 0xFD) { // 接着读取4个字节转换为int byte[] buffer = new byte[4]; if (!readBytes(buffer, 0, 4)) { throw new RedisRDBException("解析错误"); } return byte2Int(buffer); } else { return b; } } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException; return readLength(); } /** * 读取长度的方法<br> * 先读取1个字节 如果该字节内容为0xFD 则接着向后读取4个字节转换为int作为长度 * * @return 读取到的长度 * @throws RedisRDBException * 当读取发生错误时抛出该异常 */ private int readLength() throws RedisRDBException { byte b = readByte(); if (b == 0xFD) { // 接着读取4个字节转换为int byte[] buffer = new byte[4]; if (!readBytes(buffer, 0, 4)) { throw new RedisRDBException("解析错误"); } return byte2Int(buffer); } else { return b; } } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
return REDIS_HASH;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // }
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException;
* @throws RedisRDBException * 当读取发生错误时抛出该异常 */ private int readLength() throws RedisRDBException { byte b = readByte(); if (b == 0xFD) { // 接着读取4个字节转换为int byte[] buffer = new byte[4]; if (!readBytes(buffer, 0, 4)) { throw new RedisRDBException("解析错误"); } return byte2Int(buffer); } else { return b; } } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_HASH; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_ZIPLIST = 5; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_HASH = 4; // // Path: Redis-Synyed-util/src/main/java/com/wmz7year/synyed/util/NumberUtil.java // public static int byte2Int(byte[] buffer) { // if (buffer == null) { // throw new NullPointerException(); // } // if (buffer.length != 4) { // throw new IllegalArgumentException( // "Error buffer length can not cover bytes to int:" + Arrays.toString(buffer)); // } // return (((buffer[3]) << 24) | ((buffer[2] & 0xff) << 16) | ((buffer[1] & 0xff) << 8) | ((buffer[0] & 0xff))); // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisHashZipMap.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_ZIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_HASH; import static com.wmz7year.synyed.util.NumberUtil.byte2Int; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import com.wmz7year.synyed.exception.RedisRDBException; * @throws RedisRDBException * 当读取发生错误时抛出该异常 */ private int readLength() throws RedisRDBException { byte b = readByte(); if (b == 0xFD) { // 接着读取4个字节转换为int byte[] buffer = new byte[4]; if (!readBytes(buffer, 0, 4)) { throw new RedisRDBException("解析错误"); } return byte2Int(buffer); } else { return b; } } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_HASH; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
return REDIS_ENCODING_ZIPLIST;
wmz7year/Redis-Synyed
Redis-Synyed-Agent/src/main/java/com/wmz7year/synyed/net/proroc/RedisProtocolDecoder.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisProtocolConstant.java // public static final String REDIS_PROTOCOL_PARSER = "redis_protpcol_parser"; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/packet/redis/RedisPacket.java // public abstract class RedisPacket { // /** // * redis命令 // */ // protected String command; // // public RedisPacket(String command) { // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // /** // * 获取数据包原始数据的方法 // * // * @return 数据包原始数据 // */ // public abstract byte[] getData(); // }
import static com.wmz7year.synyed.constant.RedisProtocolConstant.REDIS_PROTOCOL_PARSER; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import com.wmz7year.synyed.packet.redis.RedisPacket;
package com.wmz7year.synyed.net.proroc; /** * redis协议解析器<br> * * @Title: RedisProtocolDecoder.java * @Package com.wmz7year.synyed.net.proroc * @author jiangwei ([email protected]) * @date 2015年12月10日 下午4:59:13 * @version V1.0 */ public class RedisProtocolDecoder extends CumulativeProtocolDecoder { /* * @see org.apache.mina.filter.codec.CumulativeProtocolDecoder#doDecode(org. * apache.mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer, * org.apache.mina.filter.codec.ProtocolDecoderOutput) */ @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisProtocolConstant.java // public static final String REDIS_PROTOCOL_PARSER = "redis_protpcol_parser"; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/packet/redis/RedisPacket.java // public abstract class RedisPacket { // /** // * redis命令 // */ // protected String command; // // public RedisPacket(String command) { // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // /** // * 获取数据包原始数据的方法 // * // * @return 数据包原始数据 // */ // public abstract byte[] getData(); // } // Path: Redis-Synyed-Agent/src/main/java/com/wmz7year/synyed/net/proroc/RedisProtocolDecoder.java import static com.wmz7year.synyed.constant.RedisProtocolConstant.REDIS_PROTOCOL_PARSER; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import com.wmz7year.synyed.packet.redis.RedisPacket; package com.wmz7year.synyed.net.proroc; /** * redis协议解析器<br> * * @Title: RedisProtocolDecoder.java * @Package com.wmz7year.synyed.net.proroc * @author jiangwei ([email protected]) * @date 2015年12月10日 下午4:59:13 * @version V1.0 */ public class RedisProtocolDecoder extends CumulativeProtocolDecoder { /* * @see org.apache.mina.filter.codec.CumulativeProtocolDecoder#doDecode(org. * apache.mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer, * org.apache.mina.filter.codec.ProtocolDecoderOutput) */ @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
RedisProtocolParser parser = (RedisProtocolParser) session.getAttribute(REDIS_PROTOCOL_PARSER);
wmz7year/Redis-Synyed
Redis-Synyed-Agent/src/main/java/com/wmz7year/synyed/net/proroc/RedisProtocolDecoder.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisProtocolConstant.java // public static final String REDIS_PROTOCOL_PARSER = "redis_protpcol_parser"; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/packet/redis/RedisPacket.java // public abstract class RedisPacket { // /** // * redis命令 // */ // protected String command; // // public RedisPacket(String command) { // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // /** // * 获取数据包原始数据的方法 // * // * @return 数据包原始数据 // */ // public abstract byte[] getData(); // }
import static com.wmz7year.synyed.constant.RedisProtocolConstant.REDIS_PROTOCOL_PARSER; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import com.wmz7year.synyed.packet.redis.RedisPacket;
package com.wmz7year.synyed.net.proroc; /** * redis协议解析器<br> * * @Title: RedisProtocolDecoder.java * @Package com.wmz7year.synyed.net.proroc * @author jiangwei ([email protected]) * @date 2015年12月10日 下午4:59:13 * @version V1.0 */ public class RedisProtocolDecoder extends CumulativeProtocolDecoder { /* * @see org.apache.mina.filter.codec.CumulativeProtocolDecoder#doDecode(org. * apache.mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer, * org.apache.mina.filter.codec.ProtocolDecoderOutput) */ @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { RedisProtocolParser parser = (RedisProtocolParser) session.getAttribute(REDIS_PROTOCOL_PARSER); // 将接收到的数据通过解析器解析为Redis数据包对象 parser.read(in.buf()); // 获取解析器解析出的数据包
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisProtocolConstant.java // public static final String REDIS_PROTOCOL_PARSER = "redis_protpcol_parser"; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/packet/redis/RedisPacket.java // public abstract class RedisPacket { // /** // * redis命令 // */ // protected String command; // // public RedisPacket(String command) { // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // /** // * 获取数据包原始数据的方法 // * // * @return 数据包原始数据 // */ // public abstract byte[] getData(); // } // Path: Redis-Synyed-Agent/src/main/java/com/wmz7year/synyed/net/proroc/RedisProtocolDecoder.java import static com.wmz7year.synyed.constant.RedisProtocolConstant.REDIS_PROTOCOL_PARSER; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import com.wmz7year.synyed.packet.redis.RedisPacket; package com.wmz7year.synyed.net.proroc; /** * redis协议解析器<br> * * @Title: RedisProtocolDecoder.java * @Package com.wmz7year.synyed.net.proroc * @author jiangwei ([email protected]) * @date 2015年12月10日 下午4:59:13 * @version V1.0 */ public class RedisProtocolDecoder extends CumulativeProtocolDecoder { /* * @see org.apache.mina.filter.codec.CumulativeProtocolDecoder#doDecode(org. * apache.mina.core.session.IoSession, org.apache.mina.core.buffer.IoBuffer, * org.apache.mina.filter.codec.ProtocolDecoderOutput) */ @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { RedisProtocolParser parser = (RedisProtocolParser) session.getAttribute(REDIS_PROTOCOL_PARSER); // 将接收到的数据通过解析器解析为Redis数据包对象 parser.read(in.buf()); // 获取解析器解析出的数据包
RedisPacket[] redisPackets = parser.getPackets();
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisListObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_LINKEDLIST = 4; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_LIST = 1;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_LINKEDLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_LIST; import java.util.ArrayList; import java.util.List;
package com.wmz7year.synyed.parser.entry; /** * redis list类型数据结构对象 * * @Title: RedisListObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:39:53 * @version V1.0 */ public class RedisListObject extends RedisObject { /** * list中的元素 */ private List<RedisStringObject> elements = new ArrayList<RedisStringObject>(); public RedisListObject() { } /** * 添加list中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_LINKEDLIST = 4; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_LIST = 1; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisListObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_LINKEDLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_LIST; import java.util.ArrayList; import java.util.List; package com.wmz7year.synyed.parser.entry; /** * redis list类型数据结构对象 * * @Title: RedisListObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:39:53 * @version V1.0 */ public class RedisListObject extends RedisObject { /** * list中的元素 */ private List<RedisStringObject> elements = new ArrayList<RedisStringObject>(); public RedisListObject() { } /** * 添加list中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
return REDIS_LIST;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisListObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_LINKEDLIST = 4; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_LIST = 1;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_LINKEDLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_LIST; import java.util.ArrayList; import java.util.List;
package com.wmz7year.synyed.parser.entry; /** * redis list类型数据结构对象 * * @Title: RedisListObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:39:53 * @version V1.0 */ public class RedisListObject extends RedisObject { /** * list中的元素 */ private List<RedisStringObject> elements = new ArrayList<RedisStringObject>(); public RedisListObject() { } /** * 添加list中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_LIST; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_LINKEDLIST = 4; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_LIST = 1; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisListObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_LINKEDLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_LIST; import java.util.ArrayList; import java.util.List; package com.wmz7year.synyed.parser.entry; /** * redis list类型数据结构对象 * * @Title: RedisListObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:39:53 * @version V1.0 */ public class RedisListObject extends RedisObject { /** * list中的元素 */ private List<RedisStringObject> elements = new ArrayList<RedisStringObject>(); public RedisListObject() { } /** * 添加list中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_LIST; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
return REDIS_ENCODING_LINKEDLIST;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/RDBParser.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisDB.java // public class RedisDB { // /** // * 数据库编号 // */ // private int num; // /** // * rdb中的命令列表 // */ // private List<RedisCommand> command = new ArrayList<RedisCommand>(); // // public RedisDB(int num) { // this.num = num; // } // // public int getNum() { // return num; // } // // public void setNum(int num) { // this.num = num; // } // // /** // * 添加redis命令的方法<br> // * 将命令对象添加到命令集合中 // * // * @param rdbCommand // * redis命令对象 // */ // public void addCommand(RedisRDBCommand rdbCommand) { // command.addAll(rdbCommand.getCommands()); // } // // /** // * 获取rdb中所有需要同步的命令列表的方法 // * // * @return redis命令列表集合 // */ // public List<RedisCommand> getCommands() { // return this.command; // } // // }
import java.util.Collection; import com.wmz7year.synyed.exception.RedisRDBException; import com.wmz7year.synyed.parser.entry.RedisDB;
package com.wmz7year.synyed.parser; /** * Redis rdb文件解析器<br> * 用于首次SYNC到redis时 redis把rdb文件内容发送过来解析成redis命令时使用<br> * 每个版本的格式都不同,实现类针对不同的版本进行 * * @Title: RDBParser.java * @Package com.wmz7year.synyed.parser * @author jiangwei ([email protected]) * @date 2015年12月14日 下午1:54:22 * @version V1.0 */ public interface RDBParser { /** * 获取rdb格式版本的方法<br> * rdb的格式版本信息为头内容的9个字节数据REDIS**** * * @return rdb内容版本 */ public String gerVersion(); /** * 执行解析的方法<br> * * @param rdbContent * rdb文件内容 * @throws RedisRDBException * 当解析过程中发生错误抛出该异常 */
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisDB.java // public class RedisDB { // /** // * 数据库编号 // */ // private int num; // /** // * rdb中的命令列表 // */ // private List<RedisCommand> command = new ArrayList<RedisCommand>(); // // public RedisDB(int num) { // this.num = num; // } // // public int getNum() { // return num; // } // // public void setNum(int num) { // this.num = num; // } // // /** // * 添加redis命令的方法<br> // * 将命令对象添加到命令集合中 // * // * @param rdbCommand // * redis命令对象 // */ // public void addCommand(RedisRDBCommand rdbCommand) { // command.addAll(rdbCommand.getCommands()); // } // // /** // * 获取rdb中所有需要同步的命令列表的方法 // * // * @return redis命令列表集合 // */ // public List<RedisCommand> getCommands() { // return this.command; // } // // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/RDBParser.java import java.util.Collection; import com.wmz7year.synyed.exception.RedisRDBException; import com.wmz7year.synyed.parser.entry.RedisDB; package com.wmz7year.synyed.parser; /** * Redis rdb文件解析器<br> * 用于首次SYNC到redis时 redis把rdb文件内容发送过来解析成redis命令时使用<br> * 每个版本的格式都不同,实现类针对不同的版本进行 * * @Title: RDBParser.java * @Package com.wmz7year.synyed.parser * @author jiangwei ([email protected]) * @date 2015年12月14日 下午1:54:22 * @version V1.0 */ public interface RDBParser { /** * 获取rdb格式版本的方法<br> * rdb的格式版本信息为头内容的9个字节数据REDIS**** * * @return rdb内容版本 */ public String gerVersion(); /** * 执行解析的方法<br> * * @param rdbContent * rdb文件内容 * @throws RedisRDBException * 当解析过程中发生错误抛出该异常 */
public void parse(byte[] rdbContent) throws RedisRDBException;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/RDBParser.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisDB.java // public class RedisDB { // /** // * 数据库编号 // */ // private int num; // /** // * rdb中的命令列表 // */ // private List<RedisCommand> command = new ArrayList<RedisCommand>(); // // public RedisDB(int num) { // this.num = num; // } // // public int getNum() { // return num; // } // // public void setNum(int num) { // this.num = num; // } // // /** // * 添加redis命令的方法<br> // * 将命令对象添加到命令集合中 // * // * @param rdbCommand // * redis命令对象 // */ // public void addCommand(RedisRDBCommand rdbCommand) { // command.addAll(rdbCommand.getCommands()); // } // // /** // * 获取rdb中所有需要同步的命令列表的方法 // * // * @return redis命令列表集合 // */ // public List<RedisCommand> getCommands() { // return this.command; // } // // }
import java.util.Collection; import com.wmz7year.synyed.exception.RedisRDBException; import com.wmz7year.synyed.parser.entry.RedisDB;
package com.wmz7year.synyed.parser; /** * Redis rdb文件解析器<br> * 用于首次SYNC到redis时 redis把rdb文件内容发送过来解析成redis命令时使用<br> * 每个版本的格式都不同,实现类针对不同的版本进行 * * @Title: RDBParser.java * @Package com.wmz7year.synyed.parser * @author jiangwei ([email protected]) * @date 2015年12月14日 下午1:54:22 * @version V1.0 */ public interface RDBParser { /** * 获取rdb格式版本的方法<br> * rdb的格式版本信息为头内容的9个字节数据REDIS**** * * @return rdb内容版本 */ public String gerVersion(); /** * 执行解析的方法<br> * * @param rdbContent * rdb文件内容 * @throws RedisRDBException * 当解析过程中发生错误抛出该异常 */ public void parse(byte[] rdbContent) throws RedisRDBException; /** * 获取解析出的数据库列表的方法 * * @return redis数据库列表 */
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisDB.java // public class RedisDB { // /** // * 数据库编号 // */ // private int num; // /** // * rdb中的命令列表 // */ // private List<RedisCommand> command = new ArrayList<RedisCommand>(); // // public RedisDB(int num) { // this.num = num; // } // // public int getNum() { // return num; // } // // public void setNum(int num) { // this.num = num; // } // // /** // * 添加redis命令的方法<br> // * 将命令对象添加到命令集合中 // * // * @param rdbCommand // * redis命令对象 // */ // public void addCommand(RedisRDBCommand rdbCommand) { // command.addAll(rdbCommand.getCommands()); // } // // /** // * 获取rdb中所有需要同步的命令列表的方法 // * // * @return redis命令列表集合 // */ // public List<RedisCommand> getCommands() { // return this.command; // } // // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/RDBParser.java import java.util.Collection; import com.wmz7year.synyed.exception.RedisRDBException; import com.wmz7year.synyed.parser.entry.RedisDB; package com.wmz7year.synyed.parser; /** * Redis rdb文件解析器<br> * 用于首次SYNC到redis时 redis把rdb文件内容发送过来解析成redis命令时使用<br> * 每个版本的格式都不同,实现类针对不同的版本进行 * * @Title: RDBParser.java * @Package com.wmz7year.synyed.parser * @author jiangwei ([email protected]) * @date 2015年12月14日 下午1:54:22 * @version V1.0 */ public interface RDBParser { /** * 获取rdb格式版本的方法<br> * rdb的格式版本信息为头内容的9个字节数据REDIS**** * * @return rdb内容版本 */ public String gerVersion(); /** * 执行解析的方法<br> * * @param rdbContent * rdb文件内容 * @throws RedisRDBException * 当解析过程中发生错误抛出该异常 */ public void parse(byte[] rdbContent) throws RedisRDBException; /** * 获取解析出的数据库列表的方法 * * @return redis数据库列表 */
public Collection<RedisDB> getRedisDBs();
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisZSetObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_SKIPLIST = 7; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ZSET = 3;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_SKIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ZSET; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package com.wmz7year.synyed.parser.entry; /** * redis zset类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisZSetObject extends RedisObject { private List<ZSetValue> elements = null; public RedisZSetObject(int zsetlen) { this.elements = new ArrayList<ZSetValue>(zsetlen); } /** * 向指定位置插入元素的方法 * * @param redisObject * 需要插入的元素 * @param score * 指定的位置 */ public void addElement(RedisObject redisObject, double score) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.add(new ZSetValue(redisObject, score)); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_SKIPLIST = 7; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ZSET = 3; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisZSetObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_SKIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ZSET; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; package com.wmz7year.synyed.parser.entry; /** * redis zset类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisZSetObject extends RedisObject { private List<ZSetValue> elements = null; public RedisZSetObject(int zsetlen) { this.elements = new ArrayList<ZSetValue>(zsetlen); } /** * 向指定位置插入元素的方法 * * @param redisObject * 需要插入的元素 * @param score * 指定的位置 */ public void addElement(RedisObject redisObject, double score) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.add(new ZSetValue(redisObject, score)); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
return REDIS_ZSET;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisZSetObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_SKIPLIST = 7; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ZSET = 3;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_SKIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ZSET; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package com.wmz7year.synyed.parser.entry; /** * redis zset类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisZSetObject extends RedisObject { private List<ZSetValue> elements = null; public RedisZSetObject(int zsetlen) { this.elements = new ArrayList<ZSetValue>(zsetlen); } /** * 向指定位置插入元素的方法 * * @param redisObject * 需要插入的元素 * @param score * 指定的位置 */ public void addElement(RedisObject redisObject, double score) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.add(new ZSetValue(redisObject, score)); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_ZSET; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_SKIPLIST = 7; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ZSET = 3; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisZSetObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_SKIPLIST; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ZSET; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; package com.wmz7year.synyed.parser.entry; /** * redis zset类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisZSetObject extends RedisObject { private List<ZSetValue> elements = null; public RedisZSetObject(int zsetlen) { this.elements = new ArrayList<ZSetValue>(zsetlen); } /** * 向指定位置插入元素的方法 * * @param redisObject * 需要插入的元素 * @param score * 指定的位置 */ public void addElement(RedisObject redisObject, double score) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } elements.add(new ZSetValue(redisObject, score)); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_ZSET; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
return REDIS_ENCODING_SKIPLIST;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisStringObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_RAW = 0; /* Raw representation */ // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_STRING = 0;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_RAW; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_STRING;
package com.wmz7year.synyed.parser.entry; /** * Redis 字符串类型数据对象 * * @Title: RedisStringObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:20:59 * @version V1.0 */ public class RedisStringObject extends RedisObject { /** * string字符串数据 */ private byte[] data; public RedisStringObject(byte[] data) { this.data = data; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_RAW = 0; /* Raw representation */ // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_STRING = 0; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisStringObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_RAW; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_STRING; package com.wmz7year.synyed.parser.entry; /** * Redis 字符串类型数据对象 * * @Title: RedisStringObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:20:59 * @version V1.0 */ public class RedisStringObject extends RedisObject { /** * string字符串数据 */ private byte[] data; public RedisStringObject(byte[] data) { this.data = data; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
return REDIS_STRING;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisStringObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_RAW = 0; /* Raw representation */ // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_STRING = 0;
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_RAW; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_STRING;
package com.wmz7year.synyed.parser.entry; /** * Redis 字符串类型数据对象 * * @Title: RedisStringObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:20:59 * @version V1.0 */ public class RedisStringObject extends RedisObject { /** * string字符串数据 */ private byte[] data; public RedisStringObject(byte[] data) { this.data = data; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_STRING; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_RAW = 0; /* Raw representation */ // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_STRING = 0; // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisStringObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_RAW; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_STRING; package com.wmz7year.synyed.parser.entry; /** * Redis 字符串类型数据对象 * * @Title: RedisStringObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午1:20:59 * @version V1.0 */ public class RedisStringObject extends RedisObject { /** * string字符串数据 */ private byte[] data; public RedisStringObject(byte[] data) { this.data = data; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_STRING; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
return REDIS_ENCODING_RAW;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisDB.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommand.java // public class RedisCommand { // /** // * 命令 // */ // private String command; // /** // * value // */ // private List<RedisCommandData> values = new ArrayList<RedisCommandData>(); // // public RedisCommand(String command) { // this.command = command; // } // // /** // * 添加值的方法<br> // * // * @param value // * 需要添加的值 // */ // public void addValue(byte[] value) { // this.values.add(new RedisCommandData(value)); // } // // public void addValue(String value) { // addValue(value.getBytes()); // } // // /** // * 获取命令所占的空间大小的方法<br> // * 空间大小为命令+key+values的长度 // * // * @return 所占的空间大小 // */ // public int getSize() { // int result = 0; // result += command.length(); // for (RedisCommandData value : values) { // result += value.getData().length; // } // return result; // } // // public String getCommand() { // return this.command; // } // // public void setCommand(String command) { // this.command = command; // } // // public List<RedisCommandData> getValues() { // return this.values; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommand [command=" + command + ",values=" + values + "]"; // } // // }
import java.util.ArrayList; import java.util.List; import com.wmz7year.synyed.entity.RedisCommand;
package com.wmz7year.synyed.parser.entry; /** * 封装Redis 数据库信息的实体类<br> * * @Title: RedisDB.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月15日 下午3:17:53 * @version V1.0 */ public class RedisDB { /** * 数据库编号 */ private int num; /** * rdb中的命令列表 */
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommand.java // public class RedisCommand { // /** // * 命令 // */ // private String command; // /** // * value // */ // private List<RedisCommandData> values = new ArrayList<RedisCommandData>(); // // public RedisCommand(String command) { // this.command = command; // } // // /** // * 添加值的方法<br> // * // * @param value // * 需要添加的值 // */ // public void addValue(byte[] value) { // this.values.add(new RedisCommandData(value)); // } // // public void addValue(String value) { // addValue(value.getBytes()); // } // // /** // * 获取命令所占的空间大小的方法<br> // * 空间大小为命令+key+values的长度 // * // * @return 所占的空间大小 // */ // public int getSize() { // int result = 0; // result += command.length(); // for (RedisCommandData value : values) { // result += value.getData().length; // } // return result; // } // // public String getCommand() { // return this.command; // } // // public void setCommand(String command) { // this.command = command; // } // // public List<RedisCommandData> getValues() { // return this.values; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommand [command=" + command + ",values=" + values + "]"; // } // // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisDB.java import java.util.ArrayList; import java.util.List; import com.wmz7year.synyed.entity.RedisCommand; package com.wmz7year.synyed.parser.entry; /** * 封装Redis 数据库信息的实体类<br> * * @Title: RedisDB.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月15日 下午3:17:53 * @version V1.0 */ public class RedisDB { /** * 数据库编号 */ private int num; /** * rdb中的命令列表 */
private List<RedisCommand> command = new ArrayList<RedisCommand>();
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisSetObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_HT = 3; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_RDB_TYPE_SET = 2; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommandData.java // public class RedisCommandData { // /** // * 原始数据 // */ // private byte[] data; // /** // * 转换为字符串后的数据 // */ // private String content; // // public RedisCommandData(byte[] data) { // super(); // this.data = data; // this.content = new String(data); // } // // public byte[] getData() { // return data; // } // // public void setData(byte[] data) { // this.data = data; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommandData [dataLength=" + data.length + ", content=" + content + "]"; // } // // }
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_HT; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_RDB_TYPE_SET; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.wmz7year.synyed.entity.RedisCommandData;
package com.wmz7year.synyed.parser.entry; /** * redis set类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisSetObject extends RedisObject { /** * set中的元素 */ private Set<RedisStringObject> elements = new HashSet<RedisStringObject>(); public RedisSetObject() { } /** * 添加set中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_HT = 3; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_RDB_TYPE_SET = 2; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommandData.java // public class RedisCommandData { // /** // * 原始数据 // */ // private byte[] data; // /** // * 转换为字符串后的数据 // */ // private String content; // // public RedisCommandData(byte[] data) { // super(); // this.data = data; // this.content = new String(data); // } // // public byte[] getData() { // return data; // } // // public void setData(byte[] data) { // this.data = data; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommandData [dataLength=" + data.length + ", content=" + content + "]"; // } // // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisSetObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_HT; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_RDB_TYPE_SET; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.wmz7year.synyed.entity.RedisCommandData; package com.wmz7year.synyed.parser.entry; /** * redis set类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisSetObject extends RedisObject { /** * set中的元素 */ private Set<RedisStringObject> elements = new HashSet<RedisStringObject>(); public RedisSetObject() { } /** * 添加set中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() {
return REDIS_RDB_TYPE_SET;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisSetObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_HT = 3; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_RDB_TYPE_SET = 2; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommandData.java // public class RedisCommandData { // /** // * 原始数据 // */ // private byte[] data; // /** // * 转换为字符串后的数据 // */ // private String content; // // public RedisCommandData(byte[] data) { // super(); // this.data = data; // this.content = new String(data); // } // // public byte[] getData() { // return data; // } // // public void setData(byte[] data) { // this.data = data; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommandData [dataLength=" + data.length + ", content=" + content + "]"; // } // // }
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_HT; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_RDB_TYPE_SET; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.wmz7year.synyed.entity.RedisCommandData;
package com.wmz7year.synyed.parser.entry; /** * redis set类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisSetObject extends RedisObject { /** * set中的元素 */ private Set<RedisStringObject> elements = new HashSet<RedisStringObject>(); public RedisSetObject() { } /** * 添加set中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_RDB_TYPE_SET; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_HT = 3; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_RDB_TYPE_SET = 2; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommandData.java // public class RedisCommandData { // /** // * 原始数据 // */ // private byte[] data; // /** // * 转换为字符串后的数据 // */ // private String content; // // public RedisCommandData(byte[] data) { // super(); // this.data = data; // this.content = new String(data); // } // // public byte[] getData() { // return data; // } // // public void setData(byte[] data) { // this.data = data; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommandData [dataLength=" + data.length + ", content=" + content + "]"; // } // // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisSetObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_HT; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_RDB_TYPE_SET; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.wmz7year.synyed.entity.RedisCommandData; package com.wmz7year.synyed.parser.entry; /** * redis set类型数据结构对象 * * @Title: RedisSetObject.java * @Package com.wmz7year.synyed.parser.entry * @author jiangwei ([email protected]) * @date 2015年12月16日 下午3:56:00 * @version V1.0 */ public class RedisSetObject extends RedisObject { /** * set中的元素 */ private Set<RedisStringObject> elements = new HashSet<RedisStringObject>(); public RedisSetObject() { } /** * 添加set中的元素的方法 * * @param redisObject * redis */ public void addElement(RedisObject redisObject) { if (!(redisObject instanceof RedisStringObject)) { throw new IllegalStateException("元素类型错误 必须为RedisStringObject类型"); } this.elements.add((RedisStringObject) redisObject); } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getType() */ @Override public byte getType() { return REDIS_RDB_TYPE_SET; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() {
return REDIS_ENCODING_HT;
wmz7year/Redis-Synyed
Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisSetObject.java
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_HT = 3; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_RDB_TYPE_SET = 2; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommandData.java // public class RedisCommandData { // /** // * 原始数据 // */ // private byte[] data; // /** // * 转换为字符串后的数据 // */ // private String content; // // public RedisCommandData(byte[] data) { // super(); // this.data = data; // this.content = new String(data); // } // // public byte[] getData() { // return data; // } // // public void setData(byte[] data) { // this.data = data; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommandData [dataLength=" + data.length + ", content=" + content + "]"; // } // // }
import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_HT; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_RDB_TYPE_SET; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.wmz7year.synyed.entity.RedisCommandData;
* @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() { return REDIS_ENCODING_HT; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#toCommand() */ @Override public String toCommand() { StringBuilder result = new StringBuilder(); for (RedisStringObject redisStringObject : elements) { result.append(redisStringObject.toCommand()).append(' '); } if (result.length() > 0 && result.charAt(result.length()) == ' ') { return result.substring(0, result.length() - 1); } return result.toString(); } /* * @see java.lang.Object#toString() */ @Override public String toString() { return "RedisSetObject [elements=" + elements + "]"; }
// Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_ENCODING_HT = 3; /* // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/constant/RedisRDBConstant.java // public static final byte REDIS_RDB_TYPE_SET = 2; // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/entity/RedisCommandData.java // public class RedisCommandData { // /** // * 原始数据 // */ // private byte[] data; // /** // * 转换为字符串后的数据 // */ // private String content; // // public RedisCommandData(byte[] data) { // super(); // this.data = data; // this.content = new String(data); // } // // public byte[] getData() { // return data; // } // // public void setData(byte[] data) { // this.data = data; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // /* // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "RedisCommandData [dataLength=" + data.length + ", content=" + content + "]"; // } // // } // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/parser/entry/RedisSetObject.java import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_ENCODING_HT; import static com.wmz7year.synyed.constant.RedisRDBConstant.REDIS_RDB_TYPE_SET; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.wmz7year.synyed.entity.RedisCommandData; * @see com.wmz7year.synyed.parser.entry.RedisObject#getEncoding() */ @Override public byte getEncoding() { return REDIS_ENCODING_HT; } /* * @see com.wmz7year.synyed.parser.entry.RedisObject#toCommand() */ @Override public String toCommand() { StringBuilder result = new StringBuilder(); for (RedisStringObject redisStringObject : elements) { result.append(redisStringObject.toCommand()).append(' '); } if (result.length() > 0 && result.charAt(result.length()) == ' ') { return result.substring(0, result.length() - 1); } return result.toString(); } /* * @see java.lang.Object#toString() */ @Override public String toString() { return "RedisSetObject [elements=" + elements + "]"; }
public List<RedisCommandData> getElements() {
wmz7year/Redis-Synyed
Redis-Synyed-Agent/src/test/java/com/wmz7year/synyed/parser/RDBParserFactoryTest.java
// Path: Redis-Synyed-Agent/src/main/java/com/wmz7year/synyed/Booter.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // public class Booter { // // public static void main(String[] args) { // SpringApplication.run(Booter.class, args); // } // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // }
import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.wmz7year.synyed.Booter; import com.wmz7year.synyed.exception.RedisRDBException;
package com.wmz7year.synyed.parser; /** * rdb文件解析器创建工厂类相关的测试 * * @Title: RDBParserFactoryTest.java * @Package com.wmz7year.synyed.parser * @author jiangwei ([email protected]) * @date 2015年12月15日 上午11:00:55 * @version V1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Booter.class) public class RDBParserFactoryTest { /** * 测试rdb头长度错误 */ @Test public void testErrorLengthRDBHeader() { byte[] rdbHeader = new byte[] { 0, 0, 0, 0, 0, 0 }; try { RDBParserFactory.createRDBParser(rdbHeader); assertTrue(false);
// Path: Redis-Synyed-Agent/src/main/java/com/wmz7year/synyed/Booter.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // public class Booter { // // public static void main(String[] args) { // SpringApplication.run(Booter.class, args); // } // } // // Path: Redis-Synyed-common/src/main/java/com/wmz7year/synyed/exception/RedisRDBException.java // public class RedisRDBException extends Exception { // private static final long serialVersionUID = -8089839086790389424L; // private Throwable nestedThrowable = null; // // public RedisRDBException() { // super(); // } // // public RedisRDBException(String msg) { // super(msg); // } // // public RedisRDBException(Throwable nestedThrowable) { // super(nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // public RedisRDBException(String msg, Throwable nestedThrowable) { // super(msg, nestedThrowable); // this.nestedThrowable = nestedThrowable; // } // // /* // * @see java.lang.Throwable#printStackTrace() // */ // @Override // public void printStackTrace() { // super.printStackTrace(); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) // */ // @Override // public void printStackTrace(PrintStream ps) { // super.printStackTrace(ps); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(ps); // } // } // // /* // * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) // */ // @Override // public void printStackTrace(PrintWriter pw) { // super.printStackTrace(pw); // if (nestedThrowable != null) { // nestedThrowable.printStackTrace(pw); // } // } // } // Path: Redis-Synyed-Agent/src/test/java/com/wmz7year/synyed/parser/RDBParserFactoryTest.java import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.wmz7year.synyed.Booter; import com.wmz7year.synyed.exception.RedisRDBException; package com.wmz7year.synyed.parser; /** * rdb文件解析器创建工厂类相关的测试 * * @Title: RDBParserFactoryTest.java * @Package com.wmz7year.synyed.parser * @author jiangwei ([email protected]) * @date 2015年12月15日 上午11:00:55 * @version V1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Booter.class) public class RDBParserFactoryTest { /** * 测试rdb头长度错误 */ @Test public void testErrorLengthRDBHeader() { byte[] rdbHeader = new byte[] { 0, 0, 0, 0, 0, 0 }; try { RDBParserFactory.createRDBParser(rdbHeader); assertTrue(false);
} catch (RedisRDBException e) {
craterdog/java-collection-framework
src/main/java/craterdog/collections/abstractions/SortableCollection.java
// Path: src/main/java/craterdog/collections/primitives/MergeSorter.java // public class MergeSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is needed // if (collection != null && collection.getSize() > 1) { // // // make sure the comparator exists // if (comparator == null) comparator = new NaturalComparator<>(); // // // convert the collection to an array // E[] array = collection.toArray(); // // // sort the array // sortArray(array, comparator); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // // } // } // // // private void sortArray(E[] array, Comparator<? super E> comparator) { // // check to see if the array is already sorted // int length = array.length; // if (length < 2) return; // // // split the array into two halves // int leftLength = length / 2; // E[] left = Arrays.copyOfRange(array, 0, leftLength); // E[] right = Arrays.copyOfRange(array, leftLength, length); // // // sort each half separately // sortArray(left, comparator); // sortArray(right, comparator); // // // merge the sorted halves back together // mergeArrays(left, right, array, comparator); // } // // // private void mergeArrays(E[] left, E[] right, E[] result, Comparator<? super E> comparator) { // int leftIndex = 0; // int rightIndex = 0; // int resultIndex = 0; // while (resultIndex < result.length) { // if (leftIndex < left.length && rightIndex < right.length) { // // still have elements in both halves // if (comparator.compare(left[leftIndex], right[rightIndex]) < 0) { // // copy the next left element to the result // result[resultIndex++] = left[leftIndex++]; // } else { // // copy the next right element to the result // result[resultIndex++] = right[rightIndex++]; // } // } else if (leftIndex < left.length) { // // copy the rest of the left half to the result // int leftRemaining = left.length - leftIndex; // System.arraycopy(left, leftIndex, result, resultIndex, leftRemaining); // leftIndex += leftRemaining; // resultIndex += leftRemaining; // } else { // // copy the rest of the right half to the result // int rightRemaining = right.length - rightIndex; // System.arraycopy(right, rightIndex, result, resultIndex, rightRemaining); // rightIndex += rightRemaining; // resultIndex += rightRemaining; // } // } // } // // } // // Path: src/main/java/craterdog/collections/primitives/RandomSorter.java // public class RandomSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is really required // if (collection != null && collection.getSize() > 1) { // if (collection instanceof List) { // // randomize it in place // @SuppressWarnings("unchecked") // List<E> indexedCollection = (List<E>) collection; // int size = collection.getSize(); // randomizeCollection(indexedCollection, size); // } else { // // convert the collection to an array // E[] array = collection.toArray(); // // // randomize the array // randomizeArray(array); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // } // } // } // // private void randomizeCollection(List<E> indexedCollection, int size) { // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index) + 1; // use ordinal based indexing // E swap = indexedCollection.getElement(index); // swap = indexedCollection.replaceElement(swap, randomIndex); // indexedCollection.replaceElement(swap, index); // } // } // // private void randomizeArray(E[] array) { // int size = array.length; // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index); // use zero based indexing // E swap = array[index - 1]; // array[index - 1] = array[randomIndex]; // array[randomIndex] = swap; // } // } // // }
import craterdog.collections.primitives.MergeSorter; import craterdog.collections.primitives.RandomSorter; import craterdog.core.Manipulator; import craterdog.utils.NaturalComparator; import java.util.Comparator; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory;
/************************************************************************ * Copyright (c) Crater Dog Technologies(TM). All Rights Reserved. * ************************************************************************ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * * * This code is free software; you can redistribute it and/or modify it * * under the terms of The MIT License (MIT), as published by the Open * * Source Initiative. (See http://opensource.org/licenses/MIT) * ************************************************************************/ package craterdog.collections.abstractions; /** * This abstract class defines the invariant methods that all sortable collections must inherit. * A sortable collection allows the order of its elements to be determined externally. By * default, the elements will be placed in the order in which they were added to the collection. * Additionally, the elements can be sorted in various ways depending on a specified sorting * algorithm and comparison function. * * @author Derk Norton * @param <E> The type of element managed by the collection. */ public abstract class SortableCollection<E> extends OpenCollection<E> { static private final XLogger logger = XLoggerFactory.getXLogger(SortableCollection.class); /** * This method shuffles the elements in the collection using a randomizing algorithm. */ public void shuffleElements() { logger.entry();
// Path: src/main/java/craterdog/collections/primitives/MergeSorter.java // public class MergeSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is needed // if (collection != null && collection.getSize() > 1) { // // // make sure the comparator exists // if (comparator == null) comparator = new NaturalComparator<>(); // // // convert the collection to an array // E[] array = collection.toArray(); // // // sort the array // sortArray(array, comparator); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // // } // } // // // private void sortArray(E[] array, Comparator<? super E> comparator) { // // check to see if the array is already sorted // int length = array.length; // if (length < 2) return; // // // split the array into two halves // int leftLength = length / 2; // E[] left = Arrays.copyOfRange(array, 0, leftLength); // E[] right = Arrays.copyOfRange(array, leftLength, length); // // // sort each half separately // sortArray(left, comparator); // sortArray(right, comparator); // // // merge the sorted halves back together // mergeArrays(left, right, array, comparator); // } // // // private void mergeArrays(E[] left, E[] right, E[] result, Comparator<? super E> comparator) { // int leftIndex = 0; // int rightIndex = 0; // int resultIndex = 0; // while (resultIndex < result.length) { // if (leftIndex < left.length && rightIndex < right.length) { // // still have elements in both halves // if (comparator.compare(left[leftIndex], right[rightIndex]) < 0) { // // copy the next left element to the result // result[resultIndex++] = left[leftIndex++]; // } else { // // copy the next right element to the result // result[resultIndex++] = right[rightIndex++]; // } // } else if (leftIndex < left.length) { // // copy the rest of the left half to the result // int leftRemaining = left.length - leftIndex; // System.arraycopy(left, leftIndex, result, resultIndex, leftRemaining); // leftIndex += leftRemaining; // resultIndex += leftRemaining; // } else { // // copy the rest of the right half to the result // int rightRemaining = right.length - rightIndex; // System.arraycopy(right, rightIndex, result, resultIndex, rightRemaining); // rightIndex += rightRemaining; // resultIndex += rightRemaining; // } // } // } // // } // // Path: src/main/java/craterdog/collections/primitives/RandomSorter.java // public class RandomSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is really required // if (collection != null && collection.getSize() > 1) { // if (collection instanceof List) { // // randomize it in place // @SuppressWarnings("unchecked") // List<E> indexedCollection = (List<E>) collection; // int size = collection.getSize(); // randomizeCollection(indexedCollection, size); // } else { // // convert the collection to an array // E[] array = collection.toArray(); // // // randomize the array // randomizeArray(array); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // } // } // } // // private void randomizeCollection(List<E> indexedCollection, int size) { // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index) + 1; // use ordinal based indexing // E swap = indexedCollection.getElement(index); // swap = indexedCollection.replaceElement(swap, randomIndex); // indexedCollection.replaceElement(swap, index); // } // } // // private void randomizeArray(E[] array) { // int size = array.length; // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index); // use zero based indexing // E swap = array[index - 1]; // array[index - 1] = array[randomIndex]; // array[randomIndex] = swap; // } // } // // } // Path: src/main/java/craterdog/collections/abstractions/SortableCollection.java import craterdog.collections.primitives.MergeSorter; import craterdog.collections.primitives.RandomSorter; import craterdog.core.Manipulator; import craterdog.utils.NaturalComparator; import java.util.Comparator; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /************************************************************************ * Copyright (c) Crater Dog Technologies(TM). All Rights Reserved. * ************************************************************************ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * * * This code is free software; you can redistribute it and/or modify it * * under the terms of The MIT License (MIT), as published by the Open * * Source Initiative. (See http://opensource.org/licenses/MIT) * ************************************************************************/ package craterdog.collections.abstractions; /** * This abstract class defines the invariant methods that all sortable collections must inherit. * A sortable collection allows the order of its elements to be determined externally. By * default, the elements will be placed in the order in which they were added to the collection. * Additionally, the elements can be sorted in various ways depending on a specified sorting * algorithm and comparison function. * * @author Derk Norton * @param <E> The type of element managed by the collection. */ public abstract class SortableCollection<E> extends OpenCollection<E> { static private final XLogger logger = XLoggerFactory.getXLogger(SortableCollection.class); /** * This method shuffles the elements in the collection using a randomizing algorithm. */ public void shuffleElements() { logger.entry();
Sorter<E> sorter = new RandomSorter<>();
craterdog/java-collection-framework
src/main/java/craterdog/collections/abstractions/SortableCollection.java
// Path: src/main/java/craterdog/collections/primitives/MergeSorter.java // public class MergeSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is needed // if (collection != null && collection.getSize() > 1) { // // // make sure the comparator exists // if (comparator == null) comparator = new NaturalComparator<>(); // // // convert the collection to an array // E[] array = collection.toArray(); // // // sort the array // sortArray(array, comparator); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // // } // } // // // private void sortArray(E[] array, Comparator<? super E> comparator) { // // check to see if the array is already sorted // int length = array.length; // if (length < 2) return; // // // split the array into two halves // int leftLength = length / 2; // E[] left = Arrays.copyOfRange(array, 0, leftLength); // E[] right = Arrays.copyOfRange(array, leftLength, length); // // // sort each half separately // sortArray(left, comparator); // sortArray(right, comparator); // // // merge the sorted halves back together // mergeArrays(left, right, array, comparator); // } // // // private void mergeArrays(E[] left, E[] right, E[] result, Comparator<? super E> comparator) { // int leftIndex = 0; // int rightIndex = 0; // int resultIndex = 0; // while (resultIndex < result.length) { // if (leftIndex < left.length && rightIndex < right.length) { // // still have elements in both halves // if (comparator.compare(left[leftIndex], right[rightIndex]) < 0) { // // copy the next left element to the result // result[resultIndex++] = left[leftIndex++]; // } else { // // copy the next right element to the result // result[resultIndex++] = right[rightIndex++]; // } // } else if (leftIndex < left.length) { // // copy the rest of the left half to the result // int leftRemaining = left.length - leftIndex; // System.arraycopy(left, leftIndex, result, resultIndex, leftRemaining); // leftIndex += leftRemaining; // resultIndex += leftRemaining; // } else { // // copy the rest of the right half to the result // int rightRemaining = right.length - rightIndex; // System.arraycopy(right, rightIndex, result, resultIndex, rightRemaining); // rightIndex += rightRemaining; // resultIndex += rightRemaining; // } // } // } // // } // // Path: src/main/java/craterdog/collections/primitives/RandomSorter.java // public class RandomSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is really required // if (collection != null && collection.getSize() > 1) { // if (collection instanceof List) { // // randomize it in place // @SuppressWarnings("unchecked") // List<E> indexedCollection = (List<E>) collection; // int size = collection.getSize(); // randomizeCollection(indexedCollection, size); // } else { // // convert the collection to an array // E[] array = collection.toArray(); // // // randomize the array // randomizeArray(array); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // } // } // } // // private void randomizeCollection(List<E> indexedCollection, int size) { // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index) + 1; // use ordinal based indexing // E swap = indexedCollection.getElement(index); // swap = indexedCollection.replaceElement(swap, randomIndex); // indexedCollection.replaceElement(swap, index); // } // } // // private void randomizeArray(E[] array) { // int size = array.length; // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index); // use zero based indexing // E swap = array[index - 1]; // array[index - 1] = array[randomIndex]; // array[randomIndex] = swap; // } // } // // }
import craterdog.collections.primitives.MergeSorter; import craterdog.collections.primitives.RandomSorter; import craterdog.core.Manipulator; import craterdog.utils.NaturalComparator; import java.util.Comparator; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory;
/************************************************************************ * Copyright (c) Crater Dog Technologies(TM). All Rights Reserved. * ************************************************************************ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * * * This code is free software; you can redistribute it and/or modify it * * under the terms of The MIT License (MIT), as published by the Open * * Source Initiative. (See http://opensource.org/licenses/MIT) * ************************************************************************/ package craterdog.collections.abstractions; /** * This abstract class defines the invariant methods that all sortable collections must inherit. * A sortable collection allows the order of its elements to be determined externally. By * default, the elements will be placed in the order in which they were added to the collection. * Additionally, the elements can be sorted in various ways depending on a specified sorting * algorithm and comparison function. * * @author Derk Norton * @param <E> The type of element managed by the collection. */ public abstract class SortableCollection<E> extends OpenCollection<E> { static private final XLogger logger = XLoggerFactory.getXLogger(SortableCollection.class); /** * This method shuffles the elements in the collection using a randomizing algorithm. */ public void shuffleElements() { logger.entry(); Sorter<E> sorter = new RandomSorter<>(); sorter.sortCollection(this); logger.exit(); } /** * This method sorts the elements in the collection using the default (merge) sorting * algorithm and the elements' <code>compareTo</code> method. It provides an easy way * to sort a collection using its natural ordering. */ public void sortElements() { logger.entry();
// Path: src/main/java/craterdog/collections/primitives/MergeSorter.java // public class MergeSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is needed // if (collection != null && collection.getSize() > 1) { // // // make sure the comparator exists // if (comparator == null) comparator = new NaturalComparator<>(); // // // convert the collection to an array // E[] array = collection.toArray(); // // // sort the array // sortArray(array, comparator); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // // } // } // // // private void sortArray(E[] array, Comparator<? super E> comparator) { // // check to see if the array is already sorted // int length = array.length; // if (length < 2) return; // // // split the array into two halves // int leftLength = length / 2; // E[] left = Arrays.copyOfRange(array, 0, leftLength); // E[] right = Arrays.copyOfRange(array, leftLength, length); // // // sort each half separately // sortArray(left, comparator); // sortArray(right, comparator); // // // merge the sorted halves back together // mergeArrays(left, right, array, comparator); // } // // // private void mergeArrays(E[] left, E[] right, E[] result, Comparator<? super E> comparator) { // int leftIndex = 0; // int rightIndex = 0; // int resultIndex = 0; // while (resultIndex < result.length) { // if (leftIndex < left.length && rightIndex < right.length) { // // still have elements in both halves // if (comparator.compare(left[leftIndex], right[rightIndex]) < 0) { // // copy the next left element to the result // result[resultIndex++] = left[leftIndex++]; // } else { // // copy the next right element to the result // result[resultIndex++] = right[rightIndex++]; // } // } else if (leftIndex < left.length) { // // copy the rest of the left half to the result // int leftRemaining = left.length - leftIndex; // System.arraycopy(left, leftIndex, result, resultIndex, leftRemaining); // leftIndex += leftRemaining; // resultIndex += leftRemaining; // } else { // // copy the rest of the right half to the result // int rightRemaining = right.length - rightIndex; // System.arraycopy(right, rightIndex, result, resultIndex, rightRemaining); // rightIndex += rightRemaining; // resultIndex += rightRemaining; // } // } // } // // } // // Path: src/main/java/craterdog/collections/primitives/RandomSorter.java // public class RandomSorter<E> extends Sorter<E> { // // @Override // public void sortCollection(SortableCollection<E> collection, Comparator<? super E> comparator) { // // see if any sorting is really required // if (collection != null && collection.getSize() > 1) { // if (collection instanceof List) { // // randomize it in place // @SuppressWarnings("unchecked") // List<E> indexedCollection = (List<E>) collection; // int size = collection.getSize(); // randomizeCollection(indexedCollection, size); // } else { // // convert the collection to an array // E[] array = collection.toArray(); // // // randomize the array // randomizeArray(array); // // // convert it back to a collection // collection.removeAll(); // collection.addElements(array); // } // } // } // // private void randomizeCollection(List<E> indexedCollection, int size) { // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index) + 1; // use ordinal based indexing // E swap = indexedCollection.getElement(index); // swap = indexedCollection.replaceElement(swap, randomIndex); // indexedCollection.replaceElement(swap, index); // } // } // // private void randomizeArray(E[] array) { // int size = array.length; // for (int index = size; index > 1; index--) { // int randomIndex = RandomUtils.pickRandomIndex(index); // use zero based indexing // E swap = array[index - 1]; // array[index - 1] = array[randomIndex]; // array[randomIndex] = swap; // } // } // // } // Path: src/main/java/craterdog/collections/abstractions/SortableCollection.java import craterdog.collections.primitives.MergeSorter; import craterdog.collections.primitives.RandomSorter; import craterdog.core.Manipulator; import craterdog.utils.NaturalComparator; import java.util.Comparator; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /************************************************************************ * Copyright (c) Crater Dog Technologies(TM). All Rights Reserved. * ************************************************************************ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * * * This code is free software; you can redistribute it and/or modify it * * under the terms of The MIT License (MIT), as published by the Open * * Source Initiative. (See http://opensource.org/licenses/MIT) * ************************************************************************/ package craterdog.collections.abstractions; /** * This abstract class defines the invariant methods that all sortable collections must inherit. * A sortable collection allows the order of its elements to be determined externally. By * default, the elements will be placed in the order in which they were added to the collection. * Additionally, the elements can be sorted in various ways depending on a specified sorting * algorithm and comparison function. * * @author Derk Norton * @param <E> The type of element managed by the collection. */ public abstract class SortableCollection<E> extends OpenCollection<E> { static private final XLogger logger = XLoggerFactory.getXLogger(SortableCollection.class); /** * This method shuffles the elements in the collection using a randomizing algorithm. */ public void shuffleElements() { logger.entry(); Sorter<E> sorter = new RandomSorter<>(); sorter.sortCollection(this); logger.exit(); } /** * This method sorts the elements in the collection using the default (merge) sorting * algorithm and the elements' <code>compareTo</code> method. It provides an easy way * to sort a collection using its natural ordering. */ public void sortElements() { logger.entry();
Sorter<E> sorter = new MergeSorter<>();
oscii-lab/lex
src/test/java/org/oscii/panlex/PanLexJSONParserTest.java
// Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // }
import com.google.gson.Gson; import org.junit.Test; import org.oscii.lex.Meaning; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package org.oscii.panlex; public class PanLexJSONParserTest { /* * Create an object like obj from JSON object s. */ private <T> T create(T obj, String s) { return (T) new Gson().fromJson(s, obj.getClass()); } /* * Find and return the first element of s matching condition. */ private <T> T getAndCheck(Collection<T> s, Predicate<? super T> condition) { Optional<T> maybe = s.stream().filter(condition).findFirst(); assertTrue(maybe.isPresent()); return maybe.get(); } @Test public void testForEachMeaning() throws Exception { Set<String> languages = new HashSet<>(Arrays.asList(new String[]{"spa", "eng"})); PanLexJSONParser parser = new PanLexJSONParser(PanLexDir.empty()); Predicate<Models.Lv> storeLanguage = parser.storeLanguage(languages); Predicate<Models.Ex> storeExpression = parser.storeEx(null); // Initialize parser assertTrue(parser.storeSource(create(new Models.Source(), "{\"ap\": 10, \"li\": \"gp\"}"))); assertTrue(storeLanguage.test(create(new Models.Lv(), "{\"lv\": 20, \"lc\": \"spa\"}"))); assertTrue(storeLanguage.test(create(new Models.Lv(), "{\"lv\": 30, \"lc\": \"eng\"}"))); parser.addLanguages(languages); // Load a translation: dog (noun) <-> perro is defined as "a creature" assertTrue(storeExpression.test(create(new Models.Ex(), "{\"ex\": 40, \"lv\": 20, \"tt\": \"perro\"}"))); assertTrue(storeExpression.test(create(new Models.Ex(), "{\"ex\": 50, \"lv\": 30, \"tt\": \"dog\"}"))); assertTrue(parser.storeMn(create(new Models.Mn(), "{\"mn\": 60, \"ap\": 10}"))); assertTrue(parser.storeDn(create(new Models.Dn(), "{\"dn\": 70, \"mn\": 60, \"ex\": 40}"))); assertTrue(parser.storeDn(create(new Models.Dn(), "{\"dn\": 80, \"mn\": 60, \"ex\": 50}"))); assertTrue(parser.storeDf(create(new Models.Df(), "{\"df\": 90, \"mn\": 60, \"lv\": 30, \"tt\": \"a creature\"}"))); assertTrue(parser.storeWc(create(new Models.Wc(), "{\"wc\": 100, \"dn\": 80, \"ex\": 1000}"))); assertTrue(parser.storeWcex(create(new Models.Wcex(), "{\"ex\": 1000, \"tt\": \"noun\"}"))); parser.read(null); // Verify meanings
// Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // Path: src/test/java/org/oscii/panlex/PanLexJSONParserTest.java import com.google.gson.Gson; import org.junit.Test; import org.oscii.lex.Meaning; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package org.oscii.panlex; public class PanLexJSONParserTest { /* * Create an object like obj from JSON object s. */ private <T> T create(T obj, String s) { return (T) new Gson().fromJson(s, obj.getClass()); } /* * Find and return the first element of s matching condition. */ private <T> T getAndCheck(Collection<T> s, Predicate<? super T> condition) { Optional<T> maybe = s.stream().filter(condition).findFirst(); assertTrue(maybe.isPresent()); return maybe.get(); } @Test public void testForEachMeaning() throws Exception { Set<String> languages = new HashSet<>(Arrays.asList(new String[]{"spa", "eng"})); PanLexJSONParser parser = new PanLexJSONParser(PanLexDir.empty()); Predicate<Models.Lv> storeLanguage = parser.storeLanguage(languages); Predicate<Models.Ex> storeExpression = parser.storeEx(null); // Initialize parser assertTrue(parser.storeSource(create(new Models.Source(), "{\"ap\": 10, \"li\": \"gp\"}"))); assertTrue(storeLanguage.test(create(new Models.Lv(), "{\"lv\": 20, \"lc\": \"spa\"}"))); assertTrue(storeLanguage.test(create(new Models.Lv(), "{\"lv\": 30, \"lc\": \"eng\"}"))); parser.addLanguages(languages); // Load a translation: dog (noun) <-> perro is defined as "a creature" assertTrue(storeExpression.test(create(new Models.Ex(), "{\"ex\": 40, \"lv\": 20, \"tt\": \"perro\"}"))); assertTrue(storeExpression.test(create(new Models.Ex(), "{\"ex\": 50, \"lv\": 30, \"tt\": \"dog\"}"))); assertTrue(parser.storeMn(create(new Models.Mn(), "{\"mn\": 60, \"ap\": 10}"))); assertTrue(parser.storeDn(create(new Models.Dn(), "{\"dn\": 70, \"mn\": 60, \"ex\": 40}"))); assertTrue(parser.storeDn(create(new Models.Dn(), "{\"dn\": 80, \"mn\": 60, \"ex\": 50}"))); assertTrue(parser.storeDf(create(new Models.Df(), "{\"df\": 90, \"mn\": 60, \"lv\": 30, \"tt\": \"a creature\"}"))); assertTrue(parser.storeWc(create(new Models.Wc(), "{\"wc\": 100, \"dn\": 80, \"ex\": 1000}"))); assertTrue(parser.storeWcex(create(new Models.Wcex(), "{\"ex\": 1000, \"tt\": \"noun\"}"))); parser.read(null); // Verify meanings
List<Meaning> meanings = new ArrayList<>();
oscii-lab/lex
src/main/java/org/oscii/neural/EmbeddingContainer.java
// Path: src/main/java/org/oscii/math/VectorMath.java // public final class VectorMath { // // private VectorMath() { // } // // /** // * Cosine similarity. Undefined for zero vectors. // * // * @param v1 // * @param v2 // * @return // */ // public static double cosineSimilarity(float[] v1, float[] v2) { // if (v1.length != v2.length) throw new IllegalArgumentException(); // double v1Dotv2 = 0.0; // double v1SS = 0.0; // double v2SS = 0.0; // for (int i = 0; i < v1.length; i++) { // v1Dotv2 += v1[i] * v2[i]; // v1SS += v1[i] * v1[i]; // v2SS += v2[i] * v2[i]; // } // if (v1SS == 0.0f || v2SS == 0.0f) // throw new IllegalArgumentException("Cosine similarity undefined for zero vectors"); // return v1Dotv2 / (Math.sqrt(v1SS) * Math.sqrt(v2SS)); // } // // public static double cosineSimilarity(Vector v1, Vector v2) { // if (v1.size() != v2.size()) throw new IllegalArgumentException(); // double v1v2 = v1.dot(v2); // double v1Norm = v1.norm(Vector.Norm.Two); // double v2Norm = v2.norm(Vector.Norm.Two); // if (v1Norm == 0.0 || v2Norm == 0.0) // throw new IllegalArgumentException("Cosine similarity undefined for zero vectors"); // return v1v2 / (v1Norm * v2Norm); // } // // /** // * @param dest // * @param v1 // */ // public static void addInPlace(float[] dest, float[] v1) { // if (dest.length != v1.length) throw new IllegalArgumentException(); // for (int i = 0; i < dest.length; ++i) dest[i] += v1[i]; // } // // /** // * @param v1 // * @param scalar // */ // public static void multiplyInPlace(float[] v1, float scalar) { // if (scalar == 0.0f) throw new IllegalArgumentException(); // for (int i = 0; i < v1.length; ++i) v1[i] *= scalar; // } // // }
import com.eatthepath.jvptree.VPTree; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Vector; import org.oscii.math.VectorMath; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.LineNumberReader; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static java.util.stream.Collectors.toList;
} if (n == 0) { return new DenseVector(dimension()); } avgVec.scale(1.0f / n); return avgVec; } /** * Return k words nearest to a word. The result will include the word. */ public List<String> neighbors(String word, int k) { return neighbors(embeddings[word2Index.get(word)], k); } /** * Return k words nearest to an embedding vector. */ public List<String> neighbors(Vector embedding, int k) { if (neighborIndex == null) { neighborIndex = new VPTree<Vector>(EmbeddingContainer::angularDistance, Arrays.asList(embeddings)); } return neighborIndex.getNearestNeighbors(embedding, k) .stream().map(e -> vocab[embedding2Index.get(e)]).collect(toList()); } /** * Distance metric based on angle between vectors. */ static double angularDistance(Vector a, Vector b) {
// Path: src/main/java/org/oscii/math/VectorMath.java // public final class VectorMath { // // private VectorMath() { // } // // /** // * Cosine similarity. Undefined for zero vectors. // * // * @param v1 // * @param v2 // * @return // */ // public static double cosineSimilarity(float[] v1, float[] v2) { // if (v1.length != v2.length) throw new IllegalArgumentException(); // double v1Dotv2 = 0.0; // double v1SS = 0.0; // double v2SS = 0.0; // for (int i = 0; i < v1.length; i++) { // v1Dotv2 += v1[i] * v2[i]; // v1SS += v1[i] * v1[i]; // v2SS += v2[i] * v2[i]; // } // if (v1SS == 0.0f || v2SS == 0.0f) // throw new IllegalArgumentException("Cosine similarity undefined for zero vectors"); // return v1Dotv2 / (Math.sqrt(v1SS) * Math.sqrt(v2SS)); // } // // public static double cosineSimilarity(Vector v1, Vector v2) { // if (v1.size() != v2.size()) throw new IllegalArgumentException(); // double v1v2 = v1.dot(v2); // double v1Norm = v1.norm(Vector.Norm.Two); // double v2Norm = v2.norm(Vector.Norm.Two); // if (v1Norm == 0.0 || v2Norm == 0.0) // throw new IllegalArgumentException("Cosine similarity undefined for zero vectors"); // return v1v2 / (v1Norm * v2Norm); // } // // /** // * @param dest // * @param v1 // */ // public static void addInPlace(float[] dest, float[] v1) { // if (dest.length != v1.length) throw new IllegalArgumentException(); // for (int i = 0; i < dest.length; ++i) dest[i] += v1[i]; // } // // /** // * @param v1 // * @param scalar // */ // public static void multiplyInPlace(float[] v1, float scalar) { // if (scalar == 0.0f) throw new IllegalArgumentException(); // for (int i = 0; i < v1.length; ++i) v1[i] *= scalar; // } // // } // Path: src/main/java/org/oscii/neural/EmbeddingContainer.java import com.eatthepath.jvptree.VPTree; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Vector; import org.oscii.math.VectorMath; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.LineNumberReader; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static java.util.stream.Collectors.toList; } if (n == 0) { return new DenseVector(dimension()); } avgVec.scale(1.0f / n); return avgVec; } /** * Return k words nearest to a word. The result will include the word. */ public List<String> neighbors(String word, int k) { return neighbors(embeddings[word2Index.get(word)], k); } /** * Return k words nearest to an embedding vector. */ public List<String> neighbors(Vector embedding, int k) { if (neighborIndex == null) { neighborIndex = new VPTree<Vector>(EmbeddingContainer::angularDistance, Arrays.asList(embeddings)); } return neighborIndex.getNearestNeighbors(embedding, k) .stream().map(e -> vocab[embedding2Index.get(e)]).collect(toList()); } /** * Distance metric based on angle between vectors. */ static double angularDistance(Vector a, Vector b) {
return Math.acos(VectorMath.cosineSimilarity(a, b)) / Math.PI;
oscii-lab/lex
src/main/java/org/oscii/panlex/PanLexJSONParser.java
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet;
} /* * Parses a JSON file of T records and calls process on each. */ private <T> void parse(InputStream in, T record, Predicate<T> process) { int accepted = 0; Class type = record.getClass(); String name = type.getSimpleName(); Gson gson = new Gson(); log.info(String.format("Parsing %s records", name)); try { JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); reader.beginArray(); while (reader.hasNext()) { record = gson.fromJson(reader, type); if (process.test(record)) { accepted++; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } log.info(String.format("Parsed %d %s records", accepted, name)); } /* * For all words with a shared meaning, process Meanings by language. */
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // } // Path: src/main/java/org/oscii/panlex/PanLexJSONParser.java import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet; } /* * Parses a JSON file of T records and calls process on each. */ private <T> void parse(InputStream in, T record, Predicate<T> process) { int accepted = 0; Class type = record.getClass(); String name = type.getSimpleName(); Gson gson = new Gson(); log.info(String.format("Parsing %s records", name)); try { JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); reader.beginArray(); while (reader.hasNext()) { record = gson.fromJson(reader, type); if (process.test(record)) { accepted++; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } log.info(String.format("Parsed %d %s records", accepted, name)); } /* * For all words with a shared meaning, process Meanings by language. */
public void forEachMeaning(Consumer<Meaning> process) {
oscii-lab/lex
src/main/java/org/oscii/panlex/PanLexJSONParser.java
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet;
record = gson.fromJson(reader, type); if (process.test(record)) { accepted++; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } log.info(String.format("Parsed %d %s records", accepted, name)); } /* * For all words with a shared meaning, process Meanings by language. */ public void forEachMeaning(Consumer<Meaning> process) { denotations.values().stream().collect(groupingBy(dn -> dn.mn)).values() .forEach(denotationsForMeaning -> { Map<String, List<Meaning>> byLanguage = denotationsForMeaning.stream().map(this::createMeaning) .collect(groupingBy(m -> m.expression.languageTag)); processMeanings(process, byLanguage); }); } /* * Create a meaning for a denotation containing in-language definitions. */ private Meaning createMeaning(Models.Dn dn) { Models.Ex ex = expressions.get(dn.ex); String languageTag = languageTags.get(ex.lv);
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // } // Path: src/main/java/org/oscii/panlex/PanLexJSONParser.java import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet; record = gson.fromJson(reader, type); if (process.test(record)) { accepted++; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } log.info(String.format("Parsed %d %s records", accepted, name)); } /* * For all words with a shared meaning, process Meanings by language. */ public void forEachMeaning(Consumer<Meaning> process) { denotations.values().stream().collect(groupingBy(dn -> dn.mn)).values() .forEach(denotationsForMeaning -> { Map<String, List<Meaning>> byLanguage = denotationsForMeaning.stream().map(this::createMeaning) .collect(groupingBy(m -> m.expression.languageTag)); processMeanings(process, byLanguage); }); } /* * Create a meaning for a denotation containing in-language definitions. */ private Meaning createMeaning(Models.Dn dn) { Models.Ex ex = expressions.get(dn.ex); String languageTag = languageTags.get(ex.lv);
Expression expression = new Expression(ex.tt, ex.td, languageTag);
oscii-lab/lex
src/main/java/org/oscii/panlex/PanLexJSONParser.java
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet;
log.info(String.format("Parsed %d %s records", accepted, name)); } /* * For all words with a shared meaning, process Meanings by language. */ public void forEachMeaning(Consumer<Meaning> process) { denotations.values().stream().collect(groupingBy(dn -> dn.mn)).values() .forEach(denotationsForMeaning -> { Map<String, List<Meaning>> byLanguage = denotationsForMeaning.stream().map(this::createMeaning) .collect(groupingBy(m -> m.expression.languageTag)); processMeanings(process, byLanguage); }); } /* * Create a meaning for a denotation containing in-language definitions. */ private Meaning createMeaning(Models.Dn dn) { Models.Ex ex = expressions.get(dn.ex); String languageTag = languageTags.get(ex.lv); Expression expression = new Expression(ex.tt, ex.td, languageTag); Meaning meaning = new Meaning(expression); for (Models.Wc wc : wordClassByDn.getOrDefault(dn.dn, Collections.emptyList())) { meaning.pos.add(wordClassNames.get(wc.ex)); } for (Models.Df df : definitionByMeaning.getOrDefault(dn.mn, Collections.emptyList())) { // TODO(denero) Should definitions be restricted by source language? They are now if (df.lv == ex.lv) { String dataSource = sources.get(meanings.get(df.mn).ap).ti;
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // } // Path: src/main/java/org/oscii/panlex/PanLexJSONParser.java import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet; log.info(String.format("Parsed %d %s records", accepted, name)); } /* * For all words with a shared meaning, process Meanings by language. */ public void forEachMeaning(Consumer<Meaning> process) { denotations.values().stream().collect(groupingBy(dn -> dn.mn)).values() .forEach(denotationsForMeaning -> { Map<String, List<Meaning>> byLanguage = denotationsForMeaning.stream().map(this::createMeaning) .collect(groupingBy(m -> m.expression.languageTag)); processMeanings(process, byLanguage); }); } /* * Create a meaning for a denotation containing in-language definitions. */ private Meaning createMeaning(Models.Dn dn) { Models.Ex ex = expressions.get(dn.ex); String languageTag = languageTags.get(ex.lv); Expression expression = new Expression(ex.tt, ex.td, languageTag); Meaning meaning = new Meaning(expression); for (Models.Wc wc : wordClassByDn.getOrDefault(dn.dn, Collections.emptyList())) { meaning.pos.add(wordClassNames.get(wc.ex)); } for (Models.Df df : definitionByMeaning.getOrDefault(dn.mn, Collections.emptyList())) { // TODO(denero) Should definitions be restricted by source language? They are now if (df.lv == ex.lv) { String dataSource = sources.get(meanings.get(df.mn).ap).ti;
meaning.definitions.add(new Definition(df.tt, meaning.pos, languageTag, dataSource));
oscii-lab/lex
src/main/java/org/oscii/panlex/PanLexJSONParser.java
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // }
import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet;
Models.Ex ex = expressions.get(dn.ex); String languageTag = languageTags.get(ex.lv); Expression expression = new Expression(ex.tt, ex.td, languageTag); Meaning meaning = new Meaning(expression); for (Models.Wc wc : wordClassByDn.getOrDefault(dn.dn, Collections.emptyList())) { meaning.pos.add(wordClassNames.get(wc.ex)); } for (Models.Df df : definitionByMeaning.getOrDefault(dn.mn, Collections.emptyList())) { // TODO(denero) Should definitions be restricted by source language? They are now if (df.lv == ex.lv) { String dataSource = sources.get(meanings.get(df.mn).ap).ti; meaning.definitions.add(new Definition(df.tt, meaning.pos, languageTag, dataSource)); } } return meaning; } /* * Constructs Meaning values for all expressions with the same meaning. */ private void processMeanings( Consumer<Meaning> process, Map<String, List<Meaning>> byLanguage) { for (String sourceLanguage : byLanguage.keySet()) { List<Meaning> meanings = byLanguage.get(sourceLanguage); // Add Translations for (String targetLanguage : byLanguage.keySet()) { if (!sourceLanguage.equals(targetLanguage)) { for (Meaning source : meanings) { for (Meaning target : byLanguage.get(targetLanguage)) {
// Path: src/main/java/org/oscii/lex/Definition.java // public class Definition { // public final String text; // public final List<String> pos; // public final String languageTag; // public final String dataSource; // // public Definition(String text, List<String> pos, String languageTag, String dataSoure) { // this.text = text; // this.pos = pos; // this.languageTag = languageTag; // this.dataSource = dataSoure; // } // // @Override // public String toString() { // return "Definition{" + // "text='" + text + '\'' + // ", pos=" + pos + // ", languageTag='" + languageTag + '\'' + // ", dataSource='" + dataSource + '\'' + // '}'; // } // } // // Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // // Path: src/main/java/org/oscii/lex/Translation.java // public class Translation { // public final Expression translation; // public final List<String> pos; // public double frequency; // // public Translation(Expression expression, List<String> pos) { // this.translation = expression; // this.pos = pos; // this.frequency = 0.0; // } // // @Override // public String toString() { // return "Translation{" + // "translation=" + translation + // ", frequency=" + frequency + // '}'; // } // } // Path: src/main/java/org/oscii/panlex/PanLexJSONParser.java import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import gnu.trove.THashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Definition; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import org.oscii.lex.Translation; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toSet; Models.Ex ex = expressions.get(dn.ex); String languageTag = languageTags.get(ex.lv); Expression expression = new Expression(ex.tt, ex.td, languageTag); Meaning meaning = new Meaning(expression); for (Models.Wc wc : wordClassByDn.getOrDefault(dn.dn, Collections.emptyList())) { meaning.pos.add(wordClassNames.get(wc.ex)); } for (Models.Df df : definitionByMeaning.getOrDefault(dn.mn, Collections.emptyList())) { // TODO(denero) Should definitions be restricted by source language? They are now if (df.lv == ex.lv) { String dataSource = sources.get(meanings.get(df.mn).ap).ti; meaning.definitions.add(new Definition(df.tt, meaning.pos, languageTag, dataSource)); } } return meaning; } /* * Constructs Meaning values for all expressions with the same meaning. */ private void processMeanings( Consumer<Meaning> process, Map<String, List<Meaning>> byLanguage) { for (String sourceLanguage : byLanguage.keySet()) { List<Meaning> meanings = byLanguage.get(sourceLanguage); // Add Translations for (String targetLanguage : byLanguage.keySet()) { if (!sourceLanguage.equals(targetLanguage)) { for (Meaning source : meanings) { for (Meaning target : byLanguage.get(targetLanguage)) {
source.translations.add(new Translation(target.expression, target.pos));
oscii-lab/lex
src/main/java/org/oscii/concordance/IndexedAlignedCorpus.java
// Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // }
import com.codepoetics.protonpack.StreamUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.*;
if (all == null) { all = new ArrayList<>(e.getValue().size()); sentences.put(e.getKey(), all); } all.addAll(e.getValue()); }); } @Override public void tally() { sentences.keySet().stream().forEach(language -> { log.info("Indexing words for " + language); Map<String, List<Location>> indexForLanguage = indexTokens(sentences.get(language)); index.put(language, indexForLanguage); }); } /* * Index tokens of sentences by their type. */ private Map<String, List<Location>> indexTokens(List<AlignedSentence> ss) { return ss.stream() .flatMap(s -> IntStream.range(0, s.tokens.length).mapToObj(j -> new Location(s, j))) .collect(groupingBy(Location::token)); } /* * Return a function that takes words in another language and returns translation frequencies. */ @Override
// Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // Path: src/main/java/org/oscii/concordance/IndexedAlignedCorpus.java import com.codepoetics.protonpack.StreamUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.*; if (all == null) { all = new ArrayList<>(e.getValue().size()); sentences.put(e.getKey(), all); } all.addAll(e.getValue()); }); } @Override public void tally() { sentences.keySet().stream().forEach(language -> { log.info("Indexing words for " + language); Map<String, List<Location>> indexForLanguage = indexTokens(sentences.get(language)); index.put(language, indexForLanguage); }); } /* * Index tokens of sentences by their type. */ private Map<String, List<Location>> indexTokens(List<AlignedSentence> ss) { return ss.stream() .flatMap(s -> IntStream.range(0, s.tokens.length).mapToObj(j -> new Location(s, j))) .collect(groupingBy(Location::token)); } /* * Return a function that takes words in another language and returns translation frequencies. */ @Override
public Function<Expression, Double> translationFrequencies(Expression source) {
oscii-lab/lex
src/main/java/org/oscii/lex/Order.java
// Path: src/main/java/org/oscii/concordance/PhrasalRule.java // public class PhrasalRule { // List<String> sourceWords; // List<String> targetWords; // double score = 0.0; // // public PhrasalRule(String sourcePhrase, String targetPhrase, double score) { // this.sourceWords = splitPhrase(sourcePhrase); // this.targetWords = splitPhrase(targetPhrase); // this.score = score; // } // // public String getSource() { // return String.join(" ", sourceWords); // } // // public String getTarget() { // return String.join(" ", targetWords); // } // // public double getScore() { // return score; // } // // private static List<String> splitPhrase(String phrase) { // if (phrase == null) { // return Collections.emptyList(); // } else { // return Arrays.asList(phrase.split("\\s+")); // } // } // } // // Path: src/main/java/org/oscii/concordance/SentenceExample.java // public class SentenceExample { // // final public AlignedSentence sentence; // final public int sourceStart, sourceLength, targetStart, targetLength; // public double similarity; // Word2Vec similarity to request.context // public int memoryId; // indicates a foreground (<=0) vs. background TM match (-1) // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId) { // this.sentence = sentence; // this.sourceStart = sourceStart; // this.sourceLength = sourceLength; // this.targetStart = targetStart; // this.targetLength = targetLength; // this.similarity = 0.0; // this.memoryId = memoryId; // } // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId, double similarity) { // this(sentence, sourceStart, sourceLength, targetStart, targetLength, memoryId); // this.similarity = similarity; // } // // public static SentenceExample create(AlignedSentence s, int sourceStart, int sourceLength, int memoryId) { // int targetMin = s.aligned.tokens.length; // int targetMax = -1; // for (int i = sourceStart; i < sourceStart + sourceLength; i++) { // int[] a = s.getAlignment()[i]; // for (int j : a) { // if (j < targetMin) targetMin = j; // if (j > targetMax) targetMax = j; // } // } // if (targetMax == -1) { // targetMin = 0; // } // return new SentenceExample(s, sourceStart, sourceLength, targetMin, targetMax - targetMin + 1, memoryId); // } // }
import org.oscii.concordance.PhrasalRule; import org.oscii.concordance.SentenceExample; import java.util.Comparator;
package org.oscii.lex; /** * Ordering on lexical items */ public class Order { public static final Comparator<? super Translation> byFrequency = new Comparator<Translation>() { @Override public int compare(Translation o1, Translation o2) { return Double.compare(o2.frequency, o1.frequency); } }; public static final Comparator<? super Meaning> byMaxTranslationFrequency = new Comparator<Meaning>() { @Override public int compare(Meaning o1, Meaning o2) { if (o2.translations.size() == 0) { return -1; } else if (o1.translations.size() == 0) { return 1; } else { return Double.compare( o2.translations.get(0).frequency, o1.translations.get(0).frequency); } } }; public static final Comparator<? super Expression> byLength = new Comparator<Expression>() { @Override public int compare(Expression o1, Expression o2) { return o1.text.length() - o2.text.length(); } };
// Path: src/main/java/org/oscii/concordance/PhrasalRule.java // public class PhrasalRule { // List<String> sourceWords; // List<String> targetWords; // double score = 0.0; // // public PhrasalRule(String sourcePhrase, String targetPhrase, double score) { // this.sourceWords = splitPhrase(sourcePhrase); // this.targetWords = splitPhrase(targetPhrase); // this.score = score; // } // // public String getSource() { // return String.join(" ", sourceWords); // } // // public String getTarget() { // return String.join(" ", targetWords); // } // // public double getScore() { // return score; // } // // private static List<String> splitPhrase(String phrase) { // if (phrase == null) { // return Collections.emptyList(); // } else { // return Arrays.asList(phrase.split("\\s+")); // } // } // } // // Path: src/main/java/org/oscii/concordance/SentenceExample.java // public class SentenceExample { // // final public AlignedSentence sentence; // final public int sourceStart, sourceLength, targetStart, targetLength; // public double similarity; // Word2Vec similarity to request.context // public int memoryId; // indicates a foreground (<=0) vs. background TM match (-1) // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId) { // this.sentence = sentence; // this.sourceStart = sourceStart; // this.sourceLength = sourceLength; // this.targetStart = targetStart; // this.targetLength = targetLength; // this.similarity = 0.0; // this.memoryId = memoryId; // } // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId, double similarity) { // this(sentence, sourceStart, sourceLength, targetStart, targetLength, memoryId); // this.similarity = similarity; // } // // public static SentenceExample create(AlignedSentence s, int sourceStart, int sourceLength, int memoryId) { // int targetMin = s.aligned.tokens.length; // int targetMax = -1; // for (int i = sourceStart; i < sourceStart + sourceLength; i++) { // int[] a = s.getAlignment()[i]; // for (int j : a) { // if (j < targetMin) targetMin = j; // if (j > targetMax) targetMax = j; // } // } // if (targetMax == -1) { // targetMin = 0; // } // return new SentenceExample(s, sourceStart, sourceLength, targetMin, targetMax - targetMin + 1, memoryId); // } // } // Path: src/main/java/org/oscii/lex/Order.java import org.oscii.concordance.PhrasalRule; import org.oscii.concordance.SentenceExample; import java.util.Comparator; package org.oscii.lex; /** * Ordering on lexical items */ public class Order { public static final Comparator<? super Translation> byFrequency = new Comparator<Translation>() { @Override public int compare(Translation o1, Translation o2) { return Double.compare(o2.frequency, o1.frequency); } }; public static final Comparator<? super Meaning> byMaxTranslationFrequency = new Comparator<Meaning>() { @Override public int compare(Meaning o1, Meaning o2) { if (o2.translations.size() == 0) { return -1; } else if (o1.translations.size() == 0) { return 1; } else { return Double.compare( o2.translations.get(0).frequency, o1.translations.get(0).frequency); } } }; public static final Comparator<? super Expression> byLength = new Comparator<Expression>() { @Override public int compare(Expression o1, Expression o2) { return o1.text.length() - o2.text.length(); } };
public static final Comparator<? super PhrasalRule> byScore = new Comparator<PhrasalRule>() {
oscii-lab/lex
src/main/java/org/oscii/lex/Order.java
// Path: src/main/java/org/oscii/concordance/PhrasalRule.java // public class PhrasalRule { // List<String> sourceWords; // List<String> targetWords; // double score = 0.0; // // public PhrasalRule(String sourcePhrase, String targetPhrase, double score) { // this.sourceWords = splitPhrase(sourcePhrase); // this.targetWords = splitPhrase(targetPhrase); // this.score = score; // } // // public String getSource() { // return String.join(" ", sourceWords); // } // // public String getTarget() { // return String.join(" ", targetWords); // } // // public double getScore() { // return score; // } // // private static List<String> splitPhrase(String phrase) { // if (phrase == null) { // return Collections.emptyList(); // } else { // return Arrays.asList(phrase.split("\\s+")); // } // } // } // // Path: src/main/java/org/oscii/concordance/SentenceExample.java // public class SentenceExample { // // final public AlignedSentence sentence; // final public int sourceStart, sourceLength, targetStart, targetLength; // public double similarity; // Word2Vec similarity to request.context // public int memoryId; // indicates a foreground (<=0) vs. background TM match (-1) // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId) { // this.sentence = sentence; // this.sourceStart = sourceStart; // this.sourceLength = sourceLength; // this.targetStart = targetStart; // this.targetLength = targetLength; // this.similarity = 0.0; // this.memoryId = memoryId; // } // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId, double similarity) { // this(sentence, sourceStart, sourceLength, targetStart, targetLength, memoryId); // this.similarity = similarity; // } // // public static SentenceExample create(AlignedSentence s, int sourceStart, int sourceLength, int memoryId) { // int targetMin = s.aligned.tokens.length; // int targetMax = -1; // for (int i = sourceStart; i < sourceStart + sourceLength; i++) { // int[] a = s.getAlignment()[i]; // for (int j : a) { // if (j < targetMin) targetMin = j; // if (j > targetMax) targetMax = j; // } // } // if (targetMax == -1) { // targetMin = 0; // } // return new SentenceExample(s, sourceStart, sourceLength, targetMin, targetMax - targetMin + 1, memoryId); // } // }
import org.oscii.concordance.PhrasalRule; import org.oscii.concordance.SentenceExample; import java.util.Comparator;
if (o2.translations.size() == 0) { return -1; } else if (o1.translations.size() == 0) { return 1; } else { return Double.compare( o2.translations.get(0).frequency, o1.translations.get(0).frequency); } } }; public static final Comparator<? super Expression> byLength = new Comparator<Expression>() { @Override public int compare(Expression o1, Expression o2) { return o1.text.length() - o2.text.length(); } }; public static final Comparator<? super PhrasalRule> byScore = new Comparator<PhrasalRule>() { @Override public int compare(PhrasalRule x, PhrasalRule y) { if (x != null && y != null) { return Double.compare(y.getScore(), x.getScore()); } else { return 0; } } };
// Path: src/main/java/org/oscii/concordance/PhrasalRule.java // public class PhrasalRule { // List<String> sourceWords; // List<String> targetWords; // double score = 0.0; // // public PhrasalRule(String sourcePhrase, String targetPhrase, double score) { // this.sourceWords = splitPhrase(sourcePhrase); // this.targetWords = splitPhrase(targetPhrase); // this.score = score; // } // // public String getSource() { // return String.join(" ", sourceWords); // } // // public String getTarget() { // return String.join(" ", targetWords); // } // // public double getScore() { // return score; // } // // private static List<String> splitPhrase(String phrase) { // if (phrase == null) { // return Collections.emptyList(); // } else { // return Arrays.asList(phrase.split("\\s+")); // } // } // } // // Path: src/main/java/org/oscii/concordance/SentenceExample.java // public class SentenceExample { // // final public AlignedSentence sentence; // final public int sourceStart, sourceLength, targetStart, targetLength; // public double similarity; // Word2Vec similarity to request.context // public int memoryId; // indicates a foreground (<=0) vs. background TM match (-1) // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId) { // this.sentence = sentence; // this.sourceStart = sourceStart; // this.sourceLength = sourceLength; // this.targetStart = targetStart; // this.targetLength = targetLength; // this.similarity = 0.0; // this.memoryId = memoryId; // } // // public SentenceExample(AlignedSentence sentence, int sourceStart, int sourceLength, int targetStart, int targetLength, int memoryId, double similarity) { // this(sentence, sourceStart, sourceLength, targetStart, targetLength, memoryId); // this.similarity = similarity; // } // // public static SentenceExample create(AlignedSentence s, int sourceStart, int sourceLength, int memoryId) { // int targetMin = s.aligned.tokens.length; // int targetMax = -1; // for (int i = sourceStart; i < sourceStart + sourceLength; i++) { // int[] a = s.getAlignment()[i]; // for (int j : a) { // if (j < targetMin) targetMin = j; // if (j > targetMax) targetMax = j; // } // } // if (targetMax == -1) { // targetMin = 0; // } // return new SentenceExample(s, sourceStart, sourceLength, targetMin, targetMax - targetMin + 1, memoryId); // } // } // Path: src/main/java/org/oscii/lex/Order.java import org.oscii.concordance.PhrasalRule; import org.oscii.concordance.SentenceExample; import java.util.Comparator; if (o2.translations.size() == 0) { return -1; } else if (o1.translations.size() == 0) { return 1; } else { return Double.compare( o2.translations.get(0).frequency, o1.translations.get(0).frequency); } } }; public static final Comparator<? super Expression> byLength = new Comparator<Expression>() { @Override public int compare(Expression o1, Expression o2) { return o1.text.length() - o2.text.length(); } }; public static final Comparator<? super PhrasalRule> byScore = new Comparator<PhrasalRule>() { @Override public int compare(PhrasalRule x, PhrasalRule y) { if (x != null && y != null) { return Double.compare(y.getScore(), x.getScore()); } else { return 0; } } };
public static final Comparator<? super SentenceExample> bySimilarity =
oscii-lab/lex
src/main/java/org/oscii/concordance/AlignedCorpus.java
// Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // }
import gnu.trove.THashMap; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import static java.util.stream.Collectors.toMap;
package org.oscii.concordance; /** * Interface to access corpus statistics and examples */ public abstract class AlignedCorpus { static ParallelFiles paths(String path, String sourceLanguage, String targetLanguage) { Function<String, Path> p = ext -> Paths.get(String.format("%s.%s-%s.%s", path, sourceLanguage, targetLanguage, ext)); return new ParallelFiles(p.apply(sourceLanguage), p.apply(targetLanguage), p.apply("align")); } public boolean exists(String path, String sourceLanguage, String targetLanguage) { return paths(path, sourceLanguage, targetLanguage).stream().allMatch(Files::exists); } /* * Read parallel files. */ public abstract void read(String path, String sourceLanguage, String targetLanguage, int max) throws IOException; /* * Return a function that takes phrases in another language and returns translation frequencies. */
// Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // Path: src/main/java/org/oscii/concordance/AlignedCorpus.java import gnu.trove.THashMap; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import static java.util.stream.Collectors.toMap; package org.oscii.concordance; /** * Interface to access corpus statistics and examples */ public abstract class AlignedCorpus { static ParallelFiles paths(String path, String sourceLanguage, String targetLanguage) { Function<String, Path> p = ext -> Paths.get(String.format("%s.%s-%s.%s", path, sourceLanguage, targetLanguage, ext)); return new ParallelFiles(p.apply(sourceLanguage), p.apply(targetLanguage), p.apply("align")); } public boolean exists(String path, String sourceLanguage, String targetLanguage) { return paths(path, sourceLanguage, targetLanguage).stream().allMatch(Files::exists); } /* * Read parallel files. */ public abstract void read(String path, String sourceLanguage, String targetLanguage, int max) throws IOException; /* * Return a function that takes phrases in another language and returns translation frequencies. */
public abstract Function<Expression, Double> translationFrequencies(Expression source);
oscii-lab/lex
src/main/java/org/oscii/concordance/AlignedCorpus.java
// Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // }
import gnu.trove.THashMap; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import static java.util.stream.Collectors.toMap;
package org.oscii.concordance; /** * Interface to access corpus statistics and examples */ public abstract class AlignedCorpus { static ParallelFiles paths(String path, String sourceLanguage, String targetLanguage) { Function<String, Path> p = ext -> Paths.get(String.format("%s.%s-%s.%s", path, sourceLanguage, targetLanguage, ext)); return new ParallelFiles(p.apply(sourceLanguage), p.apply(targetLanguage), p.apply("align")); } public boolean exists(String path, String sourceLanguage, String targetLanguage) { return paths(path, sourceLanguage, targetLanguage).stream().allMatch(Files::exists); } /* * Read parallel files. */ public abstract void read(String path, String sourceLanguage, String targetLanguage, int max) throws IOException; /* * Return a function that takes phrases in another language and returns translation frequencies. */ public abstract Function<Expression, Double> translationFrequencies(Expression source); /* * Score a meaning for the purpose of ranking. */
// Path: src/main/java/org/oscii/lex/Expression.java // public class Expression { // public final String text; // public final String degraded_text; // Lowercased, etc. // public final String language; // ISO-639-1 code (2-letter), e.g., "zh" // // Tag inventory: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // public String languageTag; // RFC5654 language tag, e.g., "zh-cmn-Hans-CN" // public final String source; // // public Expression(String text, String degraded_text, String languageTag) { // this(text, degraded_text, languageTag, ""); // } // // public Expression(String text, String degraded_text, String languageTag, String source) { // this.text = text; // this.degraded_text = degraded_text == null ? Lexicon.degrade(text) : degraded_text; // this.languageTag = languageTag; // // TODO(denero) Split language tag to open language // this.language = languageTag; // this.source = source; // } // // public Expression(String text, String languageTag) { // this(text, Lexicon.degrade(text), languageTag); // } // // @Override // public String toString() { // return "Expression{" + // "text='" + text + '\'' + // "language='" + language + '\'' + // "source='" + source + '\'' + // '}'; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Expression that = (Expression) o; // // if (!language.equals(that.language)) return false; // if (!text.equals(that.text)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = text.hashCode(); // result = 31 * result + language.hashCode(); // return result; // } // } // // Path: src/main/java/org/oscii/lex/Meaning.java // public class Meaning { // public final Expression expression; // public final List<String> pos = new ArrayList<>(); // public final List<Definition> definitions = new ArrayList<>(); // public final List<Translation> translations = new ArrayList<>(); // public final List<Expression> synonyms = new ArrayList<>(); // // @Override // public String toString() { // return "Meaning{" + // "expression=" + expression + // ", definitions=" + definitions + // ", translations=" + translations + // '}'; // } // // public Meaning(Expression expression) { // this.expression = expression; // } // } // Path: src/main/java/org/oscii/concordance/AlignedCorpus.java import gnu.trove.THashMap; import org.oscii.lex.Expression; import org.oscii.lex.Meaning; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; import static java.util.stream.Collectors.toMap; package org.oscii.concordance; /** * Interface to access corpus statistics and examples */ public abstract class AlignedCorpus { static ParallelFiles paths(String path, String sourceLanguage, String targetLanguage) { Function<String, Path> p = ext -> Paths.get(String.format("%s.%s-%s.%s", path, sourceLanguage, targetLanguage, ext)); return new ParallelFiles(p.apply(sourceLanguage), p.apply(targetLanguage), p.apply("align")); } public boolean exists(String path, String sourceLanguage, String targetLanguage) { return paths(path, sourceLanguage, targetLanguage).stream().allMatch(Files::exists); } /* * Read parallel files. */ public abstract void read(String path, String sourceLanguage, String targetLanguage, int max) throws IOException; /* * Return a function that takes phrases in another language and returns translation frequencies. */ public abstract Function<Expression, Double> translationFrequencies(Expression source); /* * Score a meaning for the purpose of ranking. */
public void scoreMeaning(Meaning m) {};
TU-Berlin-SNET/jTR-ABE
src/main/java/trabe/aes/AesEncryption.java
// Path: src/main/java/trabe/AbeDecryptionException.java // public class AbeDecryptionException extends DecryptionException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/trabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // }
import java.io.*; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import trabe.AbeDecryptionException; import trabe.AbeEncryptionException;
static { //Security.addProvider(new BouncyCastleProvider()); } private static byte[] hash(byte[] cpabeData) { try { MessageDigest sha256 = MessageDigest.getInstance(HASHING_ALGORITHM); return Arrays.copyOf(sha256.digest(cpabeData), AES_KEY_LENGTH); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.err.println(HASHING_ALGORITHM + " not provided by runtime environment. Exiting..."); System.exit(1); } return null; } private static byte[] combine(byte[] cpabeData, byte[] lbeKey) { byte[] hashedCpabeSecret = hash(cpabeData); if (lbeKey != null) { if (hashedCpabeSecret.length != lbeKey.length) { throw new RuntimeException("wrong key size for lbeKey, " + hashedCpabeSecret.length + " bytes required"); } for (int i = 0; i < lbeKey.length; i++) { hashedCpabeSecret[i] = (byte) (hashedCpabeSecret[i] ^ lbeKey[i]); } } return hashedCpabeSecret; }
// Path: src/main/java/trabe/AbeDecryptionException.java // public class AbeDecryptionException extends DecryptionException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/trabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // } // Path: src/main/java/trabe/aes/AesEncryption.java import java.io.*; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import trabe.AbeDecryptionException; import trabe.AbeEncryptionException; static { //Security.addProvider(new BouncyCastleProvider()); } private static byte[] hash(byte[] cpabeData) { try { MessageDigest sha256 = MessageDigest.getInstance(HASHING_ALGORITHM); return Arrays.copyOf(sha256.digest(cpabeData), AES_KEY_LENGTH); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.err.println(HASHING_ALGORITHM + " not provided by runtime environment. Exiting..."); System.exit(1); } return null; } private static byte[] combine(byte[] cpabeData, byte[] lbeKey) { byte[] hashedCpabeSecret = hash(cpabeData); if (lbeKey != null) { if (hashedCpabeSecret.length != lbeKey.length) { throw new RuntimeException("wrong key size for lbeKey, " + hashedCpabeSecret.length + " bytes required"); } for (int i = 0; i < lbeKey.length; i++) { hashedCpabeSecret[i] = (byte) (hashedCpabeSecret[i] ^ lbeKey[i]); } } return hashedCpabeSecret; }
public static void encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input, OutputStream output) throws IOException, AbeEncryptionException {
TU-Berlin-SNET/jTR-ABE
src/main/java/trabe/aes/AesEncryption.java
// Path: src/main/java/trabe/AbeDecryptionException.java // public class AbeDecryptionException extends DecryptionException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/trabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // }
import java.io.*; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import trabe.AbeDecryptionException; import trabe.AbeEncryptionException;
byte[] buffer = new byte[BUFFERSIZE]; while ((read = cis.read(buffer)) >= 0) { output.write(buffer, 0, read); } output.close(); cis.close(); } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } } public static byte[] encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, byte[] data) throws IOException, AbeEncryptionException { ByteArrayInputStream bais = new ByteArrayInputStream(data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encrypt(cpabeKey, lbeKey, iv, bais, baos); return baos.toByteArray(); } public static CipherInputStream encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input) throws IOException, AbeEncryptionException { try { SecretKeySpec skeySpec = new SecretKeySpec(combine(cpabeKey, lbeKey), KEY_ALGORITHM); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); CipherInputStream cis = new CipherInputStream(input, cipher); return cis; } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } }
// Path: src/main/java/trabe/AbeDecryptionException.java // public class AbeDecryptionException extends DecryptionException { // // private static final long serialVersionUID = 2848983353356933397L; // // public AbeDecryptionException(String msg) { // super(msg); // } // // public AbeDecryptionException(String msg, Throwable t) { // super(msg, t); // } // } // // Path: src/main/java/trabe/AbeEncryptionException.java // public class AbeEncryptionException extends GeneralSecurityException { // // private static final long serialVersionUID = 1043863535572140323L; // // public AbeEncryptionException(String msg) { // super(msg); // } // // public AbeEncryptionException(String msg, Throwable t) { // super(msg, t); // } // // } // Path: src/main/java/trabe/aes/AesEncryption.java import java.io.*; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import trabe.AbeDecryptionException; import trabe.AbeEncryptionException; byte[] buffer = new byte[BUFFERSIZE]; while ((read = cis.read(buffer)) >= 0) { output.write(buffer, 0, read); } output.close(); cis.close(); } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } } public static byte[] encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, byte[] data) throws IOException, AbeEncryptionException { ByteArrayInputStream bais = new ByteArrayInputStream(data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encrypt(cpabeKey, lbeKey, iv, bais, baos); return baos.toByteArray(); } public static CipherInputStream encrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input) throws IOException, AbeEncryptionException { try { SecretKeySpec skeySpec = new SecretKeySpec(combine(cpabeKey, lbeKey), KEY_ALGORITHM); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); CipherInputStream cis = new CipherInputStream(input, cipher); return cis; } catch (GeneralSecurityException e) { throw new AbeEncryptionException(e.getMessage(), e); } }
public static CipherInputStream decrypt(byte[] cpabeKey, byte[] lbeKey, byte[] iv, InputStream input) throws IOException, AbeDecryptionException {
TU-Berlin-SNET/jTR-ABE
src/main/java/trabe/lw14/policy/LsssMatrixCell.java
// Path: src/main/java/trabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in Underlying input stream // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (readBoolean()) { // return null; // } // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // Element e = publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // boolean instOfCurveElementAndInf = readBoolean(); // if (instOfCurveElementAndInf) { // //e.setToZero(); // according to the code this simply sets the infFlag to 1 // throw new IOException("The point is infinite. This shouldn't happen."); // } // return e; // } // } // // Path: src/main/java/trabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private final AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // /** // * Writes a string to the stream with the locale specified in // * {@link AbeSettings#STRINGS_LOCALE} and prepends the length of the // * serialized bytes. // * @param string String to write // * @throws IOException see {@link #write(byte[])} // */ // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeBoolean(elem == null); // if (elem == null) { // return; // } // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // writeBoolean(elem instanceof CurveElement && elem.isZero()); // if (elem instanceof CurveElement && elem.isZero()) { // throw new IOException("Infinite element detected. They should not happen."); // } // } // // }
import it.unisa.dia.gas.jpbc.Element; import trabe.AbeInputStream; import trabe.AbeOutputStream; import java.io.IOException;
package trabe.lw14.policy; /** * */ public class LsssMatrixCell { public int i; public int j; public int value; public String attribute; public Element hashedElement; private LsssMatrixCell(){} public LsssMatrixCell(int i, int j, int value, String attribute, Element hashedElement) { this.i = i; this.j = j; this.value = value; this.attribute = attribute; this.hashedElement = hashedElement; } public String toString(){ return "["+i+","+j+"] " + attribute + ": " + value + "(" + hashedElement + ")"; }
// Path: src/main/java/trabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in Underlying input stream // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (readBoolean()) { // return null; // } // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // Element e = publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // boolean instOfCurveElementAndInf = readBoolean(); // if (instOfCurveElementAndInf) { // //e.setToZero(); // according to the code this simply sets the infFlag to 1 // throw new IOException("The point is infinite. This shouldn't happen."); // } // return e; // } // } // // Path: src/main/java/trabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private final AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // /** // * Writes a string to the stream with the locale specified in // * {@link AbeSettings#STRINGS_LOCALE} and prepends the length of the // * serialized bytes. // * @param string String to write // * @throws IOException see {@link #write(byte[])} // */ // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeBoolean(elem == null); // if (elem == null) { // return; // } // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // writeBoolean(elem instanceof CurveElement && elem.isZero()); // if (elem instanceof CurveElement && elem.isZero()) { // throw new IOException("Infinite element detected. They should not happen."); // } // } // // } // Path: src/main/java/trabe/lw14/policy/LsssMatrixCell.java import it.unisa.dia.gas.jpbc.Element; import trabe.AbeInputStream; import trabe.AbeOutputStream; import java.io.IOException; package trabe.lw14.policy; /** * */ public class LsssMatrixCell { public int i; public int j; public int value; public String attribute; public Element hashedElement; private LsssMatrixCell(){} public LsssMatrixCell(int i, int j, int value, String attribute, Element hashedElement) { this.i = i; this.j = j; this.value = value; this.attribute = attribute; this.hashedElement = hashedElement; } public String toString(){ return "["+i+","+j+"] " + attribute + ": " + value + "(" + hashedElement + ")"; }
public void writeToStream(AbeOutputStream stream) throws IOException {
TU-Berlin-SNET/jTR-ABE
src/main/java/trabe/lw14/policy/LsssMatrixCell.java
// Path: src/main/java/trabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in Underlying input stream // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (readBoolean()) { // return null; // } // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // Element e = publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // boolean instOfCurveElementAndInf = readBoolean(); // if (instOfCurveElementAndInf) { // //e.setToZero(); // according to the code this simply sets the infFlag to 1 // throw new IOException("The point is infinite. This shouldn't happen."); // } // return e; // } // } // // Path: src/main/java/trabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private final AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // /** // * Writes a string to the stream with the locale specified in // * {@link AbeSettings#STRINGS_LOCALE} and prepends the length of the // * serialized bytes. // * @param string String to write // * @throws IOException see {@link #write(byte[])} // */ // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeBoolean(elem == null); // if (elem == null) { // return; // } // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // writeBoolean(elem instanceof CurveElement && elem.isZero()); // if (elem instanceof CurveElement && elem.isZero()) { // throw new IOException("Infinite element detected. They should not happen."); // } // } // // }
import it.unisa.dia.gas.jpbc.Element; import trabe.AbeInputStream; import trabe.AbeOutputStream; import java.io.IOException;
package trabe.lw14.policy; /** * */ public class LsssMatrixCell { public int i; public int j; public int value; public String attribute; public Element hashedElement; private LsssMatrixCell(){} public LsssMatrixCell(int i, int j, int value, String attribute, Element hashedElement) { this.i = i; this.j = j; this.value = value; this.attribute = attribute; this.hashedElement = hashedElement; } public String toString(){ return "["+i+","+j+"] " + attribute + ": " + value + "(" + hashedElement + ")"; } public void writeToStream(AbeOutputStream stream) throws IOException { stream.writeInt(value); stream.writeString(attribute); stream.writeElement(hashedElement); }
// Path: src/main/java/trabe/AbeInputStream.java // public class AbeInputStream extends DataInputStream { // private final String PUB_MISSING_ERROR = "Can't read Elements without the public master key."; // // private AbePublicKey publicKey; // // public AbeInputStream(InputStream in, AbePublicKey publicKey) { // super(in); // this.publicKey = publicKey; // } // // /** // * If you use this constructor you need to manually set the public key before reading any elements. // * // * @param in Underlying input stream // */ // public AbeInputStream(InputStream in) { // this(in, null); // } // // public void setPublicKey(AbePublicKey pubKey) { // this.publicKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // since internal attribute representation only uses [a-zA-Z0-9:_] // public String readString() throws IOException { // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // return new String(bytes, AbeSettings.STRINGS_LOCALE); // } // // public Element readElement() throws IOException { // if (readBoolean()) { // return null; // } // if (publicKey == null) throw new IOException(PUB_MISSING_ERROR); // int fieldIndex = readInt(); // int length = readInt(); // byte[] bytes = new byte[length]; // readFully(bytes); // Element e = publicKey.getPairing().getFieldAt(fieldIndex).newElementFromBytes(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // boolean instOfCurveElementAndInf = readBoolean(); // if (instOfCurveElementAndInf) { // //e.setToZero(); // according to the code this simply sets the infFlag to 1 // throw new IOException("The point is infinite. This shouldn't happen."); // } // return e; // } // } // // Path: src/main/java/trabe/AbeOutputStream.java // public class AbeOutputStream extends DataOutputStream { // // private final AbePublicKey pubKey; // // public AbeOutputStream(OutputStream out, AbePublicKey pubKey) { // super(out); // this.pubKey = pubKey; // } // // // only used for the curve parameters and attributes, no need for fancy encodings // // /** // * Writes a string to the stream with the locale specified in // * {@link AbeSettings#STRINGS_LOCALE} and prepends the length of the // * serialized bytes. // * @param string String to write // * @throws IOException see {@link #write(byte[])} // */ // public void writeString(String string) throws IOException { // byte[] bytes = string.getBytes(AbeSettings.STRINGS_LOCALE); // writeInt(bytes.length); // write(bytes); // } // // public void writeElement(Element elem) throws IOException { // writeBoolean(elem == null); // if (elem == null) { // return; // } // writeInt(pubKey.getPairing().getFieldIndex(elem.getField())); // byte[] bytes = elem.toBytes(); // writeInt(bytes.length); // write(bytes); // // // this is a workaround because it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement does not serialize the infFlag // writeBoolean(elem instanceof CurveElement && elem.isZero()); // if (elem instanceof CurveElement && elem.isZero()) { // throw new IOException("Infinite element detected. They should not happen."); // } // } // // } // Path: src/main/java/trabe/lw14/policy/LsssMatrixCell.java import it.unisa.dia.gas.jpbc.Element; import trabe.AbeInputStream; import trabe.AbeOutputStream; import java.io.IOException; package trabe.lw14.policy; /** * */ public class LsssMatrixCell { public int i; public int j; public int value; public String attribute; public Element hashedElement; private LsssMatrixCell(){} public LsssMatrixCell(int i, int j, int value, String attribute, Element hashedElement) { this.i = i; this.j = j; this.value = value; this.attribute = attribute; this.hashedElement = hashedElement; } public String toString(){ return "["+i+","+j+"] " + attribute + ": " + value + "(" + hashedElement + ")"; } public void writeToStream(AbeOutputStream stream) throws IOException { stream.writeInt(value); stream.writeString(attribute); stream.writeElement(hashedElement); }
public static LsssMatrixCell readFromStream(AbeInputStream stream) throws IOException {
TU-Berlin-SNET/jTR-ABE
src/main/java/trabe/policy/PolicyParsing.java
// Path: src/main/java/trabe/AbeSettings.java // public class AbeSettings { // public final static boolean DEBUG = false; // public final static String STRINGS_LOCALE = "US-ASCII"; // public final static String ELEMENT_HASHING_ALGORITHM = "SHA-1"; // public final static String curveParams = "type a\n" // + "q 87807107996633125224377819847540498158068831994142082" // + "1102865339926647563088022295707862517942266222142315585" // + "8769582317459277713367317481324925129998224791\n" // + "h 12016012264891146079388821366740534204802954401251311" // + "822919615131047207289359704531102844802183906537786776\n" // + "r 730750818665451621361119245571504901405976559617\n" // + "exp2 159\n" + "exp1 107\n" // + "sign1 1\n" + "sign0 1\n"; // public final static boolean USE_TREE = true; // otherwise LSSS matrix // // public static boolean PREPROCESSING = true; // public static int PREPROCESSING_THRESHOLD = 6; // how many exponentiations with the same basis are needed for pre-processing to make sense // // // currently broken: // public final static boolean USE_THRESHOLD_MATRIX = false; // otherwise LSSS matrix from boolean formula // }
import java.math.BigInteger; import java.util.List; import ch.hsr.geohash.BoundingBox; import ch.hsr.geohash.GeoHash; import trabe.AbeSettings; import trabe.policyparser.*;
if (current instanceof ASTExpression) { handleExpression((ASTExpression) current, retVal); } else if (current instanceof ASTOf) { handleOf((ASTOf) current, retVal); } else if (current instanceof ASTAttribute) { handleAttribute((ASTAttribute) current, retVal); } else if (current instanceof ASTNumericalAttribute) { handleNumericalAttribute((ASTNumericalAttribute) current, retVal); } else if (current instanceof ASTGeoHashAttribute) { ASTGeoHashAttribute currentChild = (ASTGeoHashAttribute) current; handleGeoHashAttributeNeighbourly(currentChild, retVal); } else if (!(current instanceof ASTStart)) { throw new ParseException("Unknown node found in tree."); } return retVal.append(' '); } private static void handleGeoHashAttributeNaive(ASTGeoHashAttribute current, StringBuffer retVal) throws ParseException { if (current.getPrecision() > Util.GEOHASH_MAXBITS || current.getPrecision() <= 0) { throw new ParseException("(GeoHash precision) Only values between 1 and " + Util.GEOHASH_MAXBITS + " are supported."); } GeoHash target; try { target = GeoHash.withBitPrecision(current.getLatitude(), current.getLongitude(), current.getPrecision()); } catch (IllegalArgumentException e) { throw new ParseException(e.getMessage()); } handleGeoHash(target, retVal, current.getName());
// Path: src/main/java/trabe/AbeSettings.java // public class AbeSettings { // public final static boolean DEBUG = false; // public final static String STRINGS_LOCALE = "US-ASCII"; // public final static String ELEMENT_HASHING_ALGORITHM = "SHA-1"; // public final static String curveParams = "type a\n" // + "q 87807107996633125224377819847540498158068831994142082" // + "1102865339926647563088022295707862517942266222142315585" // + "8769582317459277713367317481324925129998224791\n" // + "h 12016012264891146079388821366740534204802954401251311" // + "822919615131047207289359704531102844802183906537786776\n" // + "r 730750818665451621361119245571504901405976559617\n" // + "exp2 159\n" + "exp1 107\n" // + "sign1 1\n" + "sign0 1\n"; // public final static boolean USE_TREE = true; // otherwise LSSS matrix // // public static boolean PREPROCESSING = true; // public static int PREPROCESSING_THRESHOLD = 6; // how many exponentiations with the same basis are needed for pre-processing to make sense // // // currently broken: // public final static boolean USE_THRESHOLD_MATRIX = false; // otherwise LSSS matrix from boolean formula // } // Path: src/main/java/trabe/policy/PolicyParsing.java import java.math.BigInteger; import java.util.List; import ch.hsr.geohash.BoundingBox; import ch.hsr.geohash.GeoHash; import trabe.AbeSettings; import trabe.policyparser.*; if (current instanceof ASTExpression) { handleExpression((ASTExpression) current, retVal); } else if (current instanceof ASTOf) { handleOf((ASTOf) current, retVal); } else if (current instanceof ASTAttribute) { handleAttribute((ASTAttribute) current, retVal); } else if (current instanceof ASTNumericalAttribute) { handleNumericalAttribute((ASTNumericalAttribute) current, retVal); } else if (current instanceof ASTGeoHashAttribute) { ASTGeoHashAttribute currentChild = (ASTGeoHashAttribute) current; handleGeoHashAttributeNeighbourly(currentChild, retVal); } else if (!(current instanceof ASTStart)) { throw new ParseException("Unknown node found in tree."); } return retVal.append(' '); } private static void handleGeoHashAttributeNaive(ASTGeoHashAttribute current, StringBuffer retVal) throws ParseException { if (current.getPrecision() > Util.GEOHASH_MAXBITS || current.getPrecision() <= 0) { throw new ParseException("(GeoHash precision) Only values between 1 and " + Util.GEOHASH_MAXBITS + " are supported."); } GeoHash target; try { target = GeoHash.withBitPrecision(current.getLatitude(), current.getLongitude(), current.getPrecision()); } catch (IllegalArgumentException e) { throw new ParseException(e.getMessage()); } handleGeoHash(target, retVal, current.getName());
if (AbeSettings.DEBUG) {
Terracotta-OSS/offheap-store
src/test/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSourceTest.java
// Path: src/main/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSource.java // public class PhantomReferenceLimitedPageSource implements PageSource { // // private final ReferenceQueue<ByteBuffer> allocatedBuffers = new ReferenceQueue<>(); // private final Map<PhantomReference<ByteBuffer>, Integer> bufferSizes = new ConcurrentHashMap<>(); // // private final AtomicLong max; // // /** // * Create a source that will allocate at most {@code max} bytes. // * // * @param max the maximum total size of all available buffers // */ // public PhantomReferenceLimitedPageSource(long max) { // this.max = new AtomicLong(max); // } // // /** // * Allocates a byte buffer of the given size. // * <p> // * This {@code BufferSource} places no restrictions on the requested size of // * the buffer. // */ // @Override // public Page allocate(int size, boolean thief, boolean victim, OffHeapStorageArea owner) { // while (true) { // processQueue(); // long now = max.get(); // if (now < size) { // return null; // } else if (max.compareAndSet(now, now - size)) { // ByteBuffer buffer; // try { // buffer = ByteBuffer.allocateDirect(size); // } catch (OutOfMemoryError e) { // return null; // } // bufferSizes.put(new PhantomReference<>(buffer, allocatedBuffers), size); // return new Page(buffer, owner); // } // } // } // // /** // * Frees the supplied buffer. // * <p> // * This implementation is a no-op, no validation of the supplied buffer is // * attempted, as freeing of allocated buffers is monitored via phantom // * references. // */ // @Override // public void free(Page buffer) { // //no-op // } // // private void processQueue() { // while (true) { // Reference<?> ref = allocatedBuffers.poll(); // // if (ref == null) { // return; // } else { // Integer size = bufferSizes.remove(ref); // max.addAndGet(size.longValue()); // } // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("PhantomReferenceLimitedBufferSource\n"); // Collection<Integer> buffers = bufferSizes.values(); // sb.append("Bytes Available : ").append(max.get()).append('\n'); // sb.append("Buffers Allocated : (count=").append(buffers.size()).append(") ").append(buffers); // return sb.toString(); // } // } // // Path: src/test/java/org/terracotta/offheapstore/util/RetryAssert.java // public static <T> void assertBy(long time, TimeUnit unit, Callable<T> value, Matcher<? super T> matcher) { // boolean interrupted = Thread.interrupted(); // try { // long end = System.nanoTime() + unit.toNanos(time); // for (long sleep = 10; ; sleep <<= 1L) { // try { // Assert.assertThat(value.call(), matcher); // return; // } catch (Throwable t) { // //ignore - wait for timeout // } // // long remaining = end - System.nanoTime(); // if (remaining <= 0) { // break; // } else { // try { // Thread.sleep(Math.min(sleep, TimeUnit.NANOSECONDS.toMillis(remaining) + 1)); // } catch (InterruptedException e) { // interrupted = true; // } // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // try { // Assert.assertThat(value.call(), matcher); // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new AssertionError(e); // } // }
import org.terracotta.offheapstore.paging.Page; import org.terracotta.offheapstore.paging.PageSource; import org.terracotta.offheapstore.paging.PhantomReferenceLimitedPageSource; import static org.terracotta.offheapstore.util.RetryAssert.assertBy; import static org.hamcrest.core.IsNull.notNullValue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test;
/* * Copyright 2015 Terracotta, Inc., a Software AG company. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.offheapstore.paging; public class PhantomReferenceLimitedPageSourceTest { @Test public void testExhaustion() {
// Path: src/main/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSource.java // public class PhantomReferenceLimitedPageSource implements PageSource { // // private final ReferenceQueue<ByteBuffer> allocatedBuffers = new ReferenceQueue<>(); // private final Map<PhantomReference<ByteBuffer>, Integer> bufferSizes = new ConcurrentHashMap<>(); // // private final AtomicLong max; // // /** // * Create a source that will allocate at most {@code max} bytes. // * // * @param max the maximum total size of all available buffers // */ // public PhantomReferenceLimitedPageSource(long max) { // this.max = new AtomicLong(max); // } // // /** // * Allocates a byte buffer of the given size. // * <p> // * This {@code BufferSource} places no restrictions on the requested size of // * the buffer. // */ // @Override // public Page allocate(int size, boolean thief, boolean victim, OffHeapStorageArea owner) { // while (true) { // processQueue(); // long now = max.get(); // if (now < size) { // return null; // } else if (max.compareAndSet(now, now - size)) { // ByteBuffer buffer; // try { // buffer = ByteBuffer.allocateDirect(size); // } catch (OutOfMemoryError e) { // return null; // } // bufferSizes.put(new PhantomReference<>(buffer, allocatedBuffers), size); // return new Page(buffer, owner); // } // } // } // // /** // * Frees the supplied buffer. // * <p> // * This implementation is a no-op, no validation of the supplied buffer is // * attempted, as freeing of allocated buffers is monitored via phantom // * references. // */ // @Override // public void free(Page buffer) { // //no-op // } // // private void processQueue() { // while (true) { // Reference<?> ref = allocatedBuffers.poll(); // // if (ref == null) { // return; // } else { // Integer size = bufferSizes.remove(ref); // max.addAndGet(size.longValue()); // } // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("PhantomReferenceLimitedBufferSource\n"); // Collection<Integer> buffers = bufferSizes.values(); // sb.append("Bytes Available : ").append(max.get()).append('\n'); // sb.append("Buffers Allocated : (count=").append(buffers.size()).append(") ").append(buffers); // return sb.toString(); // } // } // // Path: src/test/java/org/terracotta/offheapstore/util/RetryAssert.java // public static <T> void assertBy(long time, TimeUnit unit, Callable<T> value, Matcher<? super T> matcher) { // boolean interrupted = Thread.interrupted(); // try { // long end = System.nanoTime() + unit.toNanos(time); // for (long sleep = 10; ; sleep <<= 1L) { // try { // Assert.assertThat(value.call(), matcher); // return; // } catch (Throwable t) { // //ignore - wait for timeout // } // // long remaining = end - System.nanoTime(); // if (remaining <= 0) { // break; // } else { // try { // Thread.sleep(Math.min(sleep, TimeUnit.NANOSECONDS.toMillis(remaining) + 1)); // } catch (InterruptedException e) { // interrupted = true; // } // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // try { // Assert.assertThat(value.call(), matcher); // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new AssertionError(e); // } // } // Path: src/test/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSourceTest.java import org.terracotta.offheapstore.paging.Page; import org.terracotta.offheapstore.paging.PageSource; import org.terracotta.offheapstore.paging.PhantomReferenceLimitedPageSource; import static org.terracotta.offheapstore.util.RetryAssert.assertBy; import static org.hamcrest.core.IsNull.notNullValue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; /* * Copyright 2015 Terracotta, Inc., a Software AG company. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.offheapstore.paging; public class PhantomReferenceLimitedPageSourceTest { @Test public void testExhaustion() {
testExhaustion(new PhantomReferenceLimitedPageSource(64));
Terracotta-OSS/offheap-store
src/test/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSourceTest.java
// Path: src/main/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSource.java // public class PhantomReferenceLimitedPageSource implements PageSource { // // private final ReferenceQueue<ByteBuffer> allocatedBuffers = new ReferenceQueue<>(); // private final Map<PhantomReference<ByteBuffer>, Integer> bufferSizes = new ConcurrentHashMap<>(); // // private final AtomicLong max; // // /** // * Create a source that will allocate at most {@code max} bytes. // * // * @param max the maximum total size of all available buffers // */ // public PhantomReferenceLimitedPageSource(long max) { // this.max = new AtomicLong(max); // } // // /** // * Allocates a byte buffer of the given size. // * <p> // * This {@code BufferSource} places no restrictions on the requested size of // * the buffer. // */ // @Override // public Page allocate(int size, boolean thief, boolean victim, OffHeapStorageArea owner) { // while (true) { // processQueue(); // long now = max.get(); // if (now < size) { // return null; // } else if (max.compareAndSet(now, now - size)) { // ByteBuffer buffer; // try { // buffer = ByteBuffer.allocateDirect(size); // } catch (OutOfMemoryError e) { // return null; // } // bufferSizes.put(new PhantomReference<>(buffer, allocatedBuffers), size); // return new Page(buffer, owner); // } // } // } // // /** // * Frees the supplied buffer. // * <p> // * This implementation is a no-op, no validation of the supplied buffer is // * attempted, as freeing of allocated buffers is monitored via phantom // * references. // */ // @Override // public void free(Page buffer) { // //no-op // } // // private void processQueue() { // while (true) { // Reference<?> ref = allocatedBuffers.poll(); // // if (ref == null) { // return; // } else { // Integer size = bufferSizes.remove(ref); // max.addAndGet(size.longValue()); // } // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("PhantomReferenceLimitedBufferSource\n"); // Collection<Integer> buffers = bufferSizes.values(); // sb.append("Bytes Available : ").append(max.get()).append('\n'); // sb.append("Buffers Allocated : (count=").append(buffers.size()).append(") ").append(buffers); // return sb.toString(); // } // } // // Path: src/test/java/org/terracotta/offheapstore/util/RetryAssert.java // public static <T> void assertBy(long time, TimeUnit unit, Callable<T> value, Matcher<? super T> matcher) { // boolean interrupted = Thread.interrupted(); // try { // long end = System.nanoTime() + unit.toNanos(time); // for (long sleep = 10; ; sleep <<= 1L) { // try { // Assert.assertThat(value.call(), matcher); // return; // } catch (Throwable t) { // //ignore - wait for timeout // } // // long remaining = end - System.nanoTime(); // if (remaining <= 0) { // break; // } else { // try { // Thread.sleep(Math.min(sleep, TimeUnit.NANOSECONDS.toMillis(remaining) + 1)); // } catch (InterruptedException e) { // interrupted = true; // } // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // try { // Assert.assertThat(value.call(), matcher); // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new AssertionError(e); // } // }
import org.terracotta.offheapstore.paging.Page; import org.terracotta.offheapstore.paging.PageSource; import org.terracotta.offheapstore.paging.PhantomReferenceLimitedPageSource; import static org.terracotta.offheapstore.util.RetryAssert.assertBy; import static org.hamcrest.core.IsNull.notNullValue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test;
/* * Copyright 2015 Terracotta, Inc., a Software AG company. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.offheapstore.paging; public class PhantomReferenceLimitedPageSourceTest { @Test public void testExhaustion() { testExhaustion(new PhantomReferenceLimitedPageSource(64)); } private static void testExhaustion(PageSource source) { Page p = source.allocate(64, false, false, null); Assert.assertNotNull(p); Assert.assertNull(source.allocate(1, false, false, null)); Assert.assertNotNull(p); } @Test public void testRecycle() throws InterruptedException { final PageSource source = new PhantomReferenceLimitedPageSource(64); testExhaustion(source);
// Path: src/main/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSource.java // public class PhantomReferenceLimitedPageSource implements PageSource { // // private final ReferenceQueue<ByteBuffer> allocatedBuffers = new ReferenceQueue<>(); // private final Map<PhantomReference<ByteBuffer>, Integer> bufferSizes = new ConcurrentHashMap<>(); // // private final AtomicLong max; // // /** // * Create a source that will allocate at most {@code max} bytes. // * // * @param max the maximum total size of all available buffers // */ // public PhantomReferenceLimitedPageSource(long max) { // this.max = new AtomicLong(max); // } // // /** // * Allocates a byte buffer of the given size. // * <p> // * This {@code BufferSource} places no restrictions on the requested size of // * the buffer. // */ // @Override // public Page allocate(int size, boolean thief, boolean victim, OffHeapStorageArea owner) { // while (true) { // processQueue(); // long now = max.get(); // if (now < size) { // return null; // } else if (max.compareAndSet(now, now - size)) { // ByteBuffer buffer; // try { // buffer = ByteBuffer.allocateDirect(size); // } catch (OutOfMemoryError e) { // return null; // } // bufferSizes.put(new PhantomReference<>(buffer, allocatedBuffers), size); // return new Page(buffer, owner); // } // } // } // // /** // * Frees the supplied buffer. // * <p> // * This implementation is a no-op, no validation of the supplied buffer is // * attempted, as freeing of allocated buffers is monitored via phantom // * references. // */ // @Override // public void free(Page buffer) { // //no-op // } // // private void processQueue() { // while (true) { // Reference<?> ref = allocatedBuffers.poll(); // // if (ref == null) { // return; // } else { // Integer size = bufferSizes.remove(ref); // max.addAndGet(size.longValue()); // } // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder("PhantomReferenceLimitedBufferSource\n"); // Collection<Integer> buffers = bufferSizes.values(); // sb.append("Bytes Available : ").append(max.get()).append('\n'); // sb.append("Buffers Allocated : (count=").append(buffers.size()).append(") ").append(buffers); // return sb.toString(); // } // } // // Path: src/test/java/org/terracotta/offheapstore/util/RetryAssert.java // public static <T> void assertBy(long time, TimeUnit unit, Callable<T> value, Matcher<? super T> matcher) { // boolean interrupted = Thread.interrupted(); // try { // long end = System.nanoTime() + unit.toNanos(time); // for (long sleep = 10; ; sleep <<= 1L) { // try { // Assert.assertThat(value.call(), matcher); // return; // } catch (Throwable t) { // //ignore - wait for timeout // } // // long remaining = end - System.nanoTime(); // if (remaining <= 0) { // break; // } else { // try { // Thread.sleep(Math.min(sleep, TimeUnit.NANOSECONDS.toMillis(remaining) + 1)); // } catch (InterruptedException e) { // interrupted = true; // } // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // try { // Assert.assertThat(value.call(), matcher); // } catch (RuntimeException e) { // throw e; // } catch (Exception e) { // throw new AssertionError(e); // } // } // Path: src/test/java/org/terracotta/offheapstore/paging/PhantomReferenceLimitedPageSourceTest.java import org.terracotta.offheapstore.paging.Page; import org.terracotta.offheapstore.paging.PageSource; import org.terracotta.offheapstore.paging.PhantomReferenceLimitedPageSource; import static org.terracotta.offheapstore.util.RetryAssert.assertBy; import static org.hamcrest.core.IsNull.notNullValue; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; /* * Copyright 2015 Terracotta, Inc., a Software AG company. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.offheapstore.paging; public class PhantomReferenceLimitedPageSourceTest { @Test public void testExhaustion() { testExhaustion(new PhantomReferenceLimitedPageSource(64)); } private static void testExhaustion(PageSource source) { Page p = source.allocate(64, false, false, null); Assert.assertNotNull(p); Assert.assertNull(source.allocate(1, false, false, null)); Assert.assertNotNull(p); } @Test public void testRecycle() throws InterruptedException { final PageSource source = new PhantomReferenceLimitedPageSource(64); testExhaustion(source);
assertBy(30, TimeUnit.SECONDS, () -> {
Terracotta-OSS/offheap-store
src/main/java/org/terracotta/offheapstore/WriteLockedOffHeapClockCache.java
// Path: src/main/java/org/terracotta/offheapstore/storage/StorageEngine.java // public interface StorageEngine<K, V> { // // /** // * Converts the supplied key and value objects into their encoded form. // * // * @param key a key object // * @param value a value object // * @param hash the key hash // * @param metadata the metadata bits // * @return the encoded mapping // */ // Long writeMapping(K key, V value, int hash, int metadata); // // void attachedMapping(long encoding, int hash, int metadata); // // /** // * Called to indicate that the associated encoded value is no longer needed. // * <p> // * This call can be used to free any associated resources tied to the // * lifecycle of the supplied encoded value. // * // * @param encoding encoded value // * @param hash hash of the freed mapping // * @param removal marks removal from a map // */ // void freeMapping(long encoding, int hash, boolean removal); // // /** // * Converts the supplied encoded value into its correct object form. // * // * @param encoding encoded value // * @return a decoded value object // */ // V readValue(long encoding); // // /** // * Called to determine the equality of the given Java object value against the // * given encoded form. // * <p> // * Simple implementations will probably perform a decode on the given encoded // * form in order to do a regular {@code Object.equals(Object)} comparison. // * This method is provided to allow implementations to optimize this // * comparison if possible. // * // * @param value a value object // * @param encoding encoded value // * @return {@code true} if the value and the encoding are equal // */ // boolean equalsValue(Object value, long encoding); // // /** // * Converts the supplied encoded key into its correct object form. // * // * @param encoding encoded key // * @param hashCode hash-code of the decoded key // * @return a decoded key object // */ // K readKey(long encoding, int hashCode); // // /** // * Called to determine the equality of the given object against the // * given encoded form. // * <p> // * Simple implementations will probably perform a decode on the given encoded // * form in order to do a regular {@code Object.equals(Object)} comparison. // * This method is provided to allow implementations to optimize this // * comparison if possible. // * // * @param key a key object // * @param encoding encoded value // * @return {@code true} if the key and the encoding are equal // */ // boolean equalsKey(Object key, long encoding); // // /** // * Called to indicate that all keys and values are now free. // */ // void clear(); // // /** // * Returns a measure of the amount of memory allocated for this storage engine. // * // * @return memory allocated for this engine in bytes // */ // long getAllocatedMemory(); // // /** // * Returns a measure of the amount of memory consumed by this storage engine. // * // * @return memory occupied by this engine in bytes // */ // long getOccupiedMemory(); // // /** // * Returns a measure of the amount of vital memory allocated for this storage engine. // * // * @return vital memory allocated for this engine in bytes // */ // long getVitalMemory(); // // /** // * Returns a measure of the total size of the keys and values stored in this storage engine. // * // * @return size of the stored keys and values in bytes // */ // long getDataSize(); // // /** // * Invalidate any local key/value caches. // * <p> // * This is called to indicate the termination of a map write "phase". Caching // * is permitted within a write operation (i.e. to cache around allocation // * failures during eviction processes). // */ // void invalidateCache(); // // void bind(Owner owner); // // void destroy(); // // boolean shrink(); // // interface Owner extends ReadWriteLock { // // Long getEncodingForHashAndBinary(int hash, ByteBuffer offHeapBinaryKey); // // long getSize(); // // long installMappingForHashAndEncoding(int pojoHash, ByteBuffer offheapBinaryKey, ByteBuffer offheapBinaryValue, int metadata); // // Iterable<Long> encodingSet(); // // boolean updateEncoding(int hashCode, long lastAddress, long compressed, long mask); // // Integer getSlotForHashAndEncoding(int hash, long address, long mask); // // boolean evict(int slot, boolean b); // // boolean isThiefForTableAllocations(); // // } // }
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.terracotta.offheapstore.paging.PageSource; import org.terracotta.offheapstore.storage.StorageEngine;
/* * Copyright 2015 Terracotta, Inc., a Software AG company. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.offheapstore; /** * An exclusive-read/write off-heap clock cache. * <p> * This cache uses one of the unused bits in the off-heap entry's status value to * store the clock data. This clock data is safe to update during read * operations since the cache provides exclusive-read/write characteristics. * Since clock eviction data resides in the hash-map's table, it is correctly * copied across during table resize operations. * <p> * The cache uses a regular {@code ReentrantLock} to provide exclusive read and * write operations. * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Chris Dennis */ public class WriteLockedOffHeapClockCache<K, V> extends AbstractOffHeapClockCache<K, V> { private final Lock lock = new ReentrantLock();
// Path: src/main/java/org/terracotta/offheapstore/storage/StorageEngine.java // public interface StorageEngine<K, V> { // // /** // * Converts the supplied key and value objects into their encoded form. // * // * @param key a key object // * @param value a value object // * @param hash the key hash // * @param metadata the metadata bits // * @return the encoded mapping // */ // Long writeMapping(K key, V value, int hash, int metadata); // // void attachedMapping(long encoding, int hash, int metadata); // // /** // * Called to indicate that the associated encoded value is no longer needed. // * <p> // * This call can be used to free any associated resources tied to the // * lifecycle of the supplied encoded value. // * // * @param encoding encoded value // * @param hash hash of the freed mapping // * @param removal marks removal from a map // */ // void freeMapping(long encoding, int hash, boolean removal); // // /** // * Converts the supplied encoded value into its correct object form. // * // * @param encoding encoded value // * @return a decoded value object // */ // V readValue(long encoding); // // /** // * Called to determine the equality of the given Java object value against the // * given encoded form. // * <p> // * Simple implementations will probably perform a decode on the given encoded // * form in order to do a regular {@code Object.equals(Object)} comparison. // * This method is provided to allow implementations to optimize this // * comparison if possible. // * // * @param value a value object // * @param encoding encoded value // * @return {@code true} if the value and the encoding are equal // */ // boolean equalsValue(Object value, long encoding); // // /** // * Converts the supplied encoded key into its correct object form. // * // * @param encoding encoded key // * @param hashCode hash-code of the decoded key // * @return a decoded key object // */ // K readKey(long encoding, int hashCode); // // /** // * Called to determine the equality of the given object against the // * given encoded form. // * <p> // * Simple implementations will probably perform a decode on the given encoded // * form in order to do a regular {@code Object.equals(Object)} comparison. // * This method is provided to allow implementations to optimize this // * comparison if possible. // * // * @param key a key object // * @param encoding encoded value // * @return {@code true} if the key and the encoding are equal // */ // boolean equalsKey(Object key, long encoding); // // /** // * Called to indicate that all keys and values are now free. // */ // void clear(); // // /** // * Returns a measure of the amount of memory allocated for this storage engine. // * // * @return memory allocated for this engine in bytes // */ // long getAllocatedMemory(); // // /** // * Returns a measure of the amount of memory consumed by this storage engine. // * // * @return memory occupied by this engine in bytes // */ // long getOccupiedMemory(); // // /** // * Returns a measure of the amount of vital memory allocated for this storage engine. // * // * @return vital memory allocated for this engine in bytes // */ // long getVitalMemory(); // // /** // * Returns a measure of the total size of the keys and values stored in this storage engine. // * // * @return size of the stored keys and values in bytes // */ // long getDataSize(); // // /** // * Invalidate any local key/value caches. // * <p> // * This is called to indicate the termination of a map write "phase". Caching // * is permitted within a write operation (i.e. to cache around allocation // * failures during eviction processes). // */ // void invalidateCache(); // // void bind(Owner owner); // // void destroy(); // // boolean shrink(); // // interface Owner extends ReadWriteLock { // // Long getEncodingForHashAndBinary(int hash, ByteBuffer offHeapBinaryKey); // // long getSize(); // // long installMappingForHashAndEncoding(int pojoHash, ByteBuffer offheapBinaryKey, ByteBuffer offheapBinaryValue, int metadata); // // Iterable<Long> encodingSet(); // // boolean updateEncoding(int hashCode, long lastAddress, long compressed, long mask); // // Integer getSlotForHashAndEncoding(int hash, long address, long mask); // // boolean evict(int slot, boolean b); // // boolean isThiefForTableAllocations(); // // } // } // Path: src/main/java/org/terracotta/offheapstore/WriteLockedOffHeapClockCache.java import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.terracotta.offheapstore.paging.PageSource; import org.terracotta.offheapstore.storage.StorageEngine; /* * Copyright 2015 Terracotta, Inc., a Software AG company. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.offheapstore; /** * An exclusive-read/write off-heap clock cache. * <p> * This cache uses one of the unused bits in the off-heap entry's status value to * store the clock data. This clock data is safe to update during read * operations since the cache provides exclusive-read/write characteristics. * Since clock eviction data resides in the hash-map's table, it is correctly * copied across during table resize operations. * <p> * The cache uses a regular {@code ReentrantLock} to provide exclusive read and * write operations. * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Chris Dennis */ public class WriteLockedOffHeapClockCache<K, V> extends AbstractOffHeapClockCache<K, V> { private final Lock lock = new ReentrantLock();
public WriteLockedOffHeapClockCache(PageSource source, StorageEngine<? super K, ? super V> storageEngine) {
Terracotta-OSS/offheap-store
src/main/java/org/terracotta/offheapstore/storage/IntegerStorageEngine.java
// Path: src/main/java/org/terracotta/offheapstore/storage/StorageEngine.java // interface Owner extends ReadWriteLock { // // Long getEncodingForHashAndBinary(int hash, ByteBuffer offHeapBinaryKey); // // long getSize(); // // long installMappingForHashAndEncoding(int pojoHash, ByteBuffer offheapBinaryKey, ByteBuffer offheapBinaryValue, int metadata); // // Iterable<Long> encodingSet(); // // boolean updateEncoding(int hashCode, long lastAddress, long compressed, long mask); // // Integer getSlotForHashAndEncoding(int hash, long address, long mask); // // boolean evict(int slot, boolean b); // // boolean isThiefForTableAllocations(); // // }
import org.terracotta.offheapstore.storage.StorageEngine.Owner; import org.terracotta.offheapstore.util.Factory;
public void clear() { //no-op } @Override public long getAllocatedMemory() { return 0; } @Override public long getOccupiedMemory() { return 0; } @Override public long getVitalMemory() { return 0; } @Override public long getDataSize() { return 0; } @Override public void invalidateCache() { //no-op } @Override
// Path: src/main/java/org/terracotta/offheapstore/storage/StorageEngine.java // interface Owner extends ReadWriteLock { // // Long getEncodingForHashAndBinary(int hash, ByteBuffer offHeapBinaryKey); // // long getSize(); // // long installMappingForHashAndEncoding(int pojoHash, ByteBuffer offheapBinaryKey, ByteBuffer offheapBinaryValue, int metadata); // // Iterable<Long> encodingSet(); // // boolean updateEncoding(int hashCode, long lastAddress, long compressed, long mask); // // Integer getSlotForHashAndEncoding(int hash, long address, long mask); // // boolean evict(int slot, boolean b); // // boolean isThiefForTableAllocations(); // // } // Path: src/main/java/org/terracotta/offheapstore/storage/IntegerStorageEngine.java import org.terracotta.offheapstore.storage.StorageEngine.Owner; import org.terracotta.offheapstore.util.Factory; public void clear() { //no-op } @Override public long getAllocatedMemory() { return 0; } @Override public long getOccupiedMemory() { return 0; } @Override public long getVitalMemory() { return 0; } @Override public long getDataSize() { return 0; } @Override public void invalidateCache() { //no-op } @Override
public void bind(Owner owner, long mask) {
Zenika/findbugs-tainted-mode
plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintValueFrameModelingVisitor.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // }
import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.Constants; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.Collection;
boolean callReturnsReference = (returnType instanceof ReferenceType); XMethod calledMethod = XFactory.createXMethod(obj, getCPG()); propagateTaintedParameterToThis(calledMethod); if (!callReturnsReference) { handleNormalInstruction(obj); } else { modelCallReturnValue(obj, calledMethod); } } private void modelCallReturnValue(InvokeInstruction obj, XMethod calledMethod) { if (TaintAnalysis.DEBUG) { System.out.println("Check " + calledMethod + " for tainted data return..."); } TypeDataflow typeDataflow; TypeFrame typeFact; try { XMethod caller = XFactory.createXMethod(javaClassAndMethod); typeDataflow = Global.getAnalysisCache() .getMethodAnalysis(TypeDataflow.class, caller.getMethodDescriptor()); typeFact = typeDataflow.getFactAtLocation(getLocation()); } catch (CheckedAnalysisException e) { throw new InvalidBytecodeException("Can't obtain type dataflow for " + calledMethod, e); } Collection<XMethod> calledMethods; try {
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // } // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintValueFrameModelingVisitor.java import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.Constants; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.Collection; boolean callReturnsReference = (returnType instanceof ReferenceType); XMethod calledMethod = XFactory.createXMethod(obj, getCPG()); propagateTaintedParameterToThis(calledMethod); if (!callReturnsReference) { handleNormalInstruction(obj); } else { modelCallReturnValue(obj, calledMethod); } } private void modelCallReturnValue(InvokeInstruction obj, XMethod calledMethod) { if (TaintAnalysis.DEBUG) { System.out.println("Check " + calledMethod + " for tainted data return..."); } TypeDataflow typeDataflow; TypeFrame typeFact; try { XMethod caller = XFactory.createXMethod(javaClassAndMethod); typeDataflow = Global.getAnalysisCache() .getMethodAnalysis(TypeDataflow.class, caller.getMethodDescriptor()); typeFact = typeDataflow.getFactAtLocation(getLocation()); } catch (CheckedAnalysisException e) { throw new InvalidBytecodeException("Can't obtain type dataflow for " + calledMethod, e); } Collection<XMethod> calledMethods; try {
calledMethods = HierarchyUtil.getResolvedMethods(typeFact, obj, cpg);
Zenika/findbugs-tainted-mode
tests/cases/src/junit/su/msu/cs/lvk/secbugs/junit/TestTaintnessFrame.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrame.java // public class TaintnessFrame extends Frame<TaintnessValue> { // public TaintnessFrame(int numLocals) { // super(numLocals); // } // // /** // * Convert to string. // * // * Create a RLE representation, i.e. one T stands for itself, but several T's are shown as nT. // */ // @Override // public String toString() { // if (isTop()) // return "[TOP]"; // if (isBottom()) // return "[BOTTOM]"; // StringBuffer buf = new StringBuffer(); // buf.append('['); // String prevValue = null; // int accumCnt = 0; // int numSlots = getNumSlots(); // int start = 0; // for (int i = start; i < numSlots; ++i) { // if (i == getNumLocals()) { // // Use a "|" character to visually separate locals from // // the operand stack. // int last = buf.length() - 1; // if (last >= 0) { // if (buf.charAt(last) == ',') // buf.deleteCharAt(last); // } // // if (prevValue != null) { // // show trailing values of locals // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // accumCnt = 0; // } // prevValue = null; // // buf.append('|'); // } // String value = valueToString(getValue(i)); // boolean isLast = (i == numSlots - 1); // if (isLast && value.endsWith(",")) // value = value.substring(0, value.length() - 1); // // if (!isLast && (prevValue == null || prevValue.equals(value))) { // accumCnt++; // prevValue = value; // } else { // boolean lastAccumulated = false; // // show packed previous values // if (prevValue != null) { // if (isLast && prevValue.equals(value)) { // lastAccumulated = true; // ++accumCnt; // } // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // } // accumCnt = 1; // prevValue = value; // // if (isLast && !lastAccumulated) { // buf.append(value); // } // } // } // buf.append(']'); // return buf.toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessValue.java // public class TaintnessValue { // public static final int BOTTOM_VALUE = 1; // // public static final int TAINTED_VALUE = 2; // public static final int UNTAINTED_VALUE = 4; // // public static final TaintValue SENSITIVE_VALUE = new TaintValue(); // // private int mask = TAINTED_VALUE; // /** // * Source line, where taint value is consumed. // */ // private SourceLineAnnotation sinkSourceLine; // // public TaintnessValue() { // } // // public TaintnessValue(TaintnessValue source) { // this.mask = source.mask; // this.sinkSourceLine = source.sinkSourceLine; // } // // public void copyFrom(TaintnessValue other) { // this.mask = other.mask; // this.sinkSourceLine = other.sinkSourceLine; // } // // public void meetWith(TaintnessValue other) { // if ((other.mask & BOTTOM_VALUE) == BOTTOM_VALUE) { // this.mask = BOTTOM_VALUE; // this.sinkSourceLine = null; // } // // this.mask |= other.mask; // // if (this.sinkSourceLine == null) { // this.sinkSourceLine = other.sinkSourceLine; // } // else keep the first source line // } // // public static TaintnessValue merge(TaintnessValue a, TaintnessValue b) { // TaintnessValue result = new TaintnessValue(a); // result.meetWith(b); // return result; // } // // public boolean sameAs(TaintnessValue other) { // return this.mask == other.mask; // } // // public void setTainted(boolean tainted) { // if (tainted) { // mask |= TAINTED_VALUE; // } else { // mask &= ~TAINTED_VALUE; // } // } // // public boolean getTainted() { // return (mask & TAINTED_VALUE) != 0; // } // // public void setUntainted(boolean untainted) { // if (untainted) { // mask |= UNTAINTED_VALUE; // } else { // mask &= ~UNTAINTED_VALUE; // } // } // // public boolean getUntainted() { // return (mask & UNTAINTED_VALUE) != 0; // } // // public SourceLineAnnotation getSinkSourceLine() { // return sinkSourceLine; // } // // public void setSinkSourceLine(SourceLineAnnotation sinkSourceLine) { // this.sinkSourceLine = sinkSourceLine; // } // // public String toString() { // if (getTainted()) { // if (getUntainted()) { // return "X"; // } else { // return "T"; // } // } else if (getUntainted()) { // return "U"; // } else { // return "?"; // } // } // // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TaintnessValue that = (TaintnessValue) o; // // return mask == that.mask; // } // // public int hashCode() { // return mask; // } // }
import junit.framework.TestCase; import su.msu.cs.lvk.secbugs.bta.TaintnessFrame; import su.msu.cs.lvk.secbugs.bta.TaintnessValue;
package su.msu.cs.lvk.secbugs.junit; /** * @author Igor Konnov */ public class TestTaintnessFrame extends TestCase { public void testToStringEmptyStackOneLocal() {
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrame.java // public class TaintnessFrame extends Frame<TaintnessValue> { // public TaintnessFrame(int numLocals) { // super(numLocals); // } // // /** // * Convert to string. // * // * Create a RLE representation, i.e. one T stands for itself, but several T's are shown as nT. // */ // @Override // public String toString() { // if (isTop()) // return "[TOP]"; // if (isBottom()) // return "[BOTTOM]"; // StringBuffer buf = new StringBuffer(); // buf.append('['); // String prevValue = null; // int accumCnt = 0; // int numSlots = getNumSlots(); // int start = 0; // for (int i = start; i < numSlots; ++i) { // if (i == getNumLocals()) { // // Use a "|" character to visually separate locals from // // the operand stack. // int last = buf.length() - 1; // if (last >= 0) { // if (buf.charAt(last) == ',') // buf.deleteCharAt(last); // } // // if (prevValue != null) { // // show trailing values of locals // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // accumCnt = 0; // } // prevValue = null; // // buf.append('|'); // } // String value = valueToString(getValue(i)); // boolean isLast = (i == numSlots - 1); // if (isLast && value.endsWith(",")) // value = value.substring(0, value.length() - 1); // // if (!isLast && (prevValue == null || prevValue.equals(value))) { // accumCnt++; // prevValue = value; // } else { // boolean lastAccumulated = false; // // show packed previous values // if (prevValue != null) { // if (isLast && prevValue.equals(value)) { // lastAccumulated = true; // ++accumCnt; // } // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // } // accumCnt = 1; // prevValue = value; // // if (isLast && !lastAccumulated) { // buf.append(value); // } // } // } // buf.append(']'); // return buf.toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessValue.java // public class TaintnessValue { // public static final int BOTTOM_VALUE = 1; // // public static final int TAINTED_VALUE = 2; // public static final int UNTAINTED_VALUE = 4; // // public static final TaintValue SENSITIVE_VALUE = new TaintValue(); // // private int mask = TAINTED_VALUE; // /** // * Source line, where taint value is consumed. // */ // private SourceLineAnnotation sinkSourceLine; // // public TaintnessValue() { // } // // public TaintnessValue(TaintnessValue source) { // this.mask = source.mask; // this.sinkSourceLine = source.sinkSourceLine; // } // // public void copyFrom(TaintnessValue other) { // this.mask = other.mask; // this.sinkSourceLine = other.sinkSourceLine; // } // // public void meetWith(TaintnessValue other) { // if ((other.mask & BOTTOM_VALUE) == BOTTOM_VALUE) { // this.mask = BOTTOM_VALUE; // this.sinkSourceLine = null; // } // // this.mask |= other.mask; // // if (this.sinkSourceLine == null) { // this.sinkSourceLine = other.sinkSourceLine; // } // else keep the first source line // } // // public static TaintnessValue merge(TaintnessValue a, TaintnessValue b) { // TaintnessValue result = new TaintnessValue(a); // result.meetWith(b); // return result; // } // // public boolean sameAs(TaintnessValue other) { // return this.mask == other.mask; // } // // public void setTainted(boolean tainted) { // if (tainted) { // mask |= TAINTED_VALUE; // } else { // mask &= ~TAINTED_VALUE; // } // } // // public boolean getTainted() { // return (mask & TAINTED_VALUE) != 0; // } // // public void setUntainted(boolean untainted) { // if (untainted) { // mask |= UNTAINTED_VALUE; // } else { // mask &= ~UNTAINTED_VALUE; // } // } // // public boolean getUntainted() { // return (mask & UNTAINTED_VALUE) != 0; // } // // public SourceLineAnnotation getSinkSourceLine() { // return sinkSourceLine; // } // // public void setSinkSourceLine(SourceLineAnnotation sinkSourceLine) { // this.sinkSourceLine = sinkSourceLine; // } // // public String toString() { // if (getTainted()) { // if (getUntainted()) { // return "X"; // } else { // return "T"; // } // } else if (getUntainted()) { // return "U"; // } else { // return "?"; // } // } // // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TaintnessValue that = (TaintnessValue) o; // // return mask == that.mask; // } // // public int hashCode() { // return mask; // } // } // Path: tests/cases/src/junit/su/msu/cs/lvk/secbugs/junit/TestTaintnessFrame.java import junit.framework.TestCase; import su.msu.cs.lvk.secbugs.bta.TaintnessFrame; import su.msu.cs.lvk.secbugs.bta.TaintnessValue; package su.msu.cs.lvk.secbugs.junit; /** * @author Igor Konnov */ public class TestTaintnessFrame extends TestCase { public void testToStringEmptyStackOneLocal() {
TaintnessFrame frame = new TaintnessFrame(1);
Zenika/findbugs-tainted-mode
tests/cases/src/junit/su/msu/cs/lvk/secbugs/junit/TestTaintnessFrame.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrame.java // public class TaintnessFrame extends Frame<TaintnessValue> { // public TaintnessFrame(int numLocals) { // super(numLocals); // } // // /** // * Convert to string. // * // * Create a RLE representation, i.e. one T stands for itself, but several T's are shown as nT. // */ // @Override // public String toString() { // if (isTop()) // return "[TOP]"; // if (isBottom()) // return "[BOTTOM]"; // StringBuffer buf = new StringBuffer(); // buf.append('['); // String prevValue = null; // int accumCnt = 0; // int numSlots = getNumSlots(); // int start = 0; // for (int i = start; i < numSlots; ++i) { // if (i == getNumLocals()) { // // Use a "|" character to visually separate locals from // // the operand stack. // int last = buf.length() - 1; // if (last >= 0) { // if (buf.charAt(last) == ',') // buf.deleteCharAt(last); // } // // if (prevValue != null) { // // show trailing values of locals // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // accumCnt = 0; // } // prevValue = null; // // buf.append('|'); // } // String value = valueToString(getValue(i)); // boolean isLast = (i == numSlots - 1); // if (isLast && value.endsWith(",")) // value = value.substring(0, value.length() - 1); // // if (!isLast && (prevValue == null || prevValue.equals(value))) { // accumCnt++; // prevValue = value; // } else { // boolean lastAccumulated = false; // // show packed previous values // if (prevValue != null) { // if (isLast && prevValue.equals(value)) { // lastAccumulated = true; // ++accumCnt; // } // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // } // accumCnt = 1; // prevValue = value; // // if (isLast && !lastAccumulated) { // buf.append(value); // } // } // } // buf.append(']'); // return buf.toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessValue.java // public class TaintnessValue { // public static final int BOTTOM_VALUE = 1; // // public static final int TAINTED_VALUE = 2; // public static final int UNTAINTED_VALUE = 4; // // public static final TaintValue SENSITIVE_VALUE = new TaintValue(); // // private int mask = TAINTED_VALUE; // /** // * Source line, where taint value is consumed. // */ // private SourceLineAnnotation sinkSourceLine; // // public TaintnessValue() { // } // // public TaintnessValue(TaintnessValue source) { // this.mask = source.mask; // this.sinkSourceLine = source.sinkSourceLine; // } // // public void copyFrom(TaintnessValue other) { // this.mask = other.mask; // this.sinkSourceLine = other.sinkSourceLine; // } // // public void meetWith(TaintnessValue other) { // if ((other.mask & BOTTOM_VALUE) == BOTTOM_VALUE) { // this.mask = BOTTOM_VALUE; // this.sinkSourceLine = null; // } // // this.mask |= other.mask; // // if (this.sinkSourceLine == null) { // this.sinkSourceLine = other.sinkSourceLine; // } // else keep the first source line // } // // public static TaintnessValue merge(TaintnessValue a, TaintnessValue b) { // TaintnessValue result = new TaintnessValue(a); // result.meetWith(b); // return result; // } // // public boolean sameAs(TaintnessValue other) { // return this.mask == other.mask; // } // // public void setTainted(boolean tainted) { // if (tainted) { // mask |= TAINTED_VALUE; // } else { // mask &= ~TAINTED_VALUE; // } // } // // public boolean getTainted() { // return (mask & TAINTED_VALUE) != 0; // } // // public void setUntainted(boolean untainted) { // if (untainted) { // mask |= UNTAINTED_VALUE; // } else { // mask &= ~UNTAINTED_VALUE; // } // } // // public boolean getUntainted() { // return (mask & UNTAINTED_VALUE) != 0; // } // // public SourceLineAnnotation getSinkSourceLine() { // return sinkSourceLine; // } // // public void setSinkSourceLine(SourceLineAnnotation sinkSourceLine) { // this.sinkSourceLine = sinkSourceLine; // } // // public String toString() { // if (getTainted()) { // if (getUntainted()) { // return "X"; // } else { // return "T"; // } // } else if (getUntainted()) { // return "U"; // } else { // return "?"; // } // } // // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TaintnessValue that = (TaintnessValue) o; // // return mask == that.mask; // } // // public int hashCode() { // return mask; // } // }
import junit.framework.TestCase; import su.msu.cs.lvk.secbugs.bta.TaintnessFrame; import su.msu.cs.lvk.secbugs.bta.TaintnessValue;
package su.msu.cs.lvk.secbugs.junit; /** * @author Igor Konnov */ public class TestTaintnessFrame extends TestCase { public void testToStringEmptyStackOneLocal() { TaintnessFrame frame = new TaintnessFrame(1);
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrame.java // public class TaintnessFrame extends Frame<TaintnessValue> { // public TaintnessFrame(int numLocals) { // super(numLocals); // } // // /** // * Convert to string. // * // * Create a RLE representation, i.e. one T stands for itself, but several T's are shown as nT. // */ // @Override // public String toString() { // if (isTop()) // return "[TOP]"; // if (isBottom()) // return "[BOTTOM]"; // StringBuffer buf = new StringBuffer(); // buf.append('['); // String prevValue = null; // int accumCnt = 0; // int numSlots = getNumSlots(); // int start = 0; // for (int i = start; i < numSlots; ++i) { // if (i == getNumLocals()) { // // Use a "|" character to visually separate locals from // // the operand stack. // int last = buf.length() - 1; // if (last >= 0) { // if (buf.charAt(last) == ',') // buf.deleteCharAt(last); // } // // if (prevValue != null) { // // show trailing values of locals // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // accumCnt = 0; // } // prevValue = null; // // buf.append('|'); // } // String value = valueToString(getValue(i)); // boolean isLast = (i == numSlots - 1); // if (isLast && value.endsWith(",")) // value = value.substring(0, value.length() - 1); // // if (!isLast && (prevValue == null || prevValue.equals(value))) { // accumCnt++; // prevValue = value; // } else { // boolean lastAccumulated = false; // // show packed previous values // if (prevValue != null) { // if (isLast && prevValue.equals(value)) { // lastAccumulated = true; // ++accumCnt; // } // if (accumCnt > 1) { // buf.append(accumCnt); // } // buf.append(prevValue); // } // accumCnt = 1; // prevValue = value; // // if (isLast && !lastAccumulated) { // buf.append(value); // } // } // } // buf.append(']'); // return buf.toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessValue.java // public class TaintnessValue { // public static final int BOTTOM_VALUE = 1; // // public static final int TAINTED_VALUE = 2; // public static final int UNTAINTED_VALUE = 4; // // public static final TaintValue SENSITIVE_VALUE = new TaintValue(); // // private int mask = TAINTED_VALUE; // /** // * Source line, where taint value is consumed. // */ // private SourceLineAnnotation sinkSourceLine; // // public TaintnessValue() { // } // // public TaintnessValue(TaintnessValue source) { // this.mask = source.mask; // this.sinkSourceLine = source.sinkSourceLine; // } // // public void copyFrom(TaintnessValue other) { // this.mask = other.mask; // this.sinkSourceLine = other.sinkSourceLine; // } // // public void meetWith(TaintnessValue other) { // if ((other.mask & BOTTOM_VALUE) == BOTTOM_VALUE) { // this.mask = BOTTOM_VALUE; // this.sinkSourceLine = null; // } // // this.mask |= other.mask; // // if (this.sinkSourceLine == null) { // this.sinkSourceLine = other.sinkSourceLine; // } // else keep the first source line // } // // public static TaintnessValue merge(TaintnessValue a, TaintnessValue b) { // TaintnessValue result = new TaintnessValue(a); // result.meetWith(b); // return result; // } // // public boolean sameAs(TaintnessValue other) { // return this.mask == other.mask; // } // // public void setTainted(boolean tainted) { // if (tainted) { // mask |= TAINTED_VALUE; // } else { // mask &= ~TAINTED_VALUE; // } // } // // public boolean getTainted() { // return (mask & TAINTED_VALUE) != 0; // } // // public void setUntainted(boolean untainted) { // if (untainted) { // mask |= UNTAINTED_VALUE; // } else { // mask &= ~UNTAINTED_VALUE; // } // } // // public boolean getUntainted() { // return (mask & UNTAINTED_VALUE) != 0; // } // // public SourceLineAnnotation getSinkSourceLine() { // return sinkSourceLine; // } // // public void setSinkSourceLine(SourceLineAnnotation sinkSourceLine) { // this.sinkSourceLine = sinkSourceLine; // } // // public String toString() { // if (getTainted()) { // if (getUntainted()) { // return "X"; // } else { // return "T"; // } // } else if (getUntainted()) { // return "U"; // } else { // return "?"; // } // } // // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TaintnessValue that = (TaintnessValue) o; // // return mask == that.mask; // } // // public int hashCode() { // return mask; // } // } // Path: tests/cases/src/junit/su/msu/cs/lvk/secbugs/junit/TestTaintnessFrame.java import junit.framework.TestCase; import su.msu.cs.lvk.secbugs.bta.TaintnessFrame; import su.msu.cs.lvk.secbugs.bta.TaintnessValue; package su.msu.cs.lvk.secbugs.junit; /** * @author Igor Konnov */ public class TestTaintnessFrame extends TestCase { public void testToStringEmptyStackOneLocal() { TaintnessFrame frame = new TaintnessFrame(1);
frame.setValue(0, new TaintnessValue());
Zenika/findbugs-tainted-mode
plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessValue.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintValue.java // public class TaintValue { // public static final int TOP = -1; // public static final int BOTTOM = -2; // // // for the moment UNTAINTED == DETAINTED, but in the future we can use it... // public static final int DETAINTED = 1; // public static final int UNTAINTED = 1; // public static final int TAINTED = 2; // // public static final TaintValue UNTAINTED_VALUE = new TaintValue(UNTAINTED, 0); // // // kind of tainted value: DETAINTED, UNTAINTED, or TAINTED // private int kind; // // depth of tainted value. Value of depth 0 was assigned by some tainted value of depth 0 directly. // // Value of depth 1 received tainted value as a parameter of its method // private int depth; // // /** // * If value is tainted, then sourceLineAnnotation may point to the line from where tainted value is originating. // */ // private SourceLineAnnotation sourceLineAnnotation; // // public TaintValue() { // this.kind = TOP; // this.depth = 0; // } // // public TaintValue(int kind, int depth) { // this.kind = kind; // this.depth = depth; // // if (kind != TAINTED && depth != 0) { // throw new IllegalArgumentException("Depth must have zero value if kind != TAINTED"); // } // } // // public TaintValue(int kind) { // this.kind = kind; // this.depth = 0; // } // // public TaintValue(TaintValue source) { // this.kind = source.kind; // this.depth = source.depth; // this.sourceLineAnnotation = source.sourceLineAnnotation; // } // // public boolean isTop() { // return this.kind == TOP; // } // // public void copyFrom(TaintValue other) { // this.kind = other.kind; // this.depth = other.depth; // this.sourceLineAnnotation = other.sourceLineAnnotation; // } // // public void meetWith(TaintValue other) { // if (other.kind == BOTTOM) { // this.kind = BOTTOM; // this.depth = 0; // this.sourceLineAnnotation = null; // } // // if (this.kind < other.kind) { // this.kind = other.kind; // this.depth = other.depth; // this.sourceLineAnnotation = other.sourceLineAnnotation; // } else if (this.kind == other.kind && this.kind == TAINTED) { // this.depth = Math.min(this.depth, other.depth); // if (this.sourceLineAnnotation == null) { // this.sourceLineAnnotation = other.sourceLineAnnotation; // } // else keep the old one // } // } // // public static TaintValue merge(TaintValue a, TaintValue b) { // TaintValue result = new TaintValue(a); // result.meetWith(b); // return result; // } // // public int getKind() { // return kind; // } // // public boolean sameAs(TaintValue other) { // return this.kind == other.kind && this.depth == other.depth; // } // // public int getDepth() { // return depth; // } // // public void setDepth(int depth) { // this.depth = depth; // } // // public void increaseDepth() { // if (kind == TAINTED) { // this.depth++; // } // } // // public void decreaseDepth() { // if (kind == TAINTED && depth > 0) { // this.depth--; // } // } // // public SourceLineAnnotation getSourceLineAnnotation() { // return sourceLineAnnotation; // } // // public void setSourceLineAnnotation(SourceLineAnnotation sourceLineAnnotation) { // this.sourceLineAnnotation = sourceLineAnnotation; // } // // public String toString() { // switch (kind) { // case BOTTOM: // return "BOT"; // case UNTAINTED: // return "U"; // case TAINTED: // return "T[" + depth + "]"; // default: // return "TOP"; // } // } // // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaintValue other = (TaintValue) obj; // if (depth != other.depth) // return false; // if (kind != other.kind) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + depth; // result = prime * result + kind; // return result; // } // // }
import edu.umd.cs.findbugs.SourceLineAnnotation; import su.msu.cs.lvk.secbugs.ta.TaintValue;
package su.msu.cs.lvk.secbugs.bta; /** * Dataflow value representing sensitive data, i.e. it can't be returned by tainted source. * * @author Igor Konnov */ public class TaintnessValue { public static final int BOTTOM_VALUE = 1; public static final int TAINTED_VALUE = 2; public static final int UNTAINTED_VALUE = 4;
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintValue.java // public class TaintValue { // public static final int TOP = -1; // public static final int BOTTOM = -2; // // // for the moment UNTAINTED == DETAINTED, but in the future we can use it... // public static final int DETAINTED = 1; // public static final int UNTAINTED = 1; // public static final int TAINTED = 2; // // public static final TaintValue UNTAINTED_VALUE = new TaintValue(UNTAINTED, 0); // // // kind of tainted value: DETAINTED, UNTAINTED, or TAINTED // private int kind; // // depth of tainted value. Value of depth 0 was assigned by some tainted value of depth 0 directly. // // Value of depth 1 received tainted value as a parameter of its method // private int depth; // // /** // * If value is tainted, then sourceLineAnnotation may point to the line from where tainted value is originating. // */ // private SourceLineAnnotation sourceLineAnnotation; // // public TaintValue() { // this.kind = TOP; // this.depth = 0; // } // // public TaintValue(int kind, int depth) { // this.kind = kind; // this.depth = depth; // // if (kind != TAINTED && depth != 0) { // throw new IllegalArgumentException("Depth must have zero value if kind != TAINTED"); // } // } // // public TaintValue(int kind) { // this.kind = kind; // this.depth = 0; // } // // public TaintValue(TaintValue source) { // this.kind = source.kind; // this.depth = source.depth; // this.sourceLineAnnotation = source.sourceLineAnnotation; // } // // public boolean isTop() { // return this.kind == TOP; // } // // public void copyFrom(TaintValue other) { // this.kind = other.kind; // this.depth = other.depth; // this.sourceLineAnnotation = other.sourceLineAnnotation; // } // // public void meetWith(TaintValue other) { // if (other.kind == BOTTOM) { // this.kind = BOTTOM; // this.depth = 0; // this.sourceLineAnnotation = null; // } // // if (this.kind < other.kind) { // this.kind = other.kind; // this.depth = other.depth; // this.sourceLineAnnotation = other.sourceLineAnnotation; // } else if (this.kind == other.kind && this.kind == TAINTED) { // this.depth = Math.min(this.depth, other.depth); // if (this.sourceLineAnnotation == null) { // this.sourceLineAnnotation = other.sourceLineAnnotation; // } // else keep the old one // } // } // // public static TaintValue merge(TaintValue a, TaintValue b) { // TaintValue result = new TaintValue(a); // result.meetWith(b); // return result; // } // // public int getKind() { // return kind; // } // // public boolean sameAs(TaintValue other) { // return this.kind == other.kind && this.depth == other.depth; // } // // public int getDepth() { // return depth; // } // // public void setDepth(int depth) { // this.depth = depth; // } // // public void increaseDepth() { // if (kind == TAINTED) { // this.depth++; // } // } // // public void decreaseDepth() { // if (kind == TAINTED && depth > 0) { // this.depth--; // } // } // // public SourceLineAnnotation getSourceLineAnnotation() { // return sourceLineAnnotation; // } // // public void setSourceLineAnnotation(SourceLineAnnotation sourceLineAnnotation) { // this.sourceLineAnnotation = sourceLineAnnotation; // } // // public String toString() { // switch (kind) { // case BOTTOM: // return "BOT"; // case UNTAINTED: // return "U"; // case TAINTED: // return "T[" + depth + "]"; // default: // return "TOP"; // } // } // // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TaintValue other = (TaintValue) obj; // if (depth != other.depth) // return false; // if (kind != other.kind) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + depth; // result = prime * result + kind; // return result; // } // // } // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessValue.java import edu.umd.cs.findbugs.SourceLineAnnotation; import su.msu.cs.lvk.secbugs.ta.TaintValue; package su.msu.cs.lvk.secbugs.bta; /** * Dataflow value representing sensitive data, i.e. it can't be returned by tainted source. * * @author Igor Konnov */ public class TaintnessValue { public static final int BOTTOM_VALUE = 1; public static final int TAINTED_VALUE = 2; public static final int UNTAINTED_VALUE = 4;
public static final TaintValue SENSITIVE_VALUE = new TaintValue();
Zenika/findbugs-tainted-mode
plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrameModelingVisitor.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // }
import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List;
package su.msu.cs.lvk.secbugs.bta; /** * @author Igor Konnov */ public class TaintnessFrameModelingVisitor extends AbstractBackwardFrameModelingVisitor<TaintnessValue, TaintnessFrame> { private JavaClassAndMethod javaClassAndMethod; private ParameterTaintnessPropertyDatabase parameterTaintnessPropertyDatabase;
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // } // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrameModelingVisitor.java import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; package su.msu.cs.lvk.secbugs.bta; /** * @author Igor Konnov */ public class TaintnessFrameModelingVisitor extends AbstractBackwardFrameModelingVisitor<TaintnessValue, TaintnessFrame> { private JavaClassAndMethod javaClassAndMethod; private ParameterTaintnessPropertyDatabase parameterTaintnessPropertyDatabase;
private KeyIndicatorPropertyDatabase keyIndicatorPropertyDatabase;
Zenika/findbugs-tainted-mode
plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrameModelingVisitor.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // }
import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List;
for (int i = 0; i < calledMethod.getNumParams() + shift; ++i) { TaintnessValue value = new TaintnessValue(); value.setTainted(true); value.setUntainted(false); pushValues.add(value); if(i==0 && !calledMethod.isStatic()){ continue;//first value on stack for non static method : this } if(parameterIterator.hasNext()){ paramSig = parameterIterator.next(); if (paramSig.equals("D") || paramSig.equals("J")){ pushValues.add(value); //for long and double types : 2 slots -> 2 values } } } TypeDataflow typeDataflow; TypeFrame typeFact; try { XMethod caller = XFactory.createXMethod(javaClassAndMethod); typeDataflow = Global.getAnalysisCache() .getMethodAnalysis(TypeDataflow.class, caller.getMethodDescriptor()); typeFact = typeDataflow.getFactAtLocation(getLocation()); } catch (CheckedAnalysisException e) { throw new InvalidBytecodeException("Can't obtain type dataflow for " + calledMethod, e); } try {
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // } // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrameModelingVisitor.java import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; for (int i = 0; i < calledMethod.getNumParams() + shift; ++i) { TaintnessValue value = new TaintnessValue(); value.setTainted(true); value.setUntainted(false); pushValues.add(value); if(i==0 && !calledMethod.isStatic()){ continue;//first value on stack for non static method : this } if(parameterIterator.hasNext()){ paramSig = parameterIterator.next(); if (paramSig.equals("D") || paramSig.equals("J")){ pushValues.add(value); //for long and double types : 2 slots -> 2 values } } } TypeDataflow typeDataflow; TypeFrame typeFact; try { XMethod caller = XFactory.createXMethod(javaClassAndMethod); typeDataflow = Global.getAnalysisCache() .getMethodAnalysis(TypeDataflow.class, caller.getMethodDescriptor()); typeFact = typeDataflow.getFactAtLocation(getLocation()); } catch (CheckedAnalysisException e) { throw new InvalidBytecodeException("Can't obtain type dataflow for " + calledMethod, e); } try {
Collection<XMethod> calledMethods = HierarchyUtil.getResolvedMethods(typeFact, obj, cpg);
Zenika/findbugs-tainted-mode
plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrameModelingVisitor.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // }
import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List;
ParameterTaintnessProperty prop = parameterTaintnessPropertyDatabase.getProperty(calledMethod.getMethodDescriptor()); if (prop != null) { SignatureParser sigParser = new SignatureParser(calledMethod.getSignature()); Iterator<String> parameterIterator = sigParser.parameterSignatureIterator(); for (int i = 0; i < calledMethod.getNumParams(); ++i) { TaintnessValue v = values.get(shift + i); v.setTainted(prop.isTaint(i) & v.getTainted()); v.setUntainted(prop.isUntaint(i) | v.getUntainted()); String paramSig = parameterIterator.next(); if (paramSig.equals("D") || paramSig.equals("J")){ i++; } if (prop.isDirectSink()) { SourceLineAnnotation source = SourceLineAnnotation.fromVisitedInstruction(javaClassAndMethod.toMethodDescriptor(), getLocation()); v.setSinkSourceLine(source); } if (DEBUG) { System.out.println("Method's " + calledMethod + " parameter " + i + " is untaint?: " + prop.isUntaint(i)); } } } else { throw new IllegalArgumentException("Called method " + calledMethod + " should be put to taintness database by MethodAnnotationDetector"); } } private void checkValidatorParameters(XMethod calledMethod, List<TaintnessValue> values, int shift) {
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/util/HierarchyUtil.java // public class HierarchyUtil { // public static Set<XMethod> getResolvedMethods(TypeFrame typeFrame, InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException, DataflowAnalysisException { // Set<JavaClassAndMethod> targetMethodSet = Hierarchy // .resolveMethodCallTargets(invokeInstruction, typeFrame, cpg); // Set<XMethod> calledMethods = new HashSet<XMethod>(); // for (JavaClassAndMethod m : targetMethodSet) { // calledMethods.add(XFactory.createXMethod(m)); // } // calledMethods.add(XFactory.createXMethod(invokeInstruction, cpg)); // return calledMethods; // } // } // Path: plugin/src/java/su/msu/cs/lvk/secbugs/bta/TaintnessFrameModelingVisitor.java import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.ba.type.TypeDataflow; import edu.umd.cs.findbugs.ba.type.TypeFrame; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; import su.msu.cs.lvk.secbugs.util.HierarchyUtil; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; ParameterTaintnessProperty prop = parameterTaintnessPropertyDatabase.getProperty(calledMethod.getMethodDescriptor()); if (prop != null) { SignatureParser sigParser = new SignatureParser(calledMethod.getSignature()); Iterator<String> parameterIterator = sigParser.parameterSignatureIterator(); for (int i = 0; i < calledMethod.getNumParams(); ++i) { TaintnessValue v = values.get(shift + i); v.setTainted(prop.isTaint(i) & v.getTainted()); v.setUntainted(prop.isUntaint(i) | v.getUntainted()); String paramSig = parameterIterator.next(); if (paramSig.equals("D") || paramSig.equals("J")){ i++; } if (prop.isDirectSink()) { SourceLineAnnotation source = SourceLineAnnotation.fromVisitedInstruction(javaClassAndMethod.toMethodDescriptor(), getLocation()); v.setSinkSourceLine(source); } if (DEBUG) { System.out.println("Method's " + calledMethod + " parameter " + i + " is untaint?: " + prop.isUntaint(i)); } } } else { throw new IllegalArgumentException("Called method " + calledMethod + " should be put to taintness database by MethodAnnotationDetector"); } } private void checkValidatorParameters(XMethod calledMethod, List<TaintnessValue> values, int shift) {
KeyIndicatorProperty prop = keyIndicatorPropertyDatabase.getProperty(calledMethod.getMethodDescriptor());
Zenika/findbugs-tainted-mode
plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintAnalysis.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // }
import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import org.apache.bcel.Constants; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase;
package su.msu.cs.lvk.secbugs.ta; /** * @author Igor Konnov */ public class TaintAnalysis extends FrameDataflowAnalysis<TaintValue, TaintValueFrame> { static final boolean DEBUG = true; //SystemProperties.getBoolean("ta.debug"); static { if (DEBUG) { System.out.println("ta.debug enabled"); } } private MethodGen methodGen; private TaintValueFrameModelingVisitor visitor; private TaintValueFrame cachedEntryFact;
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintAnalysis.java import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import org.apache.bcel.Constants; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; package su.msu.cs.lvk.secbugs.ta; /** * @author Igor Konnov */ public class TaintAnalysis extends FrameDataflowAnalysis<TaintValue, TaintValueFrame> { static final boolean DEBUG = true; //SystemProperties.getBoolean("ta.debug"); static { if (DEBUG) { System.out.println("ta.debug enabled"); } } private MethodGen methodGen; private TaintValueFrameModelingVisitor visitor; private TaintValueFrame cachedEntryFact;
private KeyIndicatorPropertyDatabase keyIndicatorPropertyDatabase;
Zenika/findbugs-tainted-mode
plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintAnalysis.java
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // }
import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import org.apache.bcel.Constants; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase;
TaintValueFrame predFact = createFact(); copy(getResultFact(block), predFact); edgeTransfer(edge, predFact); TaintValueFrame result = createFact(); makeFactTop(result); meetInto(predFact, edge, result, false); return result; } private TaintValueFrame detaintIfValidated(BasicBlock sourceBlock, int edgeType, TaintValueFrame fact) throws DataflowAnalysisException { // call to validator looks like follows: // invokevirtual m // ifeq n InstructionHandle last = sourceBlock.getLastInstruction(); if (last != null) { InstructionHandle prev = last.getPrev(); int opcode = last.getInstruction().getOpcode(); if (edgeType == Edge.FALL_THROUGH_EDGE && opcode == Constants.IFEQ || edgeType == Edge.IFCMP_EDGE && opcode == Constants.IFNE) { // It may be a call to validation method, // and current block is a then-branch if (prev != null && prev.getInstruction() instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) prev.getInstruction(); XMethod calledMethod = XFactory.createXMethod(invoke, methodGen.getConstantPool());
// Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorProperty.java // public class KeyIndicatorProperty { // public enum IndicatorType { UNKNOWN, VALIDATOR, ACCESS } // private IndicatorType indicatorType; // // public KeyIndicatorProperty(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public IndicatorType getIndicatorType() { // return indicatorType; // } // // public void setIndicatorType(IndicatorType indicatorType) { // this.indicatorType = indicatorType; // } // // public static KeyIndicatorProperty valueOf(String s) { // return new KeyIndicatorProperty(IndicatorType.valueOf(s)); // } // } // // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ma/KeyIndicatorPropertyDatabase.java // public class KeyIndicatorPropertyDatabase extends MethodPropertyDatabase<KeyIndicatorProperty> { // @Override // protected KeyIndicatorProperty decodeProperty(String propStr) // throws PropertyDatabaseFormatException { // return KeyIndicatorProperty.valueOf(propStr); // } // // @Override // protected String encodeProperty(KeyIndicatorProperty property) { // return property.getIndicatorType().toString(); // } // // } // Path: plugin/src/java/su/msu/cs/lvk/secbugs/ta/TaintAnalysis.java import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.*; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import org.apache.bcel.Constants; import org.apache.bcel.generic.*; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorProperty; import su.msu.cs.lvk.secbugs.ma.KeyIndicatorPropertyDatabase; TaintValueFrame predFact = createFact(); copy(getResultFact(block), predFact); edgeTransfer(edge, predFact); TaintValueFrame result = createFact(); makeFactTop(result); meetInto(predFact, edge, result, false); return result; } private TaintValueFrame detaintIfValidated(BasicBlock sourceBlock, int edgeType, TaintValueFrame fact) throws DataflowAnalysisException { // call to validator looks like follows: // invokevirtual m // ifeq n InstructionHandle last = sourceBlock.getLastInstruction(); if (last != null) { InstructionHandle prev = last.getPrev(); int opcode = last.getInstruction().getOpcode(); if (edgeType == Edge.FALL_THROUGH_EDGE && opcode == Constants.IFEQ || edgeType == Edge.IFCMP_EDGE && opcode == Constants.IFNE) { // It may be a call to validation method, // and current block is a then-branch if (prev != null && prev.getInstruction() instanceof InvokeInstruction) { InvokeInstruction invoke = (InvokeInstruction) prev.getInstruction(); XMethod calledMethod = XFactory.createXMethod(invoke, methodGen.getConstantPool());
KeyIndicatorProperty prop = keyIndicatorPropertyDatabase.getProperty(calledMethod.getMethodDescriptor());
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactApplication.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java // @Singleton // @Component(modules = {ApplicationModule.class, NetworkModule.class}) // public interface ApplicationComponent { // // @NonNull // Context getContext(); // // @NonNull // Logger getLogger(); // // @NonNull // Repository getRepository(); // // void inject(HomeActivity homeActivity); // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationModule.java // @Module // public class ApplicationModule { // // private final Context context; // // public ApplicationModule(@NonNull Context context) { // this.context = context; // } // // @Singleton // @Provides // @NonNull // public Context getContext() { // return context; // } // // @Singleton // @Provides // @NonNull // public Repository getRepository(@NonNull Retrofit retrofit) { // return new Service(retrofit.create(Service.Api.class)); // } // // }
import android.app.Application; import android.support.annotation.NonNull; import au.com.dius.pactconsumer.app.di.ApplicationComponent; import au.com.dius.pactconsumer.app.di.ApplicationModule; import au.com.dius.pactconsumer.app.di.DaggerApplicationComponent;
package au.com.dius.pactconsumer.app; public class PactApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); initialise(); } private void initialise() { applicationComponent = DaggerApplicationComponent.builder()
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java // @Singleton // @Component(modules = {ApplicationModule.class, NetworkModule.class}) // public interface ApplicationComponent { // // @NonNull // Context getContext(); // // @NonNull // Logger getLogger(); // // @NonNull // Repository getRepository(); // // void inject(HomeActivity homeActivity); // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationModule.java // @Module // public class ApplicationModule { // // private final Context context; // // public ApplicationModule(@NonNull Context context) { // this.context = context; // } // // @Singleton // @Provides // @NonNull // public Context getContext() { // return context; // } // // @Singleton // @Provides // @NonNull // public Repository getRepository(@NonNull Retrofit retrofit) { // return new Service(retrofit.create(Service.Api.class)); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactApplication.java import android.app.Application; import android.support.annotation.NonNull; import au.com.dius.pactconsumer.app.di.ApplicationComponent; import au.com.dius.pactconsumer.app.di.ApplicationModule; import au.com.dius.pactconsumer.app.di.DaggerApplicationComponent; package au.com.dius.pactconsumer.app; public class PactApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); initialise(); } private void initialise() { applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/domain/Contract.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactPresenter.java // public interface PactPresenter { // void onStart(); // void onStop(); // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactView.java // public interface PactView { // }
import android.support.annotation.NonNull; import au.com.dius.pactconsumer.app.PactPresenter; import au.com.dius.pactconsumer.app.PactView;
package au.com.dius.pactconsumer.domain; public interface Contract { interface View extends PactView { void setViewState(@NonNull ViewState viewState); }
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactPresenter.java // public interface PactPresenter { // void onStart(); // void onStop(); // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactView.java // public interface PactView { // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/domain/Contract.java import android.support.annotation.NonNull; import au.com.dius.pactconsumer.app.PactPresenter; import au.com.dius.pactconsumer.app.PactView; package au.com.dius.pactconsumer.domain; public interface Contract { interface View extends PactView { void setViewState(@NonNull ViewState viewState); }
interface Presenter extends PactPresenter {
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceNoContentPactTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // }
import android.content.Context; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Collections; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock;
package au.com.dius.pactconsumer.data; public class ServiceNoContentPactTest { static final DateTime DATE_TIME; static { DATE_TIME = DateTime.now(); } Service service; @Before public void setUp() {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceNoContentPactTest.java import android.content.Context; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Collections; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock; package au.com.dius.pactconsumer.data; public class ServiceNoContentPactTest { static final DateTime DATE_TIME; static { DATE_TIME = DateTime.now(); } Service service; @Before public void setUp() {
NetworkModule networkModule = new NetworkModule();
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceNoContentPactTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // }
import android.content.Context; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Collections; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock;
package au.com.dius.pactconsumer.data; public class ServiceNoContentPactTest { static final DateTime DATE_TIME; static { DATE_TIME = DateTime.now(); } Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is == 0") .uponReceiving("a request for json data") .path("/provider.json") .method("GET")
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceNoContentPactTest.java import android.content.Context; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Collections; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock; package au.com.dius.pactconsumer.data; public class ServiceNoContentPactTest { static final DateTime DATE_TIME; static { DATE_TIME = DateTime.now(); } Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is == 0") .uponReceiving("a request for json data") .path("/provider.json") .method("GET")
.query("valid_date=" + DateHelper.encodeDate(DATE_TIME))
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceNoContentPactTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // }
import android.content.Context; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Collections; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock;
package au.com.dius.pactconsumer.data; public class ServiceNoContentPactTest { static final DateTime DATE_TIME; static { DATE_TIME = DateTime.now(); } Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is == 0") .uponReceiving("a request for json data") .path("/provider.json") .method("GET") .query("valid_date=" + DateHelper.encodeDate(DATE_TIME)) .willRespondWith() .status(404) .toFragment(); } @Test @PactVerification("our_provider") public void should_process_the_json_payload_from_provider() {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceNoContentPactTest.java import android.content.Context; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Collections; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock; package au.com.dius.pactconsumer.data; public class ServiceNoContentPactTest { static final DateTime DATE_TIME; static { DATE_TIME = DateTime.now(); } Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is == 0") .uponReceiving("a request for json data") .path("/provider.json") .method("GET") .query("valid_date=" + DateHelper.encodeDate(DATE_TIME)) .willRespondWith() .status(404) .toFragment(); } @Test @PactVerification("our_provider") public void should_process_the_json_payload_from_provider() {
TestObserver<ServiceResponse> observer = service.fetchResponse(DATE_TIME).test();
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceMissingQueryPactTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import android.content.Context; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock;
package au.com.dius.pactconsumer.data; public class ServiceMissingQueryPactTest { Service service; @Before public void setUp() {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceMissingQueryPactTest.java import android.content.Context; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock; package au.com.dius.pactconsumer.data; public class ServiceMissingQueryPactTest { Service service; @Before public void setUp() {
NetworkModule networkModule = new NetworkModule();
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceMissingQueryPactTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import android.content.Context; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock;
package au.com.dius.pactconsumer.data; public class ServiceMissingQueryPactTest { Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is > 0") .uponReceiving("a request with an missing date parameter") .path("/provider.json") .method("GET") .willRespondWith() .status(400) .body("valid_date is required") .toFragment(); } @Test @PactVerification("our_provider") public void should_process_the_json_payload_from_provider() {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceMissingQueryPactTest.java import android.content.Context; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock; package au.com.dius.pactconsumer.data; public class ServiceMissingQueryPactTest { Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is > 0") .uponReceiving("a request with an missing date parameter") .path("/provider.json") .method("GET") .willRespondWith() .status(400) .body("valid_date is required") .toFragment(); } @Test @PactVerification("our_provider") public void should_process_the_json_payload_from_provider() {
TestObserver<ServiceResponse> observer = service.fetchResponse(null).test();
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceMissingQueryPactTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import android.content.Context; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock;
package au.com.dius.pactconsumer.data; public class ServiceMissingQueryPactTest { Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is > 0") .uponReceiving("a request with an missing date parameter") .path("/provider.json") .method("GET") .willRespondWith() .status(400) .body("valid_date is required") .toFragment(); } @Test @PactVerification("our_provider") public void should_process_the_json_payload_from_provider() { TestObserver<ServiceResponse> observer = service.fetchResponse(null).test();
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java // @Module // public class NetworkModule { // // @Singleton // @Provides // @NonNull // public Retrofit getRetrofit(@NonNull Context context) { // return getRetrofit(context, BuildConfig.BASE_URL); // } // // @VisibleForTesting // public Retrofit getRetrofit(@NonNull Context context, // @NonNull String baseUrl) { // return new Retrofit.Builder() // .baseUrl(baseUrl) // .client(getOkHttpClient(context)) // .addConverterFactory(MoshiConverterFactory.create(getMoshi())) // .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // .build(); // } // // private OkHttpClient getOkHttpClient(@NonNull Context context) { // OkHttpClient.Builder builder = new OkHttpClient.Builder(); // if (BuildConfig.DEBUG) { // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // builder.addNetworkInterceptor(interceptor); // } // builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); // return builder.build(); // } // // private Moshi getMoshi() { // return new Moshi.Builder().add(new DateTimeAdapter()).build(); // } // // public static class DateTimeAdapter { // // @ToJson // public String toJson(DateTime dateTime) { // return DateHelper.toString(dateTime); // } // // @FromJson // public DateTime fromJson(String json) { // return DateHelper.parse(json); // } // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceMissingQueryPactTest.java import android.content.Context; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import au.com.dius.pact.consumer.Pact; import au.com.dius.pact.consumer.PactProviderRule; import au.com.dius.pact.consumer.PactVerification; import au.com.dius.pact.consumer.dsl.PactDslWithProvider; import au.com.dius.pact.model.PactFragment; import au.com.dius.pactconsumer.app.di.NetworkModule; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver; import static org.mockito.Mockito.mock; package au.com.dius.pactconsumer.data; public class ServiceMissingQueryPactTest { Service service; @Before public void setUp() { NetworkModule networkModule = new NetworkModule(); service = new Service(networkModule.getRetrofit(mock(Context.class), "http://localhost:9292").create(Service.Api.class)); } @Rule public PactProviderRule mockProvider = new PactProviderRule("our_provider", "localhost", 9292, this); @Pact(provider = "our_provider", consumer = "our_consumer") public PactFragment createFragment(PactDslWithProvider builder) throws UnsupportedEncodingException { return builder .given("data count is > 0") .uponReceiving("a request with an missing date parameter") .path("/provider.json") .method("GET") .willRespondWith() .status(400) .body("valid_date is required") .toFragment(); } @Test @PactVerification("our_provider") public void should_process_the_json_payload_from_provider() { TestObserver<ServiceResponse> observer = service.fetchResponse(null).test();
observer.assertError(BadRequestException.class);
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import android.support.annotation.NonNull; import org.joda.time.DateTime; import java.util.Arrays; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single;
package au.com.dius.pactconsumer.data; @Singleton public class FakeService implements Repository {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java import android.support.annotation.NonNull; import org.joda.time.DateTime; import java.util.Arrays; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single; package au.com.dius.pactconsumer.data; @Singleton public class FakeService implements Repository {
public static final ServiceResponse RESPONSE;
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import android.support.annotation.NonNull; import org.joda.time.DateTime; import java.util.Arrays; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single;
package au.com.dius.pactconsumer.data; @Singleton public class FakeService implements Repository { public static final ServiceResponse RESPONSE; static { RESPONSE = new ServiceResponse( DateTime.now(), Arrays.asList(
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java import android.support.annotation.NonNull; import org.joda.time.DateTime; import java.util.Arrays; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single; package au.com.dius.pactconsumer.data; @Singleton public class FakeService implements Repository { public static final ServiceResponse RESPONSE; static { RESPONSE = new ServiceResponse( DateTime.now(), Arrays.asList(
Animal.create("Doggy", "dog"),
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import android.support.annotation.NonNull; import org.joda.time.DateTime; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single;
package au.com.dius.pactconsumer.data; public interface Repository { @NonNull
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java import android.support.annotation.NonNull; import org.joda.time.DateTime; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single; package au.com.dius.pactconsumer.data; public interface Repository { @NonNull
Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime);
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/HomeActivity.java // public class HomeActivity extends PactActivity implements Contract.View { // // @Inject // Repository repository; // // @Inject // Logger logger; // // private Presenter presenter; // // private View loadingView; // private TextView emptyView; // private TextView errorView; // private RecyclerView recyclerView; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animals); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // initialiseView(); // initialisePresenter(savedInstanceState); // } // // private void initialiseView() { // loadingView = findViewById(R.id.view_loading); // emptyView = (TextView) findViewById(R.id.txt_empty); // errorView = (TextView) findViewById(R.id.txt_error); // recyclerView = (RecyclerView) findViewById(R.id.view_recycler); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // } // // private void initialisePresenter(@Nullable Bundle savedInstanceState) { // presenter = new Presenter(repository, this, new RxBinder(), logger); // } // // @Override // public void inject(@NonNull ApplicationComponent component) { // component.inject(this); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onStart(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onStop(); // } // // @Override // public void setViewState(@NonNull ViewState viewState) { // if (viewState instanceof ViewState.Loading) { // setLoading((ViewState.Loading) viewState); // } else if (viewState instanceof ViewState.Loaded) { // setLoaded((ViewState.Loaded) viewState); // } else if (viewState instanceof ViewState.Empty) { // setEmpty((ViewState.Empty) viewState); // } else if (viewState instanceof ViewState.Error) { // setError((ViewState.Error) viewState); // } // } // // private void setLoading(@NonNull ViewState.Loading viewState) { // hideViews(); // loadingView.setVisibility(View.VISIBLE); // } // // private void setLoaded(@NonNull ViewState.Loaded viewState) { // hideViews(); // recyclerView.setVisibility(View.VISIBLE); // recyclerView.setAdapter(new AnimalsAdapter(viewState.getAnimals())); // } // // private void setEmpty(@NonNull ViewState.Empty viewState) { // hideViews(); // emptyView.setText(getResources().getString(viewState.getMessage())); // emptyView.setVisibility(View.VISIBLE); // } // // private void setError(@NonNull ViewState.Error viewState) { // hideViews(); // errorView.setText(getResources().getString(viewState.getMessage())); // errorView.setVisibility(View.VISIBLE); // } // // private void hideViews() { // loadingView.setVisibility(View.GONE); // emptyView.setVisibility(View.GONE); // errorView.setVisibility(View.GONE); // recyclerView.setVisibility(View.GONE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // }
import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.presentation.HomeActivity; import au.com.dius.pactconsumer.util.Logger; import dagger.Component;
package au.com.dius.pactconsumer.app.di; @Singleton @Component(modules = {ApplicationModule.class, NetworkModule.class}) public interface ApplicationComponent { @NonNull Context getContext(); @NonNull
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/HomeActivity.java // public class HomeActivity extends PactActivity implements Contract.View { // // @Inject // Repository repository; // // @Inject // Logger logger; // // private Presenter presenter; // // private View loadingView; // private TextView emptyView; // private TextView errorView; // private RecyclerView recyclerView; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animals); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // initialiseView(); // initialisePresenter(savedInstanceState); // } // // private void initialiseView() { // loadingView = findViewById(R.id.view_loading); // emptyView = (TextView) findViewById(R.id.txt_empty); // errorView = (TextView) findViewById(R.id.txt_error); // recyclerView = (RecyclerView) findViewById(R.id.view_recycler); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // } // // private void initialisePresenter(@Nullable Bundle savedInstanceState) { // presenter = new Presenter(repository, this, new RxBinder(), logger); // } // // @Override // public void inject(@NonNull ApplicationComponent component) { // component.inject(this); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onStart(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onStop(); // } // // @Override // public void setViewState(@NonNull ViewState viewState) { // if (viewState instanceof ViewState.Loading) { // setLoading((ViewState.Loading) viewState); // } else if (viewState instanceof ViewState.Loaded) { // setLoaded((ViewState.Loaded) viewState); // } else if (viewState instanceof ViewState.Empty) { // setEmpty((ViewState.Empty) viewState); // } else if (viewState instanceof ViewState.Error) { // setError((ViewState.Error) viewState); // } // } // // private void setLoading(@NonNull ViewState.Loading viewState) { // hideViews(); // loadingView.setVisibility(View.VISIBLE); // } // // private void setLoaded(@NonNull ViewState.Loaded viewState) { // hideViews(); // recyclerView.setVisibility(View.VISIBLE); // recyclerView.setAdapter(new AnimalsAdapter(viewState.getAnimals())); // } // // private void setEmpty(@NonNull ViewState.Empty viewState) { // hideViews(); // emptyView.setText(getResources().getString(viewState.getMessage())); // emptyView.setVisibility(View.VISIBLE); // } // // private void setError(@NonNull ViewState.Error viewState) { // hideViews(); // errorView.setText(getResources().getString(viewState.getMessage())); // errorView.setVisibility(View.VISIBLE); // } // // private void hideViews() { // loadingView.setVisibility(View.GONE); // emptyView.setVisibility(View.GONE); // errorView.setVisibility(View.GONE); // recyclerView.setVisibility(View.GONE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.presentation.HomeActivity; import au.com.dius.pactconsumer.util.Logger; import dagger.Component; package au.com.dius.pactconsumer.app.di; @Singleton @Component(modules = {ApplicationModule.class, NetworkModule.class}) public interface ApplicationComponent { @NonNull Context getContext(); @NonNull
Logger getLogger();
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/HomeActivity.java // public class HomeActivity extends PactActivity implements Contract.View { // // @Inject // Repository repository; // // @Inject // Logger logger; // // private Presenter presenter; // // private View loadingView; // private TextView emptyView; // private TextView errorView; // private RecyclerView recyclerView; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animals); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // initialiseView(); // initialisePresenter(savedInstanceState); // } // // private void initialiseView() { // loadingView = findViewById(R.id.view_loading); // emptyView = (TextView) findViewById(R.id.txt_empty); // errorView = (TextView) findViewById(R.id.txt_error); // recyclerView = (RecyclerView) findViewById(R.id.view_recycler); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // } // // private void initialisePresenter(@Nullable Bundle savedInstanceState) { // presenter = new Presenter(repository, this, new RxBinder(), logger); // } // // @Override // public void inject(@NonNull ApplicationComponent component) { // component.inject(this); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onStart(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onStop(); // } // // @Override // public void setViewState(@NonNull ViewState viewState) { // if (viewState instanceof ViewState.Loading) { // setLoading((ViewState.Loading) viewState); // } else if (viewState instanceof ViewState.Loaded) { // setLoaded((ViewState.Loaded) viewState); // } else if (viewState instanceof ViewState.Empty) { // setEmpty((ViewState.Empty) viewState); // } else if (viewState instanceof ViewState.Error) { // setError((ViewState.Error) viewState); // } // } // // private void setLoading(@NonNull ViewState.Loading viewState) { // hideViews(); // loadingView.setVisibility(View.VISIBLE); // } // // private void setLoaded(@NonNull ViewState.Loaded viewState) { // hideViews(); // recyclerView.setVisibility(View.VISIBLE); // recyclerView.setAdapter(new AnimalsAdapter(viewState.getAnimals())); // } // // private void setEmpty(@NonNull ViewState.Empty viewState) { // hideViews(); // emptyView.setText(getResources().getString(viewState.getMessage())); // emptyView.setVisibility(View.VISIBLE); // } // // private void setError(@NonNull ViewState.Error viewState) { // hideViews(); // errorView.setText(getResources().getString(viewState.getMessage())); // errorView.setVisibility(View.VISIBLE); // } // // private void hideViews() { // loadingView.setVisibility(View.GONE); // emptyView.setVisibility(View.GONE); // errorView.setVisibility(View.GONE); // recyclerView.setVisibility(View.GONE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // }
import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.presentation.HomeActivity; import au.com.dius.pactconsumer.util.Logger; import dagger.Component;
package au.com.dius.pactconsumer.app.di; @Singleton @Component(modules = {ApplicationModule.class, NetworkModule.class}) public interface ApplicationComponent { @NonNull Context getContext(); @NonNull Logger getLogger(); @NonNull
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/HomeActivity.java // public class HomeActivity extends PactActivity implements Contract.View { // // @Inject // Repository repository; // // @Inject // Logger logger; // // private Presenter presenter; // // private View loadingView; // private TextView emptyView; // private TextView errorView; // private RecyclerView recyclerView; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animals); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // initialiseView(); // initialisePresenter(savedInstanceState); // } // // private void initialiseView() { // loadingView = findViewById(R.id.view_loading); // emptyView = (TextView) findViewById(R.id.txt_empty); // errorView = (TextView) findViewById(R.id.txt_error); // recyclerView = (RecyclerView) findViewById(R.id.view_recycler); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // } // // private void initialisePresenter(@Nullable Bundle savedInstanceState) { // presenter = new Presenter(repository, this, new RxBinder(), logger); // } // // @Override // public void inject(@NonNull ApplicationComponent component) { // component.inject(this); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onStart(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onStop(); // } // // @Override // public void setViewState(@NonNull ViewState viewState) { // if (viewState instanceof ViewState.Loading) { // setLoading((ViewState.Loading) viewState); // } else if (viewState instanceof ViewState.Loaded) { // setLoaded((ViewState.Loaded) viewState); // } else if (viewState instanceof ViewState.Empty) { // setEmpty((ViewState.Empty) viewState); // } else if (viewState instanceof ViewState.Error) { // setError((ViewState.Error) viewState); // } // } // // private void setLoading(@NonNull ViewState.Loading viewState) { // hideViews(); // loadingView.setVisibility(View.VISIBLE); // } // // private void setLoaded(@NonNull ViewState.Loaded viewState) { // hideViews(); // recyclerView.setVisibility(View.VISIBLE); // recyclerView.setAdapter(new AnimalsAdapter(viewState.getAnimals())); // } // // private void setEmpty(@NonNull ViewState.Empty viewState) { // hideViews(); // emptyView.setText(getResources().getString(viewState.getMessage())); // emptyView.setVisibility(View.VISIBLE); // } // // private void setError(@NonNull ViewState.Error viewState) { // hideViews(); // errorView.setText(getResources().getString(viewState.getMessage())); // errorView.setVisibility(View.VISIBLE); // } // // private void hideViews() { // loadingView.setVisibility(View.GONE); // emptyView.setVisibility(View.GONE); // errorView.setVisibility(View.GONE); // recyclerView.setVisibility(View.GONE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.presentation.HomeActivity; import au.com.dius.pactconsumer.util.Logger; import dagger.Component; package au.com.dius.pactconsumer.app.di; @Singleton @Component(modules = {ApplicationModule.class, NetworkModule.class}) public interface ApplicationComponent { @NonNull Context getContext(); @NonNull Logger getLogger(); @NonNull
Repository getRepository();
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/HomeActivity.java // public class HomeActivity extends PactActivity implements Contract.View { // // @Inject // Repository repository; // // @Inject // Logger logger; // // private Presenter presenter; // // private View loadingView; // private TextView emptyView; // private TextView errorView; // private RecyclerView recyclerView; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animals); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // initialiseView(); // initialisePresenter(savedInstanceState); // } // // private void initialiseView() { // loadingView = findViewById(R.id.view_loading); // emptyView = (TextView) findViewById(R.id.txt_empty); // errorView = (TextView) findViewById(R.id.txt_error); // recyclerView = (RecyclerView) findViewById(R.id.view_recycler); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // } // // private void initialisePresenter(@Nullable Bundle savedInstanceState) { // presenter = new Presenter(repository, this, new RxBinder(), logger); // } // // @Override // public void inject(@NonNull ApplicationComponent component) { // component.inject(this); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onStart(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onStop(); // } // // @Override // public void setViewState(@NonNull ViewState viewState) { // if (viewState instanceof ViewState.Loading) { // setLoading((ViewState.Loading) viewState); // } else if (viewState instanceof ViewState.Loaded) { // setLoaded((ViewState.Loaded) viewState); // } else if (viewState instanceof ViewState.Empty) { // setEmpty((ViewState.Empty) viewState); // } else if (viewState instanceof ViewState.Error) { // setError((ViewState.Error) viewState); // } // } // // private void setLoading(@NonNull ViewState.Loading viewState) { // hideViews(); // loadingView.setVisibility(View.VISIBLE); // } // // private void setLoaded(@NonNull ViewState.Loaded viewState) { // hideViews(); // recyclerView.setVisibility(View.VISIBLE); // recyclerView.setAdapter(new AnimalsAdapter(viewState.getAnimals())); // } // // private void setEmpty(@NonNull ViewState.Empty viewState) { // hideViews(); // emptyView.setText(getResources().getString(viewState.getMessage())); // emptyView.setVisibility(View.VISIBLE); // } // // private void setError(@NonNull ViewState.Error viewState) { // hideViews(); // errorView.setText(getResources().getString(viewState.getMessage())); // errorView.setVisibility(View.VISIBLE); // } // // private void hideViews() { // loadingView.setVisibility(View.GONE); // emptyView.setVisibility(View.GONE); // errorView.setVisibility(View.GONE); // recyclerView.setVisibility(View.GONE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // }
import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.presentation.HomeActivity; import au.com.dius.pactconsumer.util.Logger; import dagger.Component;
package au.com.dius.pactconsumer.app.di; @Singleton @Component(modules = {ApplicationModule.class, NetworkModule.class}) public interface ApplicationComponent { @NonNull Context getContext(); @NonNull Logger getLogger(); @NonNull Repository getRepository();
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/presentation/HomeActivity.java // public class HomeActivity extends PactActivity implements Contract.View { // // @Inject // Repository repository; // // @Inject // Logger logger; // // private Presenter presenter; // // private View loadingView; // private TextView emptyView; // private TextView errorView; // private RecyclerView recyclerView; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_animals); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); // // initialiseView(); // initialisePresenter(savedInstanceState); // } // // private void initialiseView() { // loadingView = findViewById(R.id.view_loading); // emptyView = (TextView) findViewById(R.id.txt_empty); // errorView = (TextView) findViewById(R.id.txt_error); // recyclerView = (RecyclerView) findViewById(R.id.view_recycler); // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // } // // private void initialisePresenter(@Nullable Bundle savedInstanceState) { // presenter = new Presenter(repository, this, new RxBinder(), logger); // } // // @Override // public void inject(@NonNull ApplicationComponent component) { // component.inject(this); // } // // @Override // protected void onResume() { // super.onResume(); // presenter.onStart(); // } // // @Override // protected void onPause() { // super.onPause(); // presenter.onStop(); // } // // @Override // public void setViewState(@NonNull ViewState viewState) { // if (viewState instanceof ViewState.Loading) { // setLoading((ViewState.Loading) viewState); // } else if (viewState instanceof ViewState.Loaded) { // setLoaded((ViewState.Loaded) viewState); // } else if (viewState instanceof ViewState.Empty) { // setEmpty((ViewState.Empty) viewState); // } else if (viewState instanceof ViewState.Error) { // setError((ViewState.Error) viewState); // } // } // // private void setLoading(@NonNull ViewState.Loading viewState) { // hideViews(); // loadingView.setVisibility(View.VISIBLE); // } // // private void setLoaded(@NonNull ViewState.Loaded viewState) { // hideViews(); // recyclerView.setVisibility(View.VISIBLE); // recyclerView.setAdapter(new AnimalsAdapter(viewState.getAnimals())); // } // // private void setEmpty(@NonNull ViewState.Empty viewState) { // hideViews(); // emptyView.setText(getResources().getString(viewState.getMessage())); // emptyView.setVisibility(View.VISIBLE); // } // // private void setError(@NonNull ViewState.Error viewState) { // hideViews(); // errorView.setText(getResources().getString(viewState.getMessage())); // errorView.setVisibility(View.VISIBLE); // } // // private void hideViews() { // loadingView.setVisibility(View.GONE); // emptyView.setVisibility(View.GONE); // errorView.setVisibility(View.GONE); // recyclerView.setVisibility(View.GONE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.presentation.HomeActivity; import au.com.dius.pactconsumer.util.Logger; import dagger.Component; package au.com.dius.pactconsumer.app.di; @Singleton @Component(modules = {ApplicationModule.class, NetworkModule.class}) public interface ApplicationComponent { @NonNull Context getContext(); @NonNull Logger getLogger(); @NonNull Repository getRepository();
void inject(HomeActivity homeActivity);
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // }
import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import com.squareup.moshi.FromJson; import com.squareup.moshi.Moshi; import com.squareup.moshi.ToJson; import org.joda.time.DateTime; import java.io.File; import javax.inject.Singleton; import au.com.dius.pactconsumer.BuildConfig; import au.com.dius.pactconsumer.util.DateHelper; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.moshi.MoshiConverterFactory;
@VisibleForTesting public Retrofit getRetrofit(@NonNull Context context, @NonNull String baseUrl) { return new Retrofit.Builder() .baseUrl(baseUrl) .client(getOkHttpClient(context)) .addConverterFactory(MoshiConverterFactory.create(getMoshi())) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } private OkHttpClient getOkHttpClient(@NonNull Context context) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); if (BuildConfig.DEBUG) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addNetworkInterceptor(interceptor); } builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); return builder.build(); } private Moshi getMoshi() { return new Moshi.Builder().add(new DateTimeAdapter()).build(); } public static class DateTimeAdapter { @ToJson public String toJson(DateTime dateTime) {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/NetworkModule.java import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import com.squareup.moshi.FromJson; import com.squareup.moshi.Moshi; import com.squareup.moshi.ToJson; import org.joda.time.DateTime; import java.io.File; import javax.inject.Singleton; import au.com.dius.pactconsumer.BuildConfig; import au.com.dius.pactconsumer.util.DateHelper; import dagger.Module; import dagger.Provides; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.moshi.MoshiConverterFactory; @VisibleForTesting public Retrofit getRetrofit(@NonNull Context context, @NonNull String baseUrl) { return new Retrofit.Builder() .baseUrl(baseUrl) .client(getOkHttpClient(context)) .addConverterFactory(MoshiConverterFactory.create(getMoshi())) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } private OkHttpClient getOkHttpClient(@NonNull Context context) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); if (BuildConfig.DEBUG) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addNetworkInterceptor(interceptor); } builder.cache(new Cache(new File(context.getCacheDir(), "okhttp_cache"), 10 * 1024 * 1024)); return builder.build(); } private Moshi getMoshi() { return new Moshi.Builder().add(new DateTimeAdapter()).build(); } public static class DateTimeAdapter { @ToJson public String toJson(DateTime dateTime) {
return DateHelper.toString(dateTime);
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/domain/ViewState.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // }
import android.support.annotation.NonNull; import android.support.annotation.StringRes; import java.util.List; import au.com.dius.pactconsumer.data.model.Animal;
package au.com.dius.pactconsumer.domain; public class ViewState { public static class Loaded extends ViewState { @NonNull
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/domain/ViewState.java import android.support.annotation.NonNull; import android.support.annotation.StringRes; import java.util.List; import au.com.dius.pactconsumer.data.model.Animal; package au.com.dius.pactconsumer.domain; public class ViewState { public static class Loaded extends ViewState { @NonNull
private final List<Animal> animals;
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationModule.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java // @Singleton // public class Service implements Repository { // // private static final int BAD_REQUEST = 400; // private static final int NOT_FOUND = 404; // // public interface Api { // @GET("provider.json") // Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); // } // // private final Api api; // // @Inject // public Service(@NonNull Api api) { // this.api = api; // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // try { // return api.loadProviderJson(DateHelper.encodeDate(dateTime)) // .onErrorResumeNext(this::mapError); // } catch (UnsupportedEncodingException e) { // return Single.error(e); // } // } // // private Single<ServiceResponse> mapError(Throwable throwable) { // if (!(throwable instanceof HttpException)) { // return Single.error(throwable); // } // // HttpException exception = (HttpException) throwable; // if (exception.code() == NOT_FOUND) { // return Single.just(new ServiceResponse(null, Collections.emptyList())); // } else if (exception.code() == BAD_REQUEST) { // return Single.error(new BadRequestException(exception.message(), exception)); // } // return Single.error(throwable); // } // }
import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.Service; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit;
package au.com.dius.pactconsumer.app.di; @Module public class ApplicationModule { private final Context context; public ApplicationModule(@NonNull Context context) { this.context = context; } @Singleton @Provides @NonNull public Context getContext() { return context; } @Singleton @Provides @NonNull
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java // @Singleton // public class Service implements Repository { // // private static final int BAD_REQUEST = 400; // private static final int NOT_FOUND = 404; // // public interface Api { // @GET("provider.json") // Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); // } // // private final Api api; // // @Inject // public Service(@NonNull Api api) { // this.api = api; // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // try { // return api.loadProviderJson(DateHelper.encodeDate(dateTime)) // .onErrorResumeNext(this::mapError); // } catch (UnsupportedEncodingException e) { // return Single.error(e); // } // } // // private Single<ServiceResponse> mapError(Throwable throwable) { // if (!(throwable instanceof HttpException)) { // return Single.error(throwable); // } // // HttpException exception = (HttpException) throwable; // if (exception.code() == NOT_FOUND) { // return Single.just(new ServiceResponse(null, Collections.emptyList())); // } else if (exception.code() == BAD_REQUEST) { // return Single.error(new BadRequestException(exception.message(), exception)); // } // return Single.error(throwable); // } // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationModule.java import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.Service; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit; package au.com.dius.pactconsumer.app.di; @Module public class ApplicationModule { private final Context context; public ApplicationModule(@NonNull Context context) { this.context = context; } @Singleton @Provides @NonNull public Context getContext() { return context; } @Singleton @Provides @NonNull
public Repository getRepository(@NonNull Retrofit retrofit) {
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationModule.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java // @Singleton // public class Service implements Repository { // // private static final int BAD_REQUEST = 400; // private static final int NOT_FOUND = 404; // // public interface Api { // @GET("provider.json") // Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); // } // // private final Api api; // // @Inject // public Service(@NonNull Api api) { // this.api = api; // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // try { // return api.loadProviderJson(DateHelper.encodeDate(dateTime)) // .onErrorResumeNext(this::mapError); // } catch (UnsupportedEncodingException e) { // return Single.error(e); // } // } // // private Single<ServiceResponse> mapError(Throwable throwable) { // if (!(throwable instanceof HttpException)) { // return Single.error(throwable); // } // // HttpException exception = (HttpException) throwable; // if (exception.code() == NOT_FOUND) { // return Single.just(new ServiceResponse(null, Collections.emptyList())); // } else if (exception.code() == BAD_REQUEST) { // return Single.error(new BadRequestException(exception.message(), exception)); // } // return Single.error(throwable); // } // }
import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.Service; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit;
package au.com.dius.pactconsumer.app.di; @Module public class ApplicationModule { private final Context context; public ApplicationModule(@NonNull Context context) { this.context = context; } @Singleton @Provides @NonNull public Context getContext() { return context; } @Singleton @Provides @NonNull public Repository getRepository(@NonNull Retrofit retrofit) {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java // @Singleton // public class Service implements Repository { // // private static final int BAD_REQUEST = 400; // private static final int NOT_FOUND = 404; // // public interface Api { // @GET("provider.json") // Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); // } // // private final Api api; // // @Inject // public Service(@NonNull Api api) { // this.api = api; // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // try { // return api.loadProviderJson(DateHelper.encodeDate(dateTime)) // .onErrorResumeNext(this::mapError); // } catch (UnsupportedEncodingException e) { // return Single.error(e); // } // } // // private Single<ServiceResponse> mapError(Throwable throwable) { // if (!(throwable instanceof HttpException)) { // return Single.error(throwable); // } // // HttpException exception = (HttpException) throwable; // if (exception.code() == NOT_FOUND) { // return Single.just(new ServiceResponse(null, Collections.emptyList())); // } else if (exception.code() == BAD_REQUEST) { // return Single.error(new BadRequestException(exception.message(), exception)); // } // return Single.error(throwable); // } // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationModule.java import android.content.Context; import android.support.annotation.NonNull; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.Service; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit; package au.com.dius.pactconsumer.app.di; @Module public class ApplicationModule { private final Context context; public ApplicationModule(@NonNull Context context) { this.context = context; } @Singleton @Provides @NonNull public Context getContext() { return context; } @Singleton @Provides @NonNull public Repository getRepository(@NonNull Retrofit retrofit) {
return new Service(retrofit.create(Service.Api.class));
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/domain/PresenterTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java // @Singleton // public class FakeService implements Repository { // // public static final ServiceResponse RESPONSE; // // static { // RESPONSE = new ServiceResponse( // DateTime.now(), // Arrays.asList( // Animal.create("Doggy", "dog"), // Animal.create("Cathy", "cat"), // Animal.create("Birdy", "bird") // ) // ); // } // // @Inject // public FakeService() { // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // return Single.just(RESPONSE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/ServiceException.java // public class ServiceException extends RuntimeException { // // public ServiceException() { } // // public ServiceException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/util/TestRxBinder.java // public class TestRxBinder extends RxBinder { // // @Override // public <T> void bind(Observable<T> observable, // Consumer<T> onNext, // Consumer<Exception> onError, // Action onComplete) { // observable // .subscribeWith(new DisposableObserver<T>() { // // @Override // public void onNext(T o) { // try { // onNext.accept(o); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onError(Throwable thr) { // if (!(thr instanceof Exception)) { // Exceptions.throwIfFatal(thr); // return; // } // // try { // onError.accept((Exception) thr); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onComplete() { // try { // onComplete.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } // }
import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.Collections; import au.com.dius.pactconsumer.R; import au.com.dius.pactconsumer.data.FakeService; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.exceptions.ServiceException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.Logger; import au.com.dius.pactconsumer.util.TestRxBinder; import io.reactivex.Single; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package au.com.dius.pactconsumer.domain; public class PresenterTest { Repository repository; Contract.View view; Presenter presenter; @Before public void setUp() { repository = mock(Repository.class); view = mock(Contract.View.class);
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java // @Singleton // public class FakeService implements Repository { // // public static final ServiceResponse RESPONSE; // // static { // RESPONSE = new ServiceResponse( // DateTime.now(), // Arrays.asList( // Animal.create("Doggy", "dog"), // Animal.create("Cathy", "cat"), // Animal.create("Birdy", "bird") // ) // ); // } // // @Inject // public FakeService() { // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // return Single.just(RESPONSE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/ServiceException.java // public class ServiceException extends RuntimeException { // // public ServiceException() { } // // public ServiceException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/util/TestRxBinder.java // public class TestRxBinder extends RxBinder { // // @Override // public <T> void bind(Observable<T> observable, // Consumer<T> onNext, // Consumer<Exception> onError, // Action onComplete) { // observable // .subscribeWith(new DisposableObserver<T>() { // // @Override // public void onNext(T o) { // try { // onNext.accept(o); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onError(Throwable thr) { // if (!(thr instanceof Exception)) { // Exceptions.throwIfFatal(thr); // return; // } // // try { // onError.accept((Exception) thr); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onComplete() { // try { // onComplete.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/domain/PresenterTest.java import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.Collections; import au.com.dius.pactconsumer.R; import au.com.dius.pactconsumer.data.FakeService; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.exceptions.ServiceException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.Logger; import au.com.dius.pactconsumer.util.TestRxBinder; import io.reactivex.Single; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package au.com.dius.pactconsumer.domain; public class PresenterTest { Repository repository; Contract.View view; Presenter presenter; @Before public void setUp() { repository = mock(Repository.class); view = mock(Contract.View.class);
presenter = new Presenter(repository, view, new TestRxBinder(), mock(Logger.class));
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/domain/PresenterTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java // @Singleton // public class FakeService implements Repository { // // public static final ServiceResponse RESPONSE; // // static { // RESPONSE = new ServiceResponse( // DateTime.now(), // Arrays.asList( // Animal.create("Doggy", "dog"), // Animal.create("Cathy", "cat"), // Animal.create("Birdy", "bird") // ) // ); // } // // @Inject // public FakeService() { // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // return Single.just(RESPONSE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/ServiceException.java // public class ServiceException extends RuntimeException { // // public ServiceException() { } // // public ServiceException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/util/TestRxBinder.java // public class TestRxBinder extends RxBinder { // // @Override // public <T> void bind(Observable<T> observable, // Consumer<T> onNext, // Consumer<Exception> onError, // Action onComplete) { // observable // .subscribeWith(new DisposableObserver<T>() { // // @Override // public void onNext(T o) { // try { // onNext.accept(o); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onError(Throwable thr) { // if (!(thr instanceof Exception)) { // Exceptions.throwIfFatal(thr); // return; // } // // try { // onError.accept((Exception) thr); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onComplete() { // try { // onComplete.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } // }
import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.Collections; import au.com.dius.pactconsumer.R; import au.com.dius.pactconsumer.data.FakeService; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.exceptions.ServiceException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.Logger; import au.com.dius.pactconsumer.util.TestRxBinder; import io.reactivex.Single; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package au.com.dius.pactconsumer.domain; public class PresenterTest { Repository repository; Contract.View view; Presenter presenter; @Before public void setUp() { repository = mock(Repository.class); view = mock(Contract.View.class);
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java // @Singleton // public class FakeService implements Repository { // // public static final ServiceResponse RESPONSE; // // static { // RESPONSE = new ServiceResponse( // DateTime.now(), // Arrays.asList( // Animal.create("Doggy", "dog"), // Animal.create("Cathy", "cat"), // Animal.create("Birdy", "bird") // ) // ); // } // // @Inject // public FakeService() { // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // return Single.just(RESPONSE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/ServiceException.java // public class ServiceException extends RuntimeException { // // public ServiceException() { } // // public ServiceException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/util/TestRxBinder.java // public class TestRxBinder extends RxBinder { // // @Override // public <T> void bind(Observable<T> observable, // Consumer<T> onNext, // Consumer<Exception> onError, // Action onComplete) { // observable // .subscribeWith(new DisposableObserver<T>() { // // @Override // public void onNext(T o) { // try { // onNext.accept(o); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onError(Throwable thr) { // if (!(thr instanceof Exception)) { // Exceptions.throwIfFatal(thr); // return; // } // // try { // onError.accept((Exception) thr); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onComplete() { // try { // onComplete.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/domain/PresenterTest.java import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.Collections; import au.com.dius.pactconsumer.R; import au.com.dius.pactconsumer.data.FakeService; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.exceptions.ServiceException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.Logger; import au.com.dius.pactconsumer.util.TestRxBinder; import io.reactivex.Single; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package au.com.dius.pactconsumer.domain; public class PresenterTest { Repository repository; Contract.View view; Presenter presenter; @Before public void setUp() { repository = mock(Repository.class); view = mock(Contract.View.class);
presenter = new Presenter(repository, view, new TestRxBinder(), mock(Logger.class));
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/domain/PresenterTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java // @Singleton // public class FakeService implements Repository { // // public static final ServiceResponse RESPONSE; // // static { // RESPONSE = new ServiceResponse( // DateTime.now(), // Arrays.asList( // Animal.create("Doggy", "dog"), // Animal.create("Cathy", "cat"), // Animal.create("Birdy", "bird") // ) // ); // } // // @Inject // public FakeService() { // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // return Single.just(RESPONSE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/ServiceException.java // public class ServiceException extends RuntimeException { // // public ServiceException() { } // // public ServiceException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/util/TestRxBinder.java // public class TestRxBinder extends RxBinder { // // @Override // public <T> void bind(Observable<T> observable, // Consumer<T> onNext, // Consumer<Exception> onError, // Action onComplete) { // observable // .subscribeWith(new DisposableObserver<T>() { // // @Override // public void onNext(T o) { // try { // onNext.accept(o); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onError(Throwable thr) { // if (!(thr instanceof Exception)) { // Exceptions.throwIfFatal(thr); // return; // } // // try { // onError.accept((Exception) thr); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onComplete() { // try { // onComplete.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } // }
import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.Collections; import au.com.dius.pactconsumer.R; import au.com.dius.pactconsumer.data.FakeService; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.exceptions.ServiceException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.Logger; import au.com.dius.pactconsumer.util.TestRxBinder; import io.reactivex.Single; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package au.com.dius.pactconsumer.domain; public class PresenterTest { Repository repository; Contract.View view; Presenter presenter; @Before public void setUp() { repository = mock(Repository.class); view = mock(Contract.View.class); presenter = new Presenter(repository, view, new TestRxBinder(), mock(Logger.class)); } @Test public void should_show_loaded_when_fetch_succeeds() { // given
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/FakeService.java // @Singleton // public class FakeService implements Repository { // // public static final ServiceResponse RESPONSE; // // static { // RESPONSE = new ServiceResponse( // DateTime.now(), // Arrays.asList( // Animal.create("Doggy", "dog"), // Animal.create("Cathy", "cat"), // Animal.create("Birdy", "bird") // ) // ); // } // // @Inject // public FakeService() { // } // // @NonNull // @Override // public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { // return Single.just(RESPONSE); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Repository.java // public interface Repository { // // @NonNull // Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime); // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/ServiceException.java // public class ServiceException extends RuntimeException { // // public ServiceException() { } // // public ServiceException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/Logger.java // @Singleton // public class Logger { // // @Inject // public Logger() { // } // // public void d(@NonNull String tag, @NonNull String msg) { // Log.d(tag, msg); // } // // public void e(@NonNull String tag, @NonNull String msg, @NonNull Throwable tr) { // Log.e(tag, msg, tr); // } // // } // // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/util/TestRxBinder.java // public class TestRxBinder extends RxBinder { // // @Override // public <T> void bind(Observable<T> observable, // Consumer<T> onNext, // Consumer<Exception> onError, // Action onComplete) { // observable // .subscribeWith(new DisposableObserver<T>() { // // @Override // public void onNext(T o) { // try { // onNext.accept(o); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onError(Throwable thr) { // if (!(thr instanceof Exception)) { // Exceptions.throwIfFatal(thr); // return; // } // // try { // onError.accept((Exception) thr); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public void onComplete() { // try { // onComplete.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/domain/PresenterTest.java import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.Collections; import au.com.dius.pactconsumer.R; import au.com.dius.pactconsumer.data.FakeService; import au.com.dius.pactconsumer.data.Repository; import au.com.dius.pactconsumer.data.exceptions.ServiceException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.Logger; import au.com.dius.pactconsumer.util.TestRxBinder; import io.reactivex.Single; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package au.com.dius.pactconsumer.domain; public class PresenterTest { Repository repository; Contract.View view; Presenter presenter; @Before public void setUp() { repository = mock(Repository.class); view = mock(Contract.View.class); presenter = new Presenter(repository, view, new TestRxBinder(), mock(Logger.class)); } @Test public void should_show_loaded_when_fetch_succeeds() { // given
when(repository.fetchResponse(any())).thenReturn(Single.just(FakeService.RESPONSE));
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/FakeServiceTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver;
package au.com.dius.pactconsumer.data; public class FakeServiceTest { FakeService service; @Before public void setUp() { service = new FakeService(); } @Test public void should_return_list_of_animals() { // when
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/FakeServiceTest.java import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.observers.TestObserver; package au.com.dius.pactconsumer.data; public class FakeServiceTest { FakeService service; @Before public void setUp() { service = new FakeService(); } @Test public void should_return_list_of_animals() { // when
TestObserver<ServiceResponse> observer = service.fetchResponse(DateTime.now()).test();
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactActivity.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java // @Singleton // @Component(modules = {ApplicationModule.class, NetworkModule.class}) // public interface ApplicationComponent { // // @NonNull // Context getContext(); // // @NonNull // Logger getLogger(); // // @NonNull // Repository getRepository(); // // void inject(HomeActivity homeActivity); // }
import android.app.Application; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import au.com.dius.pactconsumer.app.di.ApplicationComponent;
package au.com.dius.pactconsumer.app; public abstract class PactActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); inject(getPactApplication().getApplicationComponent()); }
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/di/ApplicationComponent.java // @Singleton // @Component(modules = {ApplicationModule.class, NetworkModule.class}) // public interface ApplicationComponent { // // @NonNull // Context getContext(); // // @NonNull // Logger getLogger(); // // @NonNull // Repository getRepository(); // // void inject(HomeActivity homeActivity); // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/app/PactActivity.java import android.app.Application; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import au.com.dius.pactconsumer.app.di.ApplicationComponent; package au.com.dius.pactconsumer.app; public abstract class PactActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); inject(getPactApplication().getApplicationComponent()); }
public abstract void inject(@NonNull ApplicationComponent component);
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import java.util.Collections; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single; import io.reactivex.observers.TestObserver; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package au.com.dius.pactconsumer.data; public class ServiceTest { Service.Api api; Service service; @Before public void setup() { api = mock(Service.Api.class); service = new Service(api); } @Test public void should_process_json_payload_from_provider() { // given
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceTest.java import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import java.util.Collections; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single; import io.reactivex.observers.TestObserver; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package au.com.dius.pactconsumer.data; public class ServiceTest { Service.Api api; Service service; @Before public void setup() { api = mock(Service.Api.class); service = new Service(api); } @Test public void should_process_json_payload_from_provider() { // given
ServiceResponse response = ServiceResponse.create(DateTime.now(), Collections.singletonList(Animal.create("Doggy", "dog")));
DiUS/pact-workshop-android
consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceTest.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // }
import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import java.util.Collections; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single; import io.reactivex.observers.TestObserver; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package au.com.dius.pactconsumer.data; public class ServiceTest { Service.Api api; Service service; @Before public void setup() { api = mock(Service.Api.class); service = new Service(api); } @Test public void should_process_json_payload_from_provider() { // given
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/Animal.java // public class Animal { // // @Json(name = "name") // private final String name; // // @Json(name = "image") // private final String image; // // public Animal(@NonNull String name, @NonNull String image) { // this.name = name; // this.image = image; // } // // @NonNull // public String getName() { // return name; // } // // @NonNull // public String getType() { // return image; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Animal animal = (Animal) o; // // if (name != null ? !name.equals(animal.name) : animal.name != null) return false; // return image != null ? image.equals(animal.image) : animal.image == null; // // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (image != null ? image.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "Animal{" + // "name='" + name + '\'' + // ", image='" + image + '\'' + // '}'; // } // // public static Animal create(@NonNull String name, @NonNull String image) { // return new Animal(name, image); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // Path: consumer/app/src/test/java/au/com/dius/pactconsumer/data/ServiceTest.java import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import java.util.Collections; import au.com.dius.pactconsumer.data.model.Animal; import au.com.dius.pactconsumer.data.model.ServiceResponse; import io.reactivex.Single; import io.reactivex.observers.TestObserver; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package au.com.dius.pactconsumer.data; public class ServiceTest { Service.Api api; Service service; @Before public void setup() { api = mock(Service.Api.class); service = new Service(api); } @Test public void should_process_json_payload_from_provider() { // given
ServiceResponse response = ServiceResponse.create(DateTime.now(), Collections.singletonList(Animal.create("Doggy", "dog")));
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // }
import android.support.annotation.NonNull; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import org.joda.time.DateTime; import java.io.UnsupportedEncodingException; import java.util.Collections; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query;
package au.com.dius.pactconsumer.data; @Singleton public class Service implements Repository { private static final int BAD_REQUEST = 400; private static final int NOT_FOUND = 404; public interface Api { @GET("provider.json")
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java import android.support.annotation.NonNull; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import org.joda.time.DateTime; import java.io.UnsupportedEncodingException; import java.util.Collections; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query; package au.com.dius.pactconsumer.data; @Singleton public class Service implements Repository { private static final int BAD_REQUEST = 400; private static final int NOT_FOUND = 404; public interface Api { @GET("provider.json")
Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate);
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // }
import android.support.annotation.NonNull; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import org.joda.time.DateTime; import java.io.UnsupportedEncodingException; import java.util.Collections; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query;
package au.com.dius.pactconsumer.data; @Singleton public class Service implements Repository { private static final int BAD_REQUEST = 400; private static final int NOT_FOUND = 404; public interface Api { @GET("provider.json") Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); } private final Api api; @Inject public Service(@NonNull Api api) { this.api = api; } @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { try {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java import android.support.annotation.NonNull; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import org.joda.time.DateTime; import java.io.UnsupportedEncodingException; import java.util.Collections; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query; package au.com.dius.pactconsumer.data; @Singleton public class Service implements Repository { private static final int BAD_REQUEST = 400; private static final int NOT_FOUND = 404; public interface Api { @GET("provider.json") Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); } private final Api api; @Inject public Service(@NonNull Api api) { this.api = api; } @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { try {
return api.loadProviderJson(DateHelper.encodeDate(dateTime))
DiUS/pact-workshop-android
consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // }
import android.support.annotation.NonNull; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import org.joda.time.DateTime; import java.io.UnsupportedEncodingException; import java.util.Collections; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query;
Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); } private final Api api; @Inject public Service(@NonNull Api api) { this.api = api; } @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { try { return api.loadProviderJson(DateHelper.encodeDate(dateTime)) .onErrorResumeNext(this::mapError); } catch (UnsupportedEncodingException e) { return Single.error(e); } } private Single<ServiceResponse> mapError(Throwable throwable) { if (!(throwable instanceof HttpException)) { return Single.error(throwable); } HttpException exception = (HttpException) throwable; if (exception.code() == NOT_FOUND) { return Single.just(new ServiceResponse(null, Collections.emptyList())); } else if (exception.code() == BAD_REQUEST) {
// Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/exceptions/BadRequestException.java // public class BadRequestException extends ServiceException { // // public BadRequestException() { } // // public BadRequestException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/model/ServiceResponse.java // public class ServiceResponse { // // @Json(name = "valid_date") // private final DateTime validDate; // // @Json(name = "animals") // private final List<Animal> animals; // // public ServiceResponse(@Nullable DateTime validDate, // @NonNull List<Animal> animals) { // this.validDate = validDate; // this.animals = animals; // } // // @Nullable // public DateTime getValidDate() { // return validDate; // } // // @NonNull // public List<Animal> getAnimals() { // return animals; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // ServiceResponse that = (ServiceResponse) o; // // long millis = validDate != null ? validDate.getMillis() : -1; // long thatMillis = that.validDate != null ? that.validDate.getMillis() : -1; // if (millis != thatMillis) // return false; // // return animals != null ? animals.equals(that.animals) : that.animals == null; // } // // @Override // public int hashCode() { // int result = validDate != null ? validDate.hashCode() : 0; // result = 31 * result + (animals != null ? animals.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "ServiceResponse{" + // "validDate=" + validDate + // ", animals=" + animals + // '}'; // } // // public static ServiceResponse create(@NonNull DateTime validDate, @NonNull List<Animal> animals) { // return new ServiceResponse(validDate, animals); // } // } // // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/util/DateHelper.java // public final class DateHelper { // // private DateHelper() { // } // // public static String encodeDate(@Nullable DateTime dateTime) throws UnsupportedEncodingException { // if (dateTime == null) { // return null; // } // return URLEncoder.encode(toString(dateTime), "UTF-8"); // } // // public static DateTime parse(@NonNull String value) { // return DateTime.parse(value); // } // // public static String toString(@NonNull DateTime value) { // return value.toString(); // } // // } // Path: consumer/app/src/main/java/au/com/dius/pactconsumer/data/Service.java import android.support.annotation.NonNull; import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import org.joda.time.DateTime; import java.io.UnsupportedEncodingException; import java.util.Collections; import javax.inject.Inject; import javax.inject.Singleton; import au.com.dius.pactconsumer.data.exceptions.BadRequestException; import au.com.dius.pactconsumer.data.model.ServiceResponse; import au.com.dius.pactconsumer.util.DateHelper; import io.reactivex.Single; import retrofit2.http.GET; import retrofit2.http.Query; Single<ServiceResponse> loadProviderJson(@Query("valid_date") String validDate); } private final Api api; @Inject public Service(@NonNull Api api) { this.api = api; } @NonNull @Override public Single<ServiceResponse> fetchResponse(@NonNull DateTime dateTime) { try { return api.loadProviderJson(DateHelper.encodeDate(dateTime)) .onErrorResumeNext(this::mapError); } catch (UnsupportedEncodingException e) { return Single.error(e); } } private Single<ServiceResponse> mapError(Throwable throwable) { if (!(throwable instanceof HttpException)) { return Single.error(throwable); } HttpException exception = (HttpException) throwable; if (exception.code() == NOT_FOUND) { return Single.just(new ServiceResponse(null, Collections.emptyList())); } else if (exception.code() == BAD_REQUEST) {
return Single.error(new BadRequestException(exception.message(), exception));
wso2/product-das
modules/migration/oaep-data-migration/src/main/java/org/wso2/migration/service/KeyStoreAndTrustStoreMigration.java
// Path: modules/migration/oaep-data-migration/src/main/java/org/wso2/migration/util/DataMigrationUtil.java // public class DataMigrationUtil { // // private DataMigrationUtil() { // // } // // public static boolean isNewlyEncrypted(String encryptedValue) throws DataMigrationException, CryptoException { // CryptoUtil cryptoUtil; // try { // cryptoUtil = CryptoUtil.getDefaultCryptoUtil(CarbonCoreDataHolder.getInstance(). // getServerConfigurationService(), // CarbonCoreDataHolder.getInstance().getRegistryService()); // } catch (Exception e) { // throw new DataMigrationException("Error while initializing cryptoUtil", e); // } // return cryptoUtil.base64DecodeAndIsSelfContainedCipherText(encryptedValue); // } // // public static String reEncryptByNewAlgorithm(String value) throws CryptoException { // byte[] decryptedValue = CryptoUtil.getDefaultCryptoUtil().base64DecodeAndDecrypt( // value, "RSA"); // return CryptoUtil.getDefaultCryptoUtil() // .encryptAndBase64Encode(decryptedValue); // } // }
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.CryptoException; import org.wso2.carbon.registry.core.Collection; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.migration.exception.DataMigrationException; import org.wso2.migration.internal.MigrationServiceDataHolder; import org.wso2.migration.util.DataMigrationUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID;
} } private void migrateKeyStorePasswordForTenant(int tenantId) throws RegistryException, CryptoException, DataMigrationException { Registry registry = registryService.getGovernanceSystemRegistry(tenantId); if (registry.resourceExists(KEYSTORE_RESOURCE_PATH)) { Collection keyStoreCollection = (Collection) registry.get(KEYSTORE_RESOURCE_PATH); for (String keyStorePath : keyStoreCollection.getChildren()) { updateRegistryProperties(registry, keyStorePath, new ArrayList<>(Arrays.asList(PASSWORD, PRIVATE_KEY_PASS))); } } } private void updateRegistryProperties(Registry registry, String resource, List<String> properties) throws RegistryException, CryptoException, DataMigrationException { String newValue; if (registry == null || StringUtils.isEmpty(resource) || CollectionUtils.isEmpty(properties)) { return; } if (registry.resourceExists(resource)) { try { registry.beginTransaction(); Resource resourceObj = registry.get(resource); for (String encryptedPropertyName : properties) { String oldValue = resourceObj.getProperty(encryptedPropertyName);
// Path: modules/migration/oaep-data-migration/src/main/java/org/wso2/migration/util/DataMigrationUtil.java // public class DataMigrationUtil { // // private DataMigrationUtil() { // // } // // public static boolean isNewlyEncrypted(String encryptedValue) throws DataMigrationException, CryptoException { // CryptoUtil cryptoUtil; // try { // cryptoUtil = CryptoUtil.getDefaultCryptoUtil(CarbonCoreDataHolder.getInstance(). // getServerConfigurationService(), // CarbonCoreDataHolder.getInstance().getRegistryService()); // } catch (Exception e) { // throw new DataMigrationException("Error while initializing cryptoUtil", e); // } // return cryptoUtil.base64DecodeAndIsSelfContainedCipherText(encryptedValue); // } // // public static String reEncryptByNewAlgorithm(String value) throws CryptoException { // byte[] decryptedValue = CryptoUtil.getDefaultCryptoUtil().base64DecodeAndDecrypt( // value, "RSA"); // return CryptoUtil.getDefaultCryptoUtil() // .encryptAndBase64Encode(decryptedValue); // } // } // Path: modules/migration/oaep-data-migration/src/main/java/org/wso2/migration/service/KeyStoreAndTrustStoreMigration.java import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.CryptoException; import org.wso2.carbon.registry.core.Collection; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.migration.exception.DataMigrationException; import org.wso2.migration.internal.MigrationServiceDataHolder; import org.wso2.migration.util.DataMigrationUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; import static org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID; } } private void migrateKeyStorePasswordForTenant(int tenantId) throws RegistryException, CryptoException, DataMigrationException { Registry registry = registryService.getGovernanceSystemRegistry(tenantId); if (registry.resourceExists(KEYSTORE_RESOURCE_PATH)) { Collection keyStoreCollection = (Collection) registry.get(KEYSTORE_RESOURCE_PATH); for (String keyStorePath : keyStoreCollection.getChildren()) { updateRegistryProperties(registry, keyStorePath, new ArrayList<>(Arrays.asList(PASSWORD, PRIVATE_KEY_PASS))); } } } private void updateRegistryProperties(Registry registry, String resource, List<String> properties) throws RegistryException, CryptoException, DataMigrationException { String newValue; if (registry == null || StringUtils.isEmpty(resource) || CollectionUtils.isEmpty(properties)) { return; } if (registry.resourceExists(resource)) { try { registry.beginTransaction(); Resource resourceObj = registry.get(resource); for (String encryptedPropertyName : properties) { String oldValue = resourceObj.getProperty(encryptedPropertyName);
if (oldValue != null && !DataMigrationUtil.isNewlyEncrypted(oldValue)) {