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
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/detail/NewsDetailContract.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // }
import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.MessageDetail;
package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsDetailContract { interface View extends BaseView<Presenter> { boolean isActive(); void showNewsDetail(MessageDetail detail); }
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/MessageDetail.java // public class MessageDetail { // private String body; // private String image_source; // private String title; // private String image; // private String share_url; // private List<String> recommenders; // private String ga_prefix; // private String type; // private String id; // // public String getBody() { // return body; // } // // public void setBody(String body) { // this.body = body; // } // // public String getImage_source() { // return image_source; // } // // public void setImage_source(String image_source) { // this.image_source = image_source; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public String getShare_url() { // return share_url; // } // // public void setShare_url(String share_url) { // this.share_url = share_url; // } // // public List<String> getRecommenders() { // return recommenders; // } // // public void setRecommenders(List<String> recommenders) { // this.recommenders = recommenders; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Override // public String toString() { // return "MessageDetail{" + // "body='" + body + '\'' + // ", image_source='" + image_source + '\'' + // ", title='" + title + '\'' + // ", image='" + image + '\'' + // ", share_url='" + share_url + '\'' + // ", recommenders=" + recommenders + // ", ga_prefix='" + ga_prefix + '\'' + // ", type='" + type + '\'' + // ", id='" + id + '\'' + // '}'; // } // } // Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailContract.java import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.MessageDetail; package com.guiying.module.news.detail; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsDetailContract { interface View extends BaseView<Presenter> { boolean isActive(); void showNewsDetail(MessageDetail detail); }
interface Presenter extends BasePresenter {
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/MyViewDelegate.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseFragment.java // @Keep // public abstract class BaseFragment extends Fragment { // // protected BaseActivity mActivity; // // @Override // public void onAttach(Context context) { // super.onAttach(context); // this.mActivity = (BaseActivity) context; // } // // // /** // * 获取宿主Activity // * // * @return BaseActivity // */ // protected BaseActivity getHoldingActivity() { // return mActivity; // } // // // /** // * 添加fragment // * // * @param fragment // * @param frameId // */ // protected void addFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().addFragment(fragment, frameId); // // } // // // /** // * 替换fragment // * // * @param fragment // * @param frameId // */ // protected void replaceFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().replaceFragment(fragment, frameId); // } // // // /** // * 隐藏fragment // * // * @param fragment // */ // protected void hideFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().hideFragment(fragment); // } // // // /** // * 显示fragment // * // * @param fragment // */ // protected void showFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().showFragment(fragment); // } // // // /** // * 移除Fragment // * // * @param fragment // */ // protected void removeFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().removeFragment(fragment); // // } // // // /** // * 弹出栈顶部的Fragment // */ // protected void popFragment() { // getHoldingActivity().popFragment(); // } // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/IViewDelegate.java // @Keep // public interface IViewDelegate { // // BaseFragment getFragment(String name); // // View getView(String name); // // }
import android.support.annotation.Keep; import android.view.View; import com.guiying.module.common.base.BaseFragment; import com.guiying.module.common.base.IViewDelegate;
package com.guiying.module.news; /** * <p>类说明</p> * * @author 张华洋 2018/1/4 22:16 * @version V2.8.3 * @name MyViewDelegate */ @Keep public class MyViewDelegate implements IViewDelegate { @Override
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseFragment.java // @Keep // public abstract class BaseFragment extends Fragment { // // protected BaseActivity mActivity; // // @Override // public void onAttach(Context context) { // super.onAttach(context); // this.mActivity = (BaseActivity) context; // } // // // /** // * 获取宿主Activity // * // * @return BaseActivity // */ // protected BaseActivity getHoldingActivity() { // return mActivity; // } // // // /** // * 添加fragment // * // * @param fragment // * @param frameId // */ // protected void addFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().addFragment(fragment, frameId); // // } // // // /** // * 替换fragment // * // * @param fragment // * @param frameId // */ // protected void replaceFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().replaceFragment(fragment, frameId); // } // // // /** // * 隐藏fragment // * // * @param fragment // */ // protected void hideFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().hideFragment(fragment); // } // // // /** // * 显示fragment // * // * @param fragment // */ // protected void showFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().showFragment(fragment); // } // // // /** // * 移除Fragment // * // * @param fragment // */ // protected void removeFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().removeFragment(fragment); // // } // // // /** // * 弹出栈顶部的Fragment // */ // protected void popFragment() { // getHoldingActivity().popFragment(); // } // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/IViewDelegate.java // @Keep // public interface IViewDelegate { // // BaseFragment getFragment(String name); // // View getView(String name); // // } // Path: module_news/src/main/java/com/guiying/module/news/MyViewDelegate.java import android.support.annotation.Keep; import android.view.View; import com.guiying.module.common.base.BaseFragment; import com.guiying.module.common.base.IViewDelegate; package com.guiying.module.news; /** * <p>类说明</p> * * @author 张华洋 2018/1/4 22:16 * @version V2.8.3 * @name MyViewDelegate */ @Keep public class MyViewDelegate implements IViewDelegate { @Override
public BaseFragment getFragment(String name) {
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/main/GirlsPresenter.java
// Path: module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java // public interface GirlsDataSource { // // interface LoadGirlsCallback { // // void onGirlsLoaded(GirlsParser girlsParser); // // void onDataNotAvailable(); // } // // void getGirls(int size, int page, LoadGirlsCallback callback); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java // public class RemoteGirlsDataSource implements GirlsDataSource { // // @Override // public void getGirls(int size, int page, final LoadGirlsCallback callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.GAN_HUO_API) // .url("福利/" + size + "/" + page) // .bodyType(DataType.JSON_OBJECT, GirlsParser.class) // .build(); // client.get(new OnResultListener<GirlsParser>() { // // @Override // public void onSuccess(GirlsParser result) { // callback.onGirlsLoaded(result); // } // // @Override // public void onError(int code, String message) { // callback.onDataNotAvailable(); // } // // @Override // public void onFailure(String message) { // callback.onDataNotAvailable(); // } // }); // } // // }
import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser; import com.guiying.module.girls.data.source.RemoteGirlsDataSource;
package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class GirlsPresenter implements GirlsContract.Presenter { private GirlsContract.View mView;
// Path: module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java // public interface GirlsDataSource { // // interface LoadGirlsCallback { // // void onGirlsLoaded(GirlsParser girlsParser); // // void onDataNotAvailable(); // } // // void getGirls(int size, int page, LoadGirlsCallback callback); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java // public class RemoteGirlsDataSource implements GirlsDataSource { // // @Override // public void getGirls(int size, int page, final LoadGirlsCallback callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.GAN_HUO_API) // .url("福利/" + size + "/" + page) // .bodyType(DataType.JSON_OBJECT, GirlsParser.class) // .build(); // client.get(new OnResultListener<GirlsParser>() { // // @Override // public void onSuccess(GirlsParser result) { // callback.onGirlsLoaded(result); // } // // @Override // public void onError(int code, String message) { // callback.onDataNotAvailable(); // } // // @Override // public void onFailure(String message) { // callback.onDataNotAvailable(); // } // }); // } // // } // Path: module_girls/src/main/java/com/guiying/module/girls/main/GirlsPresenter.java import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser; import com.guiying.module.girls.data.source.RemoteGirlsDataSource; package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class GirlsPresenter implements GirlsContract.Presenter { private GirlsContract.View mView;
private GirlsDataSource mDataSource;
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/main/GirlsPresenter.java
// Path: module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java // public interface GirlsDataSource { // // interface LoadGirlsCallback { // // void onGirlsLoaded(GirlsParser girlsParser); // // void onDataNotAvailable(); // } // // void getGirls(int size, int page, LoadGirlsCallback callback); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java // public class RemoteGirlsDataSource implements GirlsDataSource { // // @Override // public void getGirls(int size, int page, final LoadGirlsCallback callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.GAN_HUO_API) // .url("福利/" + size + "/" + page) // .bodyType(DataType.JSON_OBJECT, GirlsParser.class) // .build(); // client.get(new OnResultListener<GirlsParser>() { // // @Override // public void onSuccess(GirlsParser result) { // callback.onGirlsLoaded(result); // } // // @Override // public void onError(int code, String message) { // callback.onDataNotAvailable(); // } // // @Override // public void onFailure(String message) { // callback.onDataNotAvailable(); // } // }); // } // // }
import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser; import com.guiying.module.girls.data.source.RemoteGirlsDataSource;
package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class GirlsPresenter implements GirlsContract.Presenter { private GirlsContract.View mView; private GirlsDataSource mDataSource; public GirlsPresenter(GirlsContract.View view) { mView = view; mView.setPresenter(this);
// Path: module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java // public interface GirlsDataSource { // // interface LoadGirlsCallback { // // void onGirlsLoaded(GirlsParser girlsParser); // // void onDataNotAvailable(); // } // // void getGirls(int size, int page, LoadGirlsCallback callback); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java // public class RemoteGirlsDataSource implements GirlsDataSource { // // @Override // public void getGirls(int size, int page, final LoadGirlsCallback callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.GAN_HUO_API) // .url("福利/" + size + "/" + page) // .bodyType(DataType.JSON_OBJECT, GirlsParser.class) // .build(); // client.get(new OnResultListener<GirlsParser>() { // // @Override // public void onSuccess(GirlsParser result) { // callback.onGirlsLoaded(result); // } // // @Override // public void onError(int code, String message) { // callback.onDataNotAvailable(); // } // // @Override // public void onFailure(String message) { // callback.onDataNotAvailable(); // } // }); // } // // } // Path: module_girls/src/main/java/com/guiying/module/girls/main/GirlsPresenter.java import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser; import com.guiying.module.girls.data.source.RemoteGirlsDataSource; package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class GirlsPresenter implements GirlsContract.Presenter { private GirlsContract.View mView; private GirlsDataSource mDataSource; public GirlsPresenter(GirlsContract.View view) { mView = view; mView.setPresenter(this);
mDataSource = new RemoteGirlsDataSource();
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/main/GirlsPresenter.java
// Path: module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java // public interface GirlsDataSource { // // interface LoadGirlsCallback { // // void onGirlsLoaded(GirlsParser girlsParser); // // void onDataNotAvailable(); // } // // void getGirls(int size, int page, LoadGirlsCallback callback); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java // public class RemoteGirlsDataSource implements GirlsDataSource { // // @Override // public void getGirls(int size, int page, final LoadGirlsCallback callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.GAN_HUO_API) // .url("福利/" + size + "/" + page) // .bodyType(DataType.JSON_OBJECT, GirlsParser.class) // .build(); // client.get(new OnResultListener<GirlsParser>() { // // @Override // public void onSuccess(GirlsParser result) { // callback.onGirlsLoaded(result); // } // // @Override // public void onError(int code, String message) { // callback.onDataNotAvailable(); // } // // @Override // public void onFailure(String message) { // callback.onDataNotAvailable(); // } // }); // } // // }
import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser; import com.guiying.module.girls.data.source.RemoteGirlsDataSource;
package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class GirlsPresenter implements GirlsContract.Presenter { private GirlsContract.View mView; private GirlsDataSource mDataSource; public GirlsPresenter(GirlsContract.View view) { mView = view; mView.setPresenter(this); mDataSource = new RemoteGirlsDataSource(); } @Override public void getGirls(int size, int page, final boolean isRefresh) { mDataSource.getGirls(size, page, new GirlsDataSource.LoadGirlsCallback() { @Override
// Path: module_girls/src/main/java/com/guiying/module/girls/data/GirlsDataSource.java // public interface GirlsDataSource { // // interface LoadGirlsCallback { // // void onGirlsLoaded(GirlsParser girlsParser); // // void onDataNotAvailable(); // } // // void getGirls(int size, int page, LoadGirlsCallback callback); // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/GirlsParser.java // public class GirlsParser { // // /** // * error : false // * results : [{"_id":"5771d5eb421aa931ddcc50d6","createdAt":"2016-06-28T09:42:03.761Z","desc":"Dagger2图文完全教程","publishedAt":"2016-06-28T11:33:25.276Z","source":"web","type":"Android","url":"https://github.com/luxiaoming/dagger2Demo","used":true,"who":"代码GG陆晓明"},{"_id":"5771c9ca421aa931ca5a7e59","createdAt":"2016-06-28T08:50:18.731Z","desc":"Android Design 设计模板","publishedAt":"2016-06-28T11:33:25.276Z","source":"chrome","type":"Android","url":"https://github.com/andreasschrade/android-design-template","used":true,"who":"代码家"}] // */ // // private boolean error; // /** // * _id : 5771d5eb421aa931ddcc50d6 // * createdAt : 2016-06-28T09:42:03.761Z // * desc : Dagger2图文完全教程 // * publishedAt : 2016-06-28T11:33:25.276Z // * source : web // * type : Android // * url : https://github.com/luxiaoming/dagger2Demo // * used : true // * who : 代码GG陆晓明 // */ // // private List<Girls> results; // // public void setError(boolean error) { // this.error = error; // } // // public void setResults(List<Girls> results) { // this.results = results; // } // // public boolean isError() { // return error; // } // // public List<Girls> getResults() { // return results; // } // // // } // // Path: module_girls/src/main/java/com/guiying/module/girls/data/source/RemoteGirlsDataSource.java // public class RemoteGirlsDataSource implements GirlsDataSource { // // @Override // public void getGirls(int size, int page, final LoadGirlsCallback callback) { // HttpClient client = new HttpClient.Builder() // .baseUrl(Constants.GAN_HUO_API) // .url("福利/" + size + "/" + page) // .bodyType(DataType.JSON_OBJECT, GirlsParser.class) // .build(); // client.get(new OnResultListener<GirlsParser>() { // // @Override // public void onSuccess(GirlsParser result) { // callback.onGirlsLoaded(result); // } // // @Override // public void onError(int code, String message) { // callback.onDataNotAvailable(); // } // // @Override // public void onFailure(String message) { // callback.onDataNotAvailable(); // } // }); // } // // } // Path: module_girls/src/main/java/com/guiying/module/girls/main/GirlsPresenter.java import com.guiying.module.girls.data.GirlsDataSource; import com.guiying.module.girls.data.bean.GirlsParser; import com.guiying.module.girls.data.source.RemoteGirlsDataSource; package com.guiying.module.girls.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name GirlsPresenter */ public class GirlsPresenter implements GirlsContract.Presenter { private GirlsContract.View mView; private GirlsDataSource mDataSource; public GirlsPresenter(GirlsContract.View view) { mView = view; mView.setPresenter(this); mDataSource = new RemoteGirlsDataSource(); } @Override public void getGirls(int size, int page, final boolean isRefresh) { mDataSource.getGirls(size, page, new GirlsDataSource.LoadGirlsCallback() { @Override
public void onGirlsLoaded(GirlsParser girlsParser) {
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/girl/GirlAdapter.java
// Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/Girls.java // public class Girls implements Parcelable { // // private String _id; // private String createdAt; // private String desc; // private String publishedAt; // private String source; // private String type; // private String url; // private boolean used; // private String who; // // public void set_id(String _id) { // this._id = _id; // } // // public void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public void setPublishedAt(String publishedAt) { // this.publishedAt = publishedAt; // } // // public void setSource(String source) { // this.source = source; // } // // public void setType(String type) { // this.type = type; // } // // public void setUrl(String url) { // this.url = url; // } // // public void setUsed(boolean used) { // this.used = used; // } // // public void setWho(String who) { // this.who = who; // } // // public String get_id() { // return _id; // } // // public String getCreatedAt() { // return createdAt; // } // // public String getDesc() { // return desc; // } // // public String getPublishedAt() { // return publishedAt; // } // // public String getSource() { // return source; // } // // public String getType() { // return type; // } // // public String getUrl() { // return url; // } // // public boolean isUsed() { // return used; // } // // public String getWho() { // return who; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this._id); // dest.writeString(this.createdAt); // dest.writeString(this.desc); // dest.writeString(this.publishedAt); // dest.writeString(this.source); // dest.writeString(this.type); // dest.writeString(this.url); // dest.writeByte(this.used ? (byte) 1 : (byte) 0); // dest.writeString(this.who); // } // // public Girls() { // } // // protected Girls(Parcel in) { // this._id = in.readString(); // this.createdAt = in.readString(); // this.desc = in.readString(); // this.publishedAt = in.readString(); // this.source = in.readString(); // this.type = in.readString(); // this.url = in.readString(); // this.used = in.readByte() != 0; // this.who = in.readString(); // } // // public static final Creator<Girls> CREATOR = new Creator<Girls>() { // @Override // public Girls createFromParcel(Parcel source) { // return new Girls(source); // } // // @Override // public Girls[] newArray(int size) { // return new Girls[size]; // } // }; // }
import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.github.chrisbanes.photoview.PhotoView; import com.guiying.module.girls.R; import com.guiying.module.girls.data.bean.Girls; import java.util.List;
package com.guiying.module.girls.girl; /** * <p> </p> * * @author 张华洋 2017/5/19 20:31 * @version V1.1 * @name GirlAdapter */ public class GirlAdapter extends PagerAdapter { private Context mContext;
// Path: module_girls/src/main/java/com/guiying/module/girls/data/bean/Girls.java // public class Girls implements Parcelable { // // private String _id; // private String createdAt; // private String desc; // private String publishedAt; // private String source; // private String type; // private String url; // private boolean used; // private String who; // // public void set_id(String _id) { // this._id = _id; // } // // public void setCreatedAt(String createdAt) { // this.createdAt = createdAt; // } // // public void setDesc(String desc) { // this.desc = desc; // } // // public void setPublishedAt(String publishedAt) { // this.publishedAt = publishedAt; // } // // public void setSource(String source) { // this.source = source; // } // // public void setType(String type) { // this.type = type; // } // // public void setUrl(String url) { // this.url = url; // } // // public void setUsed(boolean used) { // this.used = used; // } // // public void setWho(String who) { // this.who = who; // } // // public String get_id() { // return _id; // } // // public String getCreatedAt() { // return createdAt; // } // // public String getDesc() { // return desc; // } // // public String getPublishedAt() { // return publishedAt; // } // // public String getSource() { // return source; // } // // public String getType() { // return type; // } // // public String getUrl() { // return url; // } // // public boolean isUsed() { // return used; // } // // public String getWho() { // return who; // } // // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(this._id); // dest.writeString(this.createdAt); // dest.writeString(this.desc); // dest.writeString(this.publishedAt); // dest.writeString(this.source); // dest.writeString(this.type); // dest.writeString(this.url); // dest.writeByte(this.used ? (byte) 1 : (byte) 0); // dest.writeString(this.who); // } // // public Girls() { // } // // protected Girls(Parcel in) { // this._id = in.readString(); // this.createdAt = in.readString(); // this.desc = in.readString(); // this.publishedAt = in.readString(); // this.source = in.readString(); // this.type = in.readString(); // this.url = in.readString(); // this.used = in.readByte() != 0; // this.who = in.readString(); // } // // public static final Creator<Girls> CREATOR = new Creator<Girls>() { // @Override // public Girls createFromParcel(Parcel source) { // return new Girls(source); // } // // @Override // public Girls[] newArray(int size) { // return new Girls[size]; // } // }; // } // Path: module_girls/src/main/java/com/guiying/module/girls/girl/GirlAdapter.java import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bumptech.glide.Glide; import com.github.chrisbanes.photoview.PhotoView; import com.guiying.module.girls.R; import com.guiying.module.girls.data.bean.Girls; import java.util.List; package com.guiying.module.girls.girl; /** * <p> </p> * * @author 张华洋 2017/5/19 20:31 * @version V1.1 * @name GirlAdapter */ public class GirlAdapter extends PagerAdapter { private Context mContext;
private List<Girls> mData;
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListContract.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // }
import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.StoryList;
package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsListContract { interface View extends BaseView<Presenter> { boolean isActive();
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListContract.java import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.StoryList; package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsListContract { interface View extends BaseView<Presenter> { boolean isActive();
void showNewsList(StoryList info);
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListContract.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // }
import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.StoryList;
package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsListContract { interface View extends BaseView<Presenter> { boolean isActive(); void showNewsList(StoryList info); }
// Path: lib_common/src/main/java/com/guiying/module/common/base/BasePresenter.java // @Keep // public interface BasePresenter { // // void start(); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseView.java // @Keep // public interface BaseView<T> { // // void setPresenter(T presenter); // // } // // Path: module_news/src/main/java/com/guiying/module/news/data/bean/StoryList.java // public class StoryList { // // private String date; // private List<Story> stories; // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStories() { // return stories; // } // // public void setStories(List<Story> stories) { // this.stories = stories; // } // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListContract.java import com.guiying.module.common.base.BasePresenter; import com.guiying.module.common.base.BaseView; import com.guiying.module.news.data.bean.StoryList; package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/2/22 20:33 * @version V1.2.0 * @name NewsContract */ public interface NewsListContract { interface View extends BaseView<Presenter> { boolean isActive(); void showNewsList(StoryList info); }
interface Presenter extends BasePresenter {
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/MyDelegate.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/IApplicationDelegate.java // @Keep // public interface IApplicationDelegate { // // void onCreate(); // // void onTerminate(); // // void onLowMemory(); // // void onTrimMemory(int level); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/ViewManager.java // @Keep // public class ViewManager { // // private static Stack<Activity> activityStack; // private static List<BaseFragment> fragmentList; // // public static ViewManager getInstance() { // return ViewManagerHolder.sInstance; // } // // private static class ViewManagerHolder { // private static final ViewManager sInstance = new ViewManager(); // } // // private ViewManager() { // } // // public void addFragment(int index, BaseFragment fragment) { // if (fragmentList == null) { // fragmentList = new ArrayList<>(); // } // fragmentList.add(index, fragment); // } // // // public BaseFragment getFragment(int index) { // if (fragmentList != null) { // return fragmentList.get(index); // } // return null; // } // // // public List<BaseFragment> getAllFragment() { // if (fragmentList != null) { // return fragmentList; // } // return null; // } // // // /** // * 添加指定Activity到堆栈 // */ // public void addActivity(Activity activity) { // if (activityStack == null) { // activityStack = new Stack<Activity>(); // } // activityStack.add(activity); // } // // // /** // * 获取当前Activity // */ // public Activity currentActivity() { // Activity activity = activityStack.lastElement(); // return activity; // } // // // /** // * 结束当前Activity // */ // public void finishActivity() { // Activity activity = activityStack.lastElement(); // finishActivity(activity); // } // // // /** // * 结束指定的Activity // */ // public void finishActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // activity.finish(); // activity = null; // } // } // // // /** // * 结束指定Class的Activity // */ // public void finishActivity(Class<?> cls) { // for (Activity activity : activityStack) { // if (activity.getClass().equals(cls)) { // finishActivity(activity); // return; // } // } // } // // // /** // * 结束全部的Activity // */ // public void finishAllActivity() { // for (int i = 0, size = activityStack.size(); i < size; i++) { // if (null != activityStack.get(i)) { // activityStack.get(i).finish(); // } // } // activityStack.clear(); // } // // // /** // * 退出应用程序 // */ // public void exitApp(Context context) { // try { // finishAllActivity(); // //杀死后台进程需要在AndroidManifest中声明android.permission.KILL_BACKGROUND_PROCESSES; // android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // activityManager.killBackgroundProcesses(context.getPackageName()); // //System.exit(0); // } catch (Exception e) { // Log.e("ActivityManager", "app exit" + e.getMessage()); // } // } // }
import android.support.annotation.Keep; import com.guiying.module.common.base.IApplicationDelegate; import com.guiying.module.common.base.ViewManager;
package com.guiying.module.girls; /** * <p>类说明</p> * * @author 张华洋 2017/9/20 22:29 * @version V2.8.3 * @name MyDelegate */ @Keep public class MyDelegate implements IApplicationDelegate { @Override public void onCreate() { //主动添加
// Path: lib_common/src/main/java/com/guiying/module/common/base/IApplicationDelegate.java // @Keep // public interface IApplicationDelegate { // // void onCreate(); // // void onTerminate(); // // void onLowMemory(); // // void onTrimMemory(int level); // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/ViewManager.java // @Keep // public class ViewManager { // // private static Stack<Activity> activityStack; // private static List<BaseFragment> fragmentList; // // public static ViewManager getInstance() { // return ViewManagerHolder.sInstance; // } // // private static class ViewManagerHolder { // private static final ViewManager sInstance = new ViewManager(); // } // // private ViewManager() { // } // // public void addFragment(int index, BaseFragment fragment) { // if (fragmentList == null) { // fragmentList = new ArrayList<>(); // } // fragmentList.add(index, fragment); // } // // // public BaseFragment getFragment(int index) { // if (fragmentList != null) { // return fragmentList.get(index); // } // return null; // } // // // public List<BaseFragment> getAllFragment() { // if (fragmentList != null) { // return fragmentList; // } // return null; // } // // // /** // * 添加指定Activity到堆栈 // */ // public void addActivity(Activity activity) { // if (activityStack == null) { // activityStack = new Stack<Activity>(); // } // activityStack.add(activity); // } // // // /** // * 获取当前Activity // */ // public Activity currentActivity() { // Activity activity = activityStack.lastElement(); // return activity; // } // // // /** // * 结束当前Activity // */ // public void finishActivity() { // Activity activity = activityStack.lastElement(); // finishActivity(activity); // } // // // /** // * 结束指定的Activity // */ // public void finishActivity(Activity activity) { // if (activity != null) { // activityStack.remove(activity); // activity.finish(); // activity = null; // } // } // // // /** // * 结束指定Class的Activity // */ // public void finishActivity(Class<?> cls) { // for (Activity activity : activityStack) { // if (activity.getClass().equals(cls)) { // finishActivity(activity); // return; // } // } // } // // // /** // * 结束全部的Activity // */ // public void finishAllActivity() { // for (int i = 0, size = activityStack.size(); i < size; i++) { // if (null != activityStack.get(i)) { // activityStack.get(i).finish(); // } // } // activityStack.clear(); // } // // // /** // * 退出应用程序 // */ // public void exitApp(Context context) { // try { // finishAllActivity(); // //杀死后台进程需要在AndroidManifest中声明android.permission.KILL_BACKGROUND_PROCESSES; // android.app.ActivityManager activityManager = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // activityManager.killBackgroundProcesses(context.getPackageName()); // //System.exit(0); // } catch (Exception e) { // Log.e("ActivityManager", "app exit" + e.getMessage()); // } // } // } // Path: module_girls/src/main/java/com/guiying/module/girls/MyDelegate.java import android.support.annotation.Keep; import com.guiying.module.common.base.IApplicationDelegate; import com.guiying.module.common.base.ViewManager; package com.guiying.module.girls; /** * <p>类说明</p> * * @author 张华洋 2017/9/20 22:29 * @version V2.8.3 * @name MyDelegate */ @Keep public class MyDelegate implements IApplicationDelegate { @Override public void onCreate() { //主动添加
ViewManager.getInstance().addFragment(0, GirlsFragment.newInstance());
guiying712/AndroidModulePattern
lib_common/src/main/java/com/guiying/module/common/base/BaseFragment.java
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // }
import android.content.Context; import android.support.annotation.IdRes; import android.support.annotation.Keep; import android.support.v4.app.Fragment; import com.guiying.module.common.utils.Utils;
package com.guiying.module.common.base; /** * <p>Fragment的基类</p> * * @author 张华洋 * @name BaseFragment */ @Keep public abstract class BaseFragment extends Fragment { protected BaseActivity mActivity; @Override public void onAttach(Context context) { super.onAttach(context); this.mActivity = (BaseActivity) context; } /** * 获取宿主Activity * * @return BaseActivity */ protected BaseActivity getHoldingActivity() { return mActivity; } /** * 添加fragment * * @param fragment * @param frameId */ protected void addFragment(BaseFragment fragment, @IdRes int frameId) {
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // } // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseFragment.java import android.content.Context; import android.support.annotation.IdRes; import android.support.annotation.Keep; import android.support.v4.app.Fragment; import com.guiying.module.common.utils.Utils; package com.guiying.module.common.base; /** * <p>Fragment的基类</p> * * @author 张华洋 * @name BaseFragment */ @Keep public abstract class BaseFragment extends Fragment { protected BaseActivity mActivity; @Override public void onAttach(Context context) { super.onAttach(context); this.mActivity = (BaseActivity) context; } /** * 获取宿主Activity * * @return BaseActivity */ protected BaseActivity getHoldingActivity() { return mActivity; } /** * 添加fragment * * @param fragment * @param frameId */ protected void addFragment(BaseFragment fragment, @IdRes int frameId) {
Utils.checkNotNull(fragment);
guiying712/AndroidModulePattern
module_app/src/main/java/com/guiying/module/MyApplication.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseApplication.java // public class BaseApplication extends Application { // // public static final String ROOT_PACKAGE = "com.guiying.module"; // // private static BaseApplication sInstance; // // private List<IApplicationDelegate> mAppDelegateList; // // // public static BaseApplication getIns() { // return sInstance; // } // // @Override // public void onCreate() { // super.onCreate(); // sInstance = this; // Logger.init("pattern").logLevel(LogLevel.FULL); // Utils.init(this); // mAppDelegateList = ClassUtils.getObjectsWithInterface(this, IApplicationDelegate.class, ROOT_PACKAGE); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onCreate(); // } // // } // // @Override // public void onTerminate() { // super.onTerminate(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTerminate(); // } // } // // // @Override // public void onLowMemory() { // super.onLowMemory(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onLowMemory(); // } // } // // @Override // public void onTrimMemory(int level) { // super.onTrimMemory(level); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTrimMemory(level); // } // } // } // // Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // }
import android.content.Context; import android.support.multidex.MultiDex; import com.alibaba.android.arouter.launcher.ARouter; import com.guiying.module.common.base.BaseApplication; import com.guiying.module.common.utils.Utils; import org.acra.ACRA; import org.acra.ReportField; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import org.acra.collector.CrashReportData; import org.acra.sender.EmailIntentSender; import org.acra.sender.ReportSender; import org.acra.sender.ReportSenderException;
package com.guiying.module; /** * <p>这里仅需做一些初始化的工作</p> * * @author 张华洋 2017/2/15 20:14 * @version V1.2.0 * @name MyApplication */ @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.DIALOG, customReportContent = { ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, ReportField.BRAND, ReportField.STACK_TRACE, ReportField.LOGCAT, ReportField.USER_COMMENT}, resToastText = R.string.crash_toast_text, resDialogText = R.string.crash_dialog_text, resDialogTitle = R.string.crash_dialog_title)
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseApplication.java // public class BaseApplication extends Application { // // public static final String ROOT_PACKAGE = "com.guiying.module"; // // private static BaseApplication sInstance; // // private List<IApplicationDelegate> mAppDelegateList; // // // public static BaseApplication getIns() { // return sInstance; // } // // @Override // public void onCreate() { // super.onCreate(); // sInstance = this; // Logger.init("pattern").logLevel(LogLevel.FULL); // Utils.init(this); // mAppDelegateList = ClassUtils.getObjectsWithInterface(this, IApplicationDelegate.class, ROOT_PACKAGE); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onCreate(); // } // // } // // @Override // public void onTerminate() { // super.onTerminate(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTerminate(); // } // } // // // @Override // public void onLowMemory() { // super.onLowMemory(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onLowMemory(); // } // } // // @Override // public void onTrimMemory(int level) { // super.onTrimMemory(level); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTrimMemory(level); // } // } // } // // Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // } // Path: module_app/src/main/java/com/guiying/module/MyApplication.java import android.content.Context; import android.support.multidex.MultiDex; import com.alibaba.android.arouter.launcher.ARouter; import com.guiying.module.common.base.BaseApplication; import com.guiying.module.common.utils.Utils; import org.acra.ACRA; import org.acra.ReportField; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import org.acra.collector.CrashReportData; import org.acra.sender.EmailIntentSender; import org.acra.sender.ReportSender; import org.acra.sender.ReportSenderException; package com.guiying.module; /** * <p>这里仅需做一些初始化的工作</p> * * @author 张华洋 2017/2/15 20:14 * @version V1.2.0 * @name MyApplication */ @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.DIALOG, customReportContent = { ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, ReportField.BRAND, ReportField.STACK_TRACE, ReportField.LOGCAT, ReportField.USER_COMMENT}, resToastText = R.string.crash_toast_text, resDialogText = R.string.crash_dialog_text, resDialogTitle = R.string.crash_dialog_title)
public class MyApplication extends BaseApplication {
guiying712/AndroidModulePattern
module_app/src/main/java/com/guiying/module/MyApplication.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseApplication.java // public class BaseApplication extends Application { // // public static final String ROOT_PACKAGE = "com.guiying.module"; // // private static BaseApplication sInstance; // // private List<IApplicationDelegate> mAppDelegateList; // // // public static BaseApplication getIns() { // return sInstance; // } // // @Override // public void onCreate() { // super.onCreate(); // sInstance = this; // Logger.init("pattern").logLevel(LogLevel.FULL); // Utils.init(this); // mAppDelegateList = ClassUtils.getObjectsWithInterface(this, IApplicationDelegate.class, ROOT_PACKAGE); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onCreate(); // } // // } // // @Override // public void onTerminate() { // super.onTerminate(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTerminate(); // } // } // // // @Override // public void onLowMemory() { // super.onLowMemory(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onLowMemory(); // } // } // // @Override // public void onTrimMemory(int level) { // super.onTrimMemory(level); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTrimMemory(level); // } // } // } // // Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // }
import android.content.Context; import android.support.multidex.MultiDex; import com.alibaba.android.arouter.launcher.ARouter; import com.guiying.module.common.base.BaseApplication; import com.guiying.module.common.utils.Utils; import org.acra.ACRA; import org.acra.ReportField; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import org.acra.collector.CrashReportData; import org.acra.sender.EmailIntentSender; import org.acra.sender.ReportSender; import org.acra.sender.ReportSenderException;
package com.guiying.module; /** * <p>这里仅需做一些初始化的工作</p> * * @author 张华洋 2017/2/15 20:14 * @version V1.2.0 * @name MyApplication */ @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.DIALOG, customReportContent = { ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, ReportField.BRAND, ReportField.STACK_TRACE, ReportField.LOGCAT, ReportField.USER_COMMENT}, resToastText = R.string.crash_toast_text, resDialogText = R.string.crash_dialog_text, resDialogTitle = R.string.crash_dialog_title) public class MyApplication extends BaseApplication { @Override public void onCreate() { super.onCreate();
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseApplication.java // public class BaseApplication extends Application { // // public static final String ROOT_PACKAGE = "com.guiying.module"; // // private static BaseApplication sInstance; // // private List<IApplicationDelegate> mAppDelegateList; // // // public static BaseApplication getIns() { // return sInstance; // } // // @Override // public void onCreate() { // super.onCreate(); // sInstance = this; // Logger.init("pattern").logLevel(LogLevel.FULL); // Utils.init(this); // mAppDelegateList = ClassUtils.getObjectsWithInterface(this, IApplicationDelegate.class, ROOT_PACKAGE); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onCreate(); // } // // } // // @Override // public void onTerminate() { // super.onTerminate(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTerminate(); // } // } // // // @Override // public void onLowMemory() { // super.onLowMemory(); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onLowMemory(); // } // } // // @Override // public void onTrimMemory(int level) { // super.onTrimMemory(level); // for (IApplicationDelegate delegate : mAppDelegateList) { // delegate.onTrimMemory(level); // } // } // } // // Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // } // Path: module_app/src/main/java/com/guiying/module/MyApplication.java import android.content.Context; import android.support.multidex.MultiDex; import com.alibaba.android.arouter.launcher.ARouter; import com.guiying.module.common.base.BaseApplication; import com.guiying.module.common.utils.Utils; import org.acra.ACRA; import org.acra.ReportField; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; import org.acra.collector.CrashReportData; import org.acra.sender.EmailIntentSender; import org.acra.sender.ReportSender; import org.acra.sender.ReportSenderException; package com.guiying.module; /** * <p>这里仅需做一些初始化的工作</p> * * @author 张华洋 2017/2/15 20:14 * @version V1.2.0 * @name MyApplication */ @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.DIALOG, customReportContent = { ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.CUSTOM_DATA, ReportField.BRAND, ReportField.STACK_TRACE, ReportField.LOGCAT, ReportField.USER_COMMENT}, resToastText = R.string.crash_toast_text, resDialogText = R.string.crash_dialog_text, resDialogTitle = R.string.crash_dialog_title) public class MyApplication extends BaseApplication { @Override public void onCreate() { super.onCreate();
if (Utils.isAppDebug()) {
guiying712/AndroidModulePattern
lib_common/src/main/java/com/guiying/module/common/base/BaseApplication.java
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // }
import android.app.Application; import com.guiying.module.common.utils.Utils; import com.orhanobut.logger.LogLevel; import com.orhanobut.logger.Logger; import java.util.List;
package com.guiying.module.common.base; /** * 要想使用BaseApplication,必须在组件中实现自己的Application,并且继承BaseApplication; * 组件中实现的Application必须在debug包中的AndroidManifest.xml中注册,否则无法使用; * 组件的Application需置于java/debug文件夹中,不得放于主代码; * 组件中获取Context的方法必须为:Utils.getContext(),不允许其他写法; * * @author 2016/12/2 17:02 * @version V1.0.0 * @name BaseApplication */ public class BaseApplication extends Application { public static final String ROOT_PACKAGE = "com.guiying.module"; private static BaseApplication sInstance; private List<IApplicationDelegate> mAppDelegateList; public static BaseApplication getIns() { return sInstance; } @Override public void onCreate() { super.onCreate(); sInstance = this; Logger.init("pattern").logLevel(LogLevel.FULL);
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // } // Path: lib_common/src/main/java/com/guiying/module/common/base/BaseApplication.java import android.app.Application; import com.guiying.module.common.utils.Utils; import com.orhanobut.logger.LogLevel; import com.orhanobut.logger.Logger; import java.util.List; package com.guiying.module.common.base; /** * 要想使用BaseApplication,必须在组件中实现自己的Application,并且继承BaseApplication; * 组件中实现的Application必须在debug包中的AndroidManifest.xml中注册,否则无法使用; * 组件的Application需置于java/debug文件夹中,不得放于主代码; * 组件中获取Context的方法必须为:Utils.getContext(),不允许其他写法; * * @author 2016/12/2 17:02 * @version V1.0.0 * @name BaseApplication */ public class BaseApplication extends Application { public static final String ROOT_PACKAGE = "com.guiying.module"; private static BaseApplication sInstance; private List<IApplicationDelegate> mAppDelegateList; public static BaseApplication getIns() { return sInstance; } @Override public void onCreate() { super.onCreate(); sInstance = this; Logger.init("pattern").logLevel(LogLevel.FULL);
Utils.init(this);
guiying712/AndroidModulePattern
module_girls/src/main/java/com/guiying/module/girls/MyViewDelegate.java
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseFragment.java // @Keep // public abstract class BaseFragment extends Fragment { // // protected BaseActivity mActivity; // // @Override // public void onAttach(Context context) { // super.onAttach(context); // this.mActivity = (BaseActivity) context; // } // // // /** // * 获取宿主Activity // * // * @return BaseActivity // */ // protected BaseActivity getHoldingActivity() { // return mActivity; // } // // // /** // * 添加fragment // * // * @param fragment // * @param frameId // */ // protected void addFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().addFragment(fragment, frameId); // // } // // // /** // * 替换fragment // * // * @param fragment // * @param frameId // */ // protected void replaceFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().replaceFragment(fragment, frameId); // } // // // /** // * 隐藏fragment // * // * @param fragment // */ // protected void hideFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().hideFragment(fragment); // } // // // /** // * 显示fragment // * // * @param fragment // */ // protected void showFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().showFragment(fragment); // } // // // /** // * 移除Fragment // * // * @param fragment // */ // protected void removeFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().removeFragment(fragment); // // } // // // /** // * 弹出栈顶部的Fragment // */ // protected void popFragment() { // getHoldingActivity().popFragment(); // } // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/IViewDelegate.java // @Keep // public interface IViewDelegate { // // BaseFragment getFragment(String name); // // View getView(String name); // // }
import android.support.annotation.Keep; import android.view.View; import com.guiying.module.common.base.BaseFragment; import com.guiying.module.common.base.IViewDelegate;
package com.guiying.module.girls; /** * <p>类说明</p> * * @author 张华洋 2018/1/4 22:16 * @version V2.8.3 * @name MyViewDelegate */ @Keep public class MyViewDelegate implements IViewDelegate { @Override
// Path: lib_common/src/main/java/com/guiying/module/common/base/BaseFragment.java // @Keep // public abstract class BaseFragment extends Fragment { // // protected BaseActivity mActivity; // // @Override // public void onAttach(Context context) { // super.onAttach(context); // this.mActivity = (BaseActivity) context; // } // // // /** // * 获取宿主Activity // * // * @return BaseActivity // */ // protected BaseActivity getHoldingActivity() { // return mActivity; // } // // // /** // * 添加fragment // * // * @param fragment // * @param frameId // */ // protected void addFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().addFragment(fragment, frameId); // // } // // // /** // * 替换fragment // * // * @param fragment // * @param frameId // */ // protected void replaceFragment(BaseFragment fragment, @IdRes int frameId) { // Utils.checkNotNull(fragment); // getHoldingActivity().replaceFragment(fragment, frameId); // } // // // /** // * 隐藏fragment // * // * @param fragment // */ // protected void hideFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().hideFragment(fragment); // } // // // /** // * 显示fragment // * // * @param fragment // */ // protected void showFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().showFragment(fragment); // } // // // /** // * 移除Fragment // * // * @param fragment // */ // protected void removeFragment(BaseFragment fragment) { // Utils.checkNotNull(fragment); // getHoldingActivity().removeFragment(fragment); // // } // // // /** // * 弹出栈顶部的Fragment // */ // protected void popFragment() { // getHoldingActivity().popFragment(); // } // // } // // Path: lib_common/src/main/java/com/guiying/module/common/base/IViewDelegate.java // @Keep // public interface IViewDelegate { // // BaseFragment getFragment(String name); // // View getView(String name); // // } // Path: module_girls/src/main/java/com/guiying/module/girls/MyViewDelegate.java import android.support.annotation.Keep; import android.view.View; import com.guiying.module.common.base.BaseFragment; import com.guiying.module.common.base.IViewDelegate; package com.guiying.module.girls; /** * <p>类说明</p> * * @author 张华洋 2018/1/4 22:16 * @version V2.8.3 * @name MyViewDelegate */ @Keep public class MyViewDelegate implements IViewDelegate { @Override
public BaseFragment getFragment(String name) {
guiying712/AndroidModulePattern
lib_common/src/main/java/com/guiying/module/common/glide/ImageUtils.java
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.GlideDrawableImageViewTarget; import com.bumptech.glide.request.target.SimpleTarget; import com.guiying.module.common.utils.Utils;
package com.guiying.module.common.glide; /** * <p> 图片加载工具类</p> * * @name ImageUtils */ public class ImageUtils { /** * 默认加载 */ public static void loadImageView(String path, ImageView mImageView) { Glide.with(mImageView.getContext()).load(path).into(mImageView); } public static void loadImageWithError(String path, int errorRes, ImageView mImageView) { Glide.with(mImageView.getContext()) .load(path) .crossFade() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .error(errorRes) .into(mImageView); } /** * 设置加载中以及加载失败图片 */ public static void loadImageWithLoading(String path, ImageView mImageView, int lodingImage, int errorRes) { Glide.with(mImageView.getContext()).load(path).placeholder(lodingImage). error(errorRes).into(mImageView); } /** * 设置加载动画 * api也提供了几个常用的动画:比如crossFade() */ public static void loadImageViewAnim(String path, int anim, ImageView mImageView) { Glide.with(mImageView.getContext()).load(path).animate(anim).into(mImageView); } /** * 加载为bitmap * * @param path 图片地址 * @param listener 回调 */ public static void loadBitMap(String path, final onLoadBitmap listener) {
// Path: lib_common/src/main/java/com/guiying/module/common/utils/Utils.java // public class Utils { // // private static Context context; // // private Utils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 初始化工具类 // * // * @param context 上下文 // */ // public static void init(Context context) { // Utils.context = context.getApplicationContext(); // } // // /** // * 获取ApplicationContext // * // * @return ApplicationContext // */ // public static Context getContext() { // if (context != null) return context; // throw new NullPointerException("u should init first"); // } // // /** // * View获取Activity的工具 // * // * @param view view // * @return Activity // */ // public static // @NonNull // Activity getActivity(View view) { // Context context = view.getContext(); // // while (context instanceof ContextWrapper) { // if (context instanceof Activity) { // return (Activity) context; // } // context = ((ContextWrapper) context).getBaseContext(); // } // // throw new IllegalStateException("View " + view + " is not attached to an Activity"); // } // // /** // * 全局获取String的方法 // * // * @param id 资源Id // * @return String // */ // public static String getString(@StringRes int id) { // return context.getResources().getString(id); // } // // /** // * 判断App是否是Debug版本 // * // * @return {@code true}: 是<br>{@code false}: 否 // */ // public static boolean isAppDebug() { // if (StringUtils.isSpace(context.getPackageName())) return false; // try { // PackageManager pm = context.getPackageManager(); // ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), 0); // return ai != null && (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // return false; // } // } // // // /** // * The {@code fragment} is added to the container view with id {@code frameId}. The operation is // * performed by the {@code fragmentManager}. // */ // public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager, // @NonNull Fragment fragment, int frameId) { // checkNotNull(fragmentManager); // checkNotNull(fragment); // FragmentTransaction transaction = fragmentManager.beginTransaction(); // transaction.add(frameId, fragment); // transaction.commit(); // } // // // public static <T> T checkNotNull(T obj) { // if (obj == null) { // throw new NullPointerException(); // } // return obj; // } // // } // Path: lib_common/src/main/java/com/guiying/module/common/glide/ImageUtils.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.GlideDrawableImageViewTarget; import com.bumptech.glide.request.target.SimpleTarget; import com.guiying.module.common.utils.Utils; package com.guiying.module.common.glide; /** * <p> 图片加载工具类</p> * * @name ImageUtils */ public class ImageUtils { /** * 默认加载 */ public static void loadImageView(String path, ImageView mImageView) { Glide.with(mImageView.getContext()).load(path).into(mImageView); } public static void loadImageWithError(String path, int errorRes, ImageView mImageView) { Glide.with(mImageView.getContext()) .load(path) .crossFade() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .error(errorRes) .into(mImageView); } /** * 设置加载中以及加载失败图片 */ public static void loadImageWithLoading(String path, ImageView mImageView, int lodingImage, int errorRes) { Glide.with(mImageView.getContext()).load(path).placeholder(lodingImage). error(errorRes).into(mImageView); } /** * 设置加载动画 * api也提供了几个常用的动画:比如crossFade() */ public static void loadImageViewAnim(String path, int anim, ImageView mImageView) { Glide.with(mImageView.getContext()).load(path).animate(anim).into(mImageView); } /** * 加载为bitmap * * @param path 图片地址 * @param listener 回调 */ public static void loadBitMap(String path, final onLoadBitmap listener) {
Glide.with(Utils.getContext()).load(path).asBitmap().into(new SimpleTarget<Bitmap>() {
guiying712/AndroidModulePattern
lib_common/src/main/java/com/guiying/module/common/http/HttpsUtils.java
// Path: lib_common/src/main/java/com/guiying/module/common/utils/CloseUtils.java // public class CloseUtils { // // private CloseUtils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 关闭IO // * // * @param closeables closeable // */ // public static void closeIO(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // // /** // * 安静关闭IO // * // * @param closeables closeable // */ // public static void closeIOQuietly(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException ignored) { // } // } // } // } // }
import android.content.Context; import android.support.annotation.RawRes; import android.text.TextUtils; import com.guiying.module.common.utils.CloseUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.Socket; import java.security.InvalidKeyException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.SignatureException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager;
package com.guiying.module.common.http; /** * <p>Https证书校验工具类</p> * * @author 张华洋 2017/5/11 16:14 * @version V1.2.0 * @name HttpsUtils */ public class HttpsUtils { public static class SSLParams { public SSLSocketFactory sSLSocketFactory; public X509TrustManager trustManager; } /** * @param context 上下文 * @param bksFileId "XXX.bks"文件(文件位置res/raw/XXX.bks) * @param password The certificate's password. * @return SSLParams */ public static SSLParams getSslSocketFactory(Context context, @RawRes int bksFileId, String password, String alias) { if (context == null) { throw new NullPointerException("context == null"); } if (TextUtils.isEmpty(password) || TextUtils.isEmpty(alias)) { throw new NullPointerException("password == null or alias == null!"); } SSLParams sslParams = new SSLParams(); try { // 创建一个BKS类型的KeyStore,存储我们信任的证书 KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(context.getResources().openRawResource(bksFileId), password.toCharArray()); //通过alias直接从密钥库中读取证书 Certificate rootCA = clientKeyStore.getCertificate(alias); // Turn it to X509 format. InputStream certInput = new ByteArrayInputStream(rootCA.getEncoded()); X509Certificate serverCert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certInput); //关闭流
// Path: lib_common/src/main/java/com/guiying/module/common/utils/CloseUtils.java // public class CloseUtils { // // private CloseUtils() { // throw new UnsupportedOperationException("u can't instantiate me..."); // } // // /** // * 关闭IO // * // * @param closeables closeable // */ // public static void closeIO(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // // /** // * 安静关闭IO // * // * @param closeables closeable // */ // public static void closeIOQuietly(Closeable... closeables) { // if (closeables == null) return; // for (Closeable closeable : closeables) { // if (closeable != null) { // try { // closeable.close(); // } catch (IOException ignored) { // } // } // } // } // } // Path: lib_common/src/main/java/com/guiying/module/common/http/HttpsUtils.java import android.content.Context; import android.support.annotation.RawRes; import android.text.TextUtils; import com.guiying.module.common.utils.CloseUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.Socket; import java.security.InvalidKeyException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.SignatureException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; package com.guiying.module.common.http; /** * <p>Https证书校验工具类</p> * * @author 张华洋 2017/5/11 16:14 * @version V1.2.0 * @name HttpsUtils */ public class HttpsUtils { public static class SSLParams { public SSLSocketFactory sSLSocketFactory; public X509TrustManager trustManager; } /** * @param context 上下文 * @param bksFileId "XXX.bks"文件(文件位置res/raw/XXX.bks) * @param password The certificate's password. * @return SSLParams */ public static SSLParams getSslSocketFactory(Context context, @RawRes int bksFileId, String password, String alias) { if (context == null) { throw new NullPointerException("context == null"); } if (TextUtils.isEmpty(password) || TextUtils.isEmpty(alias)) { throw new NullPointerException("password == null or alias == null!"); } SSLParams sslParams = new SSLParams(); try { // 创建一个BKS类型的KeyStore,存储我们信任的证书 KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(context.getResources().openRawResource(bksFileId), password.toCharArray()); //通过alias直接从密钥库中读取证书 Certificate rootCA = clientKeyStore.getCertificate(alias); // Turn it to X509 format. InputStream certInput = new ByteArrayInputStream(rootCA.getEncoded()); X509Certificate serverCert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certInput); //关闭流
CloseUtils.closeIO(certInput);
guiying712/AndroidModulePattern
module_news/src/main/java/com/guiying/module/news/main/NewsListAdapter.java
// Path: module_news/src/main/java/com/guiying/module/news/data/bean/Story.java // public class Story { // // /** // * 新闻标题 // **/ // private String title; // /** // * 供 Google Analytics 使用 // **/ // private String ga_prefix; // /** // * 图像地址(官方 API 使用数组形式。目前暂未有使用多张图片的情形出现,曾见无 images 属性的情况,请在使用中注意 ) // **/ // private String[] images; // /** // * 消息是否包含多张图片(仅出现在包含多图的新闻中) // **/ // private String multipic; // private String type; // /** // * url 与 share_url 中最后的数字(应为内容的 id) // **/ // private String id; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String[] getImages() { // return images; // } // // public void setImages(String[] images) { // this.images = images; // } // // public String getMultipic() { // return multipic; // } // // public void setMultipic(String multipic) { // this.multipic = multipic; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailActivity.java // @Route(path = "/news/detail") // public class NewsDetailActivity extends BaseActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // NewsDetailView detailView = new NewsDetailView(this); // setContentView(detailView); // String id = getIntent().getStringExtra("id"); // new NewsDetailPresenter(detailView).getNewsDetail(id); // } // // }
import android.content.Context; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.guiying.module.news.R; import com.guiying.module.news.data.bean.Story; import com.guiying.module.news.detail.NewsDetailActivity; import com.jude.easyrecyclerview.adapter.BaseViewHolder; import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/4/20 22:26 * @version V1.2.0 * @name NewsListAdapter */ public class NewsListAdapter extends RecyclerArrayAdapter<Story> { public NewsListAdapter(Context context) { super(context); } @Override public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { return new NewsListHolder(parent); } private class NewsListHolder extends BaseViewHolder<Story> { private TextView mTextView; private ImageView mImageView; NewsListHolder(ViewGroup parent) { super(parent, R.layout.item_news_list); mTextView = $(R.id.news_title); mImageView = $(R.id.news_image); } @Override public void setData(final Story data) { super.setData(data); mTextView.setText(data.getTitle()); Glide.with(getContext()) .load(data.getImages()[0]) .centerCrop() .crossFade() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(mImageView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
// Path: module_news/src/main/java/com/guiying/module/news/data/bean/Story.java // public class Story { // // /** // * 新闻标题 // **/ // private String title; // /** // * 供 Google Analytics 使用 // **/ // private String ga_prefix; // /** // * 图像地址(官方 API 使用数组形式。目前暂未有使用多张图片的情形出现,曾见无 images 属性的情况,请在使用中注意 ) // **/ // private String[] images; // /** // * 消息是否包含多张图片(仅出现在包含多图的新闻中) // **/ // private String multipic; // private String type; // /** // * url 与 share_url 中最后的数字(应为内容的 id) // **/ // private String id; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getGa_prefix() { // return ga_prefix; // } // // public void setGa_prefix(String ga_prefix) { // this.ga_prefix = ga_prefix; // } // // public String[] getImages() { // return images; // } // // public void setImages(String[] images) { // this.images = images; // } // // public String getMultipic() { // return multipic; // } // // public void setMultipic(String multipic) { // this.multipic = multipic; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // } // // Path: module_news/src/main/java/com/guiying/module/news/detail/NewsDetailActivity.java // @Route(path = "/news/detail") // public class NewsDetailActivity extends BaseActivity { // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // NewsDetailView detailView = new NewsDetailView(this); // setContentView(detailView); // String id = getIntent().getStringExtra("id"); // new NewsDetailPresenter(detailView).getNewsDetail(id); // } // // } // Path: module_news/src/main/java/com/guiying/module/news/main/NewsListAdapter.java import android.content.Context; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.guiying.module.news.R; import com.guiying.module.news.data.bean.Story; import com.guiying.module.news.detail.NewsDetailActivity; import com.jude.easyrecyclerview.adapter.BaseViewHolder; import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter; package com.guiying.module.news.main; /** * <p>类说明</p> * * @author 张华洋 2017/4/20 22:26 * @version V1.2.0 * @name NewsListAdapter */ public class NewsListAdapter extends RecyclerArrayAdapter<Story> { public NewsListAdapter(Context context) { super(context); } @Override public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { return new NewsListHolder(parent); } private class NewsListHolder extends BaseViewHolder<Story> { private TextView mTextView; private ImageView mImageView; NewsListHolder(ViewGroup parent) { super(parent, R.layout.item_news_list); mTextView = $(R.id.news_title); mImageView = $(R.id.news_image); } @Override public void setData(final Story data) { super.setData(data); mTextView.setText(data.getTitle()); Glide.with(getContext()) .load(data.getImages()[0]) .centerCrop() .crossFade() .diskCacheStrategy(DiskCacheStrategy.SOURCE) .into(mImageView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
Intent intent = new Intent(getContext(), NewsDetailActivity.class);
generators-io-projects/generators
generators-core/src/main/java/io/generators/core/network/IPv6Generator.java
// Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // // Path: generators-core/src/main/java/io/generators/core/RandomPositiveIntegerGenerator.java // public class RandomPositiveIntegerGenerator implements Generator<Integer> { // private final int from; // private final int to; // private final Random random = ThreadLocalRandom.current(); // // /** // * Creates generator that generates integers between from (inclusive) and to (exclusive). // * // * @param from inclusive lower bound // * @param to exclusive upper bound // * @throws IllegalArgumentException when <code>from</code> is less then zero or <code>to</code> is less then or equal to <code>from</code> // */ // public RandomPositiveIntegerGenerator(int from, int to) { // checkArgument(from >= 0, "from must be >= 0"); // checkArgument(from < to, "from must be < to"); // this.from = from; // this.to = to; // } // // /** // * Creates generator that generates integers between from 0 and {@link Integer#MAX_VALUE}. // */ // public RandomPositiveIntegerGenerator() { // this(0, Integer.MAX_VALUE); // } // // @Override // public Integer next() { // return from + random.nextInt(to - from); // } // }
import static java.lang.String.format; import com.google.common.base.Joiner; import io.generators.core.Generator; import io.generators.core.RandomPositiveIntegerGenerator;
package io.generators.core.network; /** * Class generates random valid IPv6 addresses. Currently includes all the types of IP addresses including broadcast, * loopback etc in the default generation strategy. And it does not support the abbreviated notation. * * @author Saket */ public class IPv6Generator implements Generator<String> { private static final String IP_ADDRESS_FORMAT = "%s:%s:%s:%s:%s:%s:%s:%s"; private final Generator<Integer> hexDigitGenerator; public IPv6Generator() {
// Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // // Path: generators-core/src/main/java/io/generators/core/RandomPositiveIntegerGenerator.java // public class RandomPositiveIntegerGenerator implements Generator<Integer> { // private final int from; // private final int to; // private final Random random = ThreadLocalRandom.current(); // // /** // * Creates generator that generates integers between from (inclusive) and to (exclusive). // * // * @param from inclusive lower bound // * @param to exclusive upper bound // * @throws IllegalArgumentException when <code>from</code> is less then zero or <code>to</code> is less then or equal to <code>from</code> // */ // public RandomPositiveIntegerGenerator(int from, int to) { // checkArgument(from >= 0, "from must be >= 0"); // checkArgument(from < to, "from must be < to"); // this.from = from; // this.to = to; // } // // /** // * Creates generator that generates integers between from 0 and {@link Integer#MAX_VALUE}. // */ // public RandomPositiveIntegerGenerator() { // this(0, Integer.MAX_VALUE); // } // // @Override // public Integer next() { // return from + random.nextInt(to - from); // } // } // Path: generators-core/src/main/java/io/generators/core/network/IPv6Generator.java import static java.lang.String.format; import com.google.common.base.Joiner; import io.generators.core.Generator; import io.generators.core.RandomPositiveIntegerGenerator; package io.generators.core.network; /** * Class generates random valid IPv6 addresses. Currently includes all the types of IP addresses including broadcast, * loopback etc in the default generation strategy. And it does not support the abbreviated notation. * * @author Saket */ public class IPv6Generator implements Generator<String> { private static final String IP_ADDRESS_FORMAT = "%s:%s:%s:%s:%s:%s:%s:%s"; private final Generator<Integer> hexDigitGenerator; public IPv6Generator() {
this(new RandomPositiveIntegerGenerator(0, 16));
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/MorePredicatesTest.java
// Path: generators-core/src/test/java/io/generators/core/MorePredicatesTest.java // static <T> PredicateDataPoint<T> create(Predicate<T> predicate, T value, boolean result) { // return new PredicateDataPoint<>(predicate, value, result); // }
import com.google.common.base.Predicate; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import static io.generators.core.MorePredicatesTest.PredicateDataPoint.create; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package io.generators.core; @RunWith(Theories.class) public class MorePredicatesTest { private static final Predicate<Integer> IN_PREDICATE = MorePredicates.in(6, 7, 8); @DataPoints public static final PredicateDataPoint<Integer>[] DATA_POINTS = new PredicateDataPoint[]{
// Path: generators-core/src/test/java/io/generators/core/MorePredicatesTest.java // static <T> PredicateDataPoint<T> create(Predicate<T> predicate, T value, boolean result) { // return new PredicateDataPoint<>(predicate, value, result); // } // Path: generators-core/src/test/java/io/generators/core/MorePredicatesTest.java import com.google.common.base.Predicate; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import static io.generators.core.MorePredicatesTest.PredicateDataPoint.create; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package io.generators.core; @RunWith(Theories.class) public class MorePredicatesTest { private static final Predicate<Integer> IN_PREDICATE = MorePredicates.in(6, 7, 8); @DataPoints public static final PredicateDataPoint<Integer>[] DATA_POINTS = new PredicateDataPoint[]{
create(IN_PREDICATE, 5, false),
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/TypeGeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static io.generators.core.Generators.ofInstance; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package io.generators.core; public class TypeGeneratorTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private static final String MESSAGE = "Some message"; static class AlwaysThrowsException { public AlwaysThrowsException(Integer i) { throw new IllegalArgumentException(MESSAGE); } } @Test public void shouldFailWhenTypeClassIsNull() { //Given expectedException.expect(NullPointerException.class); expectedException.expectMessage("typeClass"); //When Class<WholeAmount> typeClass = null;
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // } // Path: generators-core/src/test/java/io/generators/core/TypeGeneratorTest.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static io.generators.core.Generators.ofInstance; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package io.generators.core; public class TypeGeneratorTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private static final String MESSAGE = "Some message"; static class AlwaysThrowsException { public AlwaysThrowsException(Integer i) { throw new IllegalArgumentException(MESSAGE); } } @Test public void shouldFailWhenTypeClassIsNull() { //Given expectedException.expect(NullPointerException.class); expectedException.expectMessage("typeClass"); //When Class<WholeAmount> typeClass = null;
new TypeGenerator<>(typeClass, ofInstance(13));
generators-io-projects/generators
generators-core/src/main/java/io/generators/core/network/IPv4Generator.java
// Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // // Path: generators-core/src/main/java/io/generators/core/RandomPositiveIntegerGenerator.java // public class RandomPositiveIntegerGenerator implements Generator<Integer> { // private final int from; // private final int to; // private final Random random = ThreadLocalRandom.current(); // // /** // * Creates generator that generates integers between from (inclusive) and to (exclusive). // * // * @param from inclusive lower bound // * @param to exclusive upper bound // * @throws IllegalArgumentException when <code>from</code> is less then zero or <code>to</code> is less then or equal to <code>from</code> // */ // public RandomPositiveIntegerGenerator(int from, int to) { // checkArgument(from >= 0, "from must be >= 0"); // checkArgument(from < to, "from must be < to"); // this.from = from; // this.to = to; // } // // /** // * Creates generator that generates integers between from 0 and {@link Integer#MAX_VALUE}. // */ // public RandomPositiveIntegerGenerator() { // this(0, Integer.MAX_VALUE); // } // // @Override // public Integer next() { // return from + random.nextInt(to - from); // } // }
import static java.lang.String.format; import io.generators.core.Generator; import io.generators.core.RandomPositiveIntegerGenerator;
package io.generators.core.network; /** * Class generates random valid IPv4 addresses. Currently includes all the types of IP addresses including broadcast, * loopback etc in the default generation strategy. * * @author Saket */ public class IPv4Generator implements Generator<String> { private static final String IP_ADDRESS_FORMAT = "%s.%s.%s.%s"; private final Generator<Integer> octetGenerator; public IPv4Generator() {
// Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // // Path: generators-core/src/main/java/io/generators/core/RandomPositiveIntegerGenerator.java // public class RandomPositiveIntegerGenerator implements Generator<Integer> { // private final int from; // private final int to; // private final Random random = ThreadLocalRandom.current(); // // /** // * Creates generator that generates integers between from (inclusive) and to (exclusive). // * // * @param from inclusive lower bound // * @param to exclusive upper bound // * @throws IllegalArgumentException when <code>from</code> is less then zero or <code>to</code> is less then or equal to <code>from</code> // */ // public RandomPositiveIntegerGenerator(int from, int to) { // checkArgument(from >= 0, "from must be >= 0"); // checkArgument(from < to, "from must be < to"); // this.from = from; // this.to = to; // } // // /** // * Creates generator that generates integers between from 0 and {@link Integer#MAX_VALUE}. // */ // public RandomPositiveIntegerGenerator() { // this(0, Integer.MAX_VALUE); // } // // @Override // public Integer next() { // return from + random.nextInt(to - from); // } // } // Path: generators-core/src/main/java/io/generators/core/network/IPv4Generator.java import static java.lang.String.format; import io.generators.core.Generator; import io.generators.core.RandomPositiveIntegerGenerator; package io.generators.core.network; /** * Class generates random valid IPv4 addresses. Currently includes all the types of IP addresses including broadcast, * loopback etc in the default generation strategy. * * @author Saket */ public class IPv4Generator implements Generator<String> { private static final String IP_ADDRESS_FORMAT = "%s.%s.%s.%s"; private final Generator<Integer> octetGenerator; public IPv4Generator() {
this(new RandomPositiveIntegerGenerator(0, 256));
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/FluentGeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // } // // Path: generators-core/src/main/java/io/generators/core/Generators.java // public static Generator<Integer> positiveInts(int from, int to) { // return new RandomPositiveIntegerGenerator(from, to); // }
import com.google.common.base.Function; import com.google.common.base.Predicate; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; import static io.generators.core.Generators.ofInstance; import static io.generators.core.Generators.positiveInts; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.verify;
package io.generators.core; @RunWith(MockitoJUnitRunner.class) public class FluentGeneratorTest { @Mock private Consumer<Integer> firstConsumer; @Mock private Consumer<Integer> secondConsumer; @Test public void shouldCreateGenerator() { //Given
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // } // // Path: generators-core/src/main/java/io/generators/core/Generators.java // public static Generator<Integer> positiveInts(int from, int to) { // return new RandomPositiveIntegerGenerator(from, to); // } // Path: generators-core/src/test/java/io/generators/core/FluentGeneratorTest.java import com.google.common.base.Function; import com.google.common.base.Predicate; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; import static io.generators.core.Generators.ofInstance; import static io.generators.core.Generators.positiveInts; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.verify; package io.generators.core; @RunWith(MockitoJUnitRunner.class) public class FluentGeneratorTest { @Mock private Consumer<Integer> firstConsumer; @Mock private Consumer<Integer> secondConsumer; @Test public void shouldCreateGenerator() { //Given
Generator<Integer> generator = FluentGenerator.from(positiveInts);
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/FluentGeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // } // // Path: generators-core/src/main/java/io/generators/core/Generators.java // public static Generator<Integer> positiveInts(int from, int to) { // return new RandomPositiveIntegerGenerator(from, to); // }
import com.google.common.base.Function; import com.google.common.base.Predicate; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; import static io.generators.core.Generators.ofInstance; import static io.generators.core.Generators.positiveInts; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.verify;
.unique() .ofType(WholeAmount.class); //When WholeAmount wholeAmount = generator.next(); //Then assertThat(wholeAmount, notNullValue()); } @Test public void shouldCreateFluentUniqueOfTypeIterableGenerator() { //Given Iterable<WholeAmount> amounts = FluentGenerator.from(positiveInts) .unique() .ofType(WholeAmount.class) .toIterable(5); Set<WholeAmount> amountsSet = newHashSet(); //When for (WholeAmount amount : amounts) { amountsSet.add(amount); } assertThat(amountsSet, hasSize(5)); } @Test public void shouldApplyTransformingGenerator() { //Given
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // } // // Path: generators-core/src/main/java/io/generators/core/Generators.java // public static Generator<Integer> positiveInts(int from, int to) { // return new RandomPositiveIntegerGenerator(from, to); // } // Path: generators-core/src/test/java/io/generators/core/FluentGeneratorTest.java import com.google.common.base.Function; import com.google.common.base.Predicate; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import java.util.Set; import static com.google.common.collect.Sets.newHashSet; import static io.generators.core.Generators.ofInstance; import static io.generators.core.Generators.positiveInts; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.verify; .unique() .ofType(WholeAmount.class); //When WholeAmount wholeAmount = generator.next(); //Then assertThat(wholeAmount, notNullValue()); } @Test public void shouldCreateFluentUniqueOfTypeIterableGenerator() { //Given Iterable<WholeAmount> amounts = FluentGenerator.from(positiveInts) .unique() .ofType(WholeAmount.class) .toIterable(5); Set<WholeAmount> amountsSet = newHashSet(); //When for (WholeAmount amount : amounts) { amountsSet.add(amount); } assertThat(amountsSet, hasSize(5)); } @Test public void shouldApplyTransformingGenerator() { //Given
FluentGenerator<Long> generator = FluentGenerator.from(ofInstance(-5))
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/network/IPv6GeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test;
package io.generators.core.network; /** * @author Saket */ public class IPv6GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() {
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // Path: generators-core/src/test/java/io/generators/core/network/IPv6GeneratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test; package io.generators.core.network; /** * @author Saket */ public class IPv6GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() {
Generator<String> generator = new IPv6Generator();
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/network/IPv6GeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test;
package io.generators.core.network; /** * @author Saket */ public class IPv6GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() { Generator<String> generator = new IPv6Generator(); for (int i = 0; i < 100; i++) { String ipAddress = generator.next(); assertThatHasValidHexDigitsInGroups(ipAddress); } } @Test public void shouldReturnAnIPAddressUsingTheDelegateOctetGenerator() {
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // Path: generators-core/src/test/java/io/generators/core/network/IPv6GeneratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test; package io.generators.core.network; /** * @author Saket */ public class IPv6GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() { Generator<String> generator = new IPv6Generator(); for (int i = 0; i < 100; i++) { String ipAddress = generator.next(); assertThatHasValidHexDigitsInGroups(ipAddress); } } @Test public void shouldReturnAnIPAddressUsingTheDelegateOctetGenerator() {
Generator<String> generator = new IPv6Generator(new CyclicGenerator<>(10));
generators-io-projects/generators
generators-core/src/main/java/io/generators/core/Generators.java
// Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<Long, Long> appendLuhnCheckDigit() { // return new LuhnCheckDigitFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toLowerCase() { // return new ToLowerCaseFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toUpperCase(@Nonnull Locale locale) { // return new ToUpperCaseFunction(checkNotNull(locale)); // }
import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import java.util.List; import java.util.Locale; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static io.generators.core.MoreFunctions.appendLuhnCheckDigit; import static io.generators.core.MoreFunctions.toLowerCase; import static io.generators.core.MoreFunctions.toUpperCase; import static java.lang.Math.pow;
return new TypeGenerator<>(type, valueGenerator); } public static <T> Iterable<T> iterable(int limit, Generator<T> generator) { return new GeneratorIterable<>(limit, generator); } public static <T> Generator<T> biased(int percentageBiasTowardsFirst, Generator<T> firstGenerator, Generator<T> secondGenerator) { return new BiasedGenerator<>(percentageBiasTowardsFirst, firstGenerator, secondGenerator); } public static <T> List<T> listFrom(int limit, Generator<T> generator) { return FluentIterable.from(new GeneratorIterable<>(generator)).limit(limit).toList(); } public static <T> Set<T> setFrom(int limit, Generator<T> generator) { return FluentIterable.from(new GeneratorIterable<>(generator)).limit(limit).toSet(); } public static <T extends Enum<T>> Generator<T> randomEnum(Class<T> enumClass) { return new RandomEnumGenerator<>(enumClass); } /** * Creates Generator that appends Luhn check digit (modulus 10) to the number generated by {@code partialNumberGenerator} * * @param partialAccountNumberGenerator generator of the main part of the card number * @return generator that returns card/account numbers with calculated Luhn check Digit */ public static Generator<Long> cardNumber(Generator<Long> partialAccountNumberGenerator) {
// Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<Long, Long> appendLuhnCheckDigit() { // return new LuhnCheckDigitFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toLowerCase() { // return new ToLowerCaseFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toUpperCase(@Nonnull Locale locale) { // return new ToUpperCaseFunction(checkNotNull(locale)); // } // Path: generators-core/src/main/java/io/generators/core/Generators.java import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import java.util.List; import java.util.Locale; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static io.generators.core.MoreFunctions.appendLuhnCheckDigit; import static io.generators.core.MoreFunctions.toLowerCase; import static io.generators.core.MoreFunctions.toUpperCase; import static java.lang.Math.pow; return new TypeGenerator<>(type, valueGenerator); } public static <T> Iterable<T> iterable(int limit, Generator<T> generator) { return new GeneratorIterable<>(limit, generator); } public static <T> Generator<T> biased(int percentageBiasTowardsFirst, Generator<T> firstGenerator, Generator<T> secondGenerator) { return new BiasedGenerator<>(percentageBiasTowardsFirst, firstGenerator, secondGenerator); } public static <T> List<T> listFrom(int limit, Generator<T> generator) { return FluentIterable.from(new GeneratorIterable<>(generator)).limit(limit).toList(); } public static <T> Set<T> setFrom(int limit, Generator<T> generator) { return FluentIterable.from(new GeneratorIterable<>(generator)).limit(limit).toSet(); } public static <T extends Enum<T>> Generator<T> randomEnum(Class<T> enumClass) { return new RandomEnumGenerator<>(enumClass); } /** * Creates Generator that appends Luhn check digit (modulus 10) to the number generated by {@code partialNumberGenerator} * * @param partialAccountNumberGenerator generator of the main part of the card number * @return generator that returns card/account numbers with calculated Luhn check Digit */ public static Generator<Long> cardNumber(Generator<Long> partialAccountNumberGenerator) {
return new TransformingGenerator<>(partialAccountNumberGenerator, appendLuhnCheckDigit());
generators-io-projects/generators
generators-core/src/main/java/io/generators/core/Generators.java
// Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<Long, Long> appendLuhnCheckDigit() { // return new LuhnCheckDigitFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toLowerCase() { // return new ToLowerCaseFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toUpperCase(@Nonnull Locale locale) { // return new ToUpperCaseFunction(checkNotNull(locale)); // }
import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import java.util.List; import java.util.Locale; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static io.generators.core.MoreFunctions.appendLuhnCheckDigit; import static io.generators.core.MoreFunctions.toLowerCase; import static io.generators.core.MoreFunctions.toUpperCase; import static java.lang.Math.pow;
public static <T> Set<T> setFrom(int limit, Generator<T> generator) { return FluentIterable.from(new GeneratorIterable<>(generator)).limit(limit).toSet(); } public static <T extends Enum<T>> Generator<T> randomEnum(Class<T> enumClass) { return new RandomEnumGenerator<>(enumClass); } /** * Creates Generator that appends Luhn check digit (modulus 10) to the number generated by {@code partialNumberGenerator} * * @param partialAccountNumberGenerator generator of the main part of the card number * @return generator that returns card/account numbers with calculated Luhn check Digit */ public static Generator<Long> cardNumber(Generator<Long> partialAccountNumberGenerator) { return new TransformingGenerator<>(partialAccountNumberGenerator, appendLuhnCheckDigit()); } public static Generator<Integer> nDigitPositiveInteger(int digits) { checkArgument(digits > 0 && digits < 11, "Number of digits must be between 1 and 10"); int from = (int) pow(10, digits - 1); int to = (int) pow(10, digits); return new RandomPositiveIntegerGenerator(from, to); } public static <F, T> Generator<T> transform(Generator<F> delegate, Function<F, T> transformation) { return new TransformingGenerator<>(delegate, transformation); } public static Generator<String> upperCase(GeneratorOfInstance<String> delegate, Locale locale) {
// Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<Long, Long> appendLuhnCheckDigit() { // return new LuhnCheckDigitFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toLowerCase() { // return new ToLowerCaseFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toUpperCase(@Nonnull Locale locale) { // return new ToUpperCaseFunction(checkNotNull(locale)); // } // Path: generators-core/src/main/java/io/generators/core/Generators.java import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import java.util.List; import java.util.Locale; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static io.generators.core.MoreFunctions.appendLuhnCheckDigit; import static io.generators.core.MoreFunctions.toLowerCase; import static io.generators.core.MoreFunctions.toUpperCase; import static java.lang.Math.pow; public static <T> Set<T> setFrom(int limit, Generator<T> generator) { return FluentIterable.from(new GeneratorIterable<>(generator)).limit(limit).toSet(); } public static <T extends Enum<T>> Generator<T> randomEnum(Class<T> enumClass) { return new RandomEnumGenerator<>(enumClass); } /** * Creates Generator that appends Luhn check digit (modulus 10) to the number generated by {@code partialNumberGenerator} * * @param partialAccountNumberGenerator generator of the main part of the card number * @return generator that returns card/account numbers with calculated Luhn check Digit */ public static Generator<Long> cardNumber(Generator<Long> partialAccountNumberGenerator) { return new TransformingGenerator<>(partialAccountNumberGenerator, appendLuhnCheckDigit()); } public static Generator<Integer> nDigitPositiveInteger(int digits) { checkArgument(digits > 0 && digits < 11, "Number of digits must be between 1 and 10"); int from = (int) pow(10, digits - 1); int to = (int) pow(10, digits); return new RandomPositiveIntegerGenerator(from, to); } public static <F, T> Generator<T> transform(Generator<F> delegate, Function<F, T> transformation) { return new TransformingGenerator<>(delegate, transformation); } public static Generator<String> upperCase(GeneratorOfInstance<String> delegate, Locale locale) {
return transform(delegate, toUpperCase(locale));
generators-io-projects/generators
generators-core/src/main/java/io/generators/core/Generators.java
// Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<Long, Long> appendLuhnCheckDigit() { // return new LuhnCheckDigitFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toLowerCase() { // return new ToLowerCaseFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toUpperCase(@Nonnull Locale locale) { // return new ToUpperCaseFunction(checkNotNull(locale)); // }
import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import java.util.List; import java.util.Locale; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static io.generators.core.MoreFunctions.appendLuhnCheckDigit; import static io.generators.core.MoreFunctions.toLowerCase; import static io.generators.core.MoreFunctions.toUpperCase; import static java.lang.Math.pow;
/** * Creates Generator that appends Luhn check digit (modulus 10) to the number generated by {@code partialNumberGenerator} * * @param partialAccountNumberGenerator generator of the main part of the card number * @return generator that returns card/account numbers with calculated Luhn check Digit */ public static Generator<Long> cardNumber(Generator<Long> partialAccountNumberGenerator) { return new TransformingGenerator<>(partialAccountNumberGenerator, appendLuhnCheckDigit()); } public static Generator<Integer> nDigitPositiveInteger(int digits) { checkArgument(digits > 0 && digits < 11, "Number of digits must be between 1 and 10"); int from = (int) pow(10, digits - 1); int to = (int) pow(10, digits); return new RandomPositiveIntegerGenerator(from, to); } public static <F, T> Generator<T> transform(Generator<F> delegate, Function<F, T> transformation) { return new TransformingGenerator<>(delegate, transformation); } public static Generator<String> upperCase(GeneratorOfInstance<String> delegate, Locale locale) { return transform(delegate, toUpperCase(locale)); } public static Generator<String> upperCase(GeneratorOfInstance<String> delegate) { return transform(delegate, toUpperCase()); } public static Generator<String> lowerCase(GeneratorOfInstance<String> delegate) {
// Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<Long, Long> appendLuhnCheckDigit() { // return new LuhnCheckDigitFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toLowerCase() { // return new ToLowerCaseFunction(); // } // // Path: generators-core/src/main/java/io/generators/core/MoreFunctions.java // public static Function<String, String> toUpperCase(@Nonnull Locale locale) { // return new ToUpperCaseFunction(checkNotNull(locale)); // } // Path: generators-core/src/main/java/io/generators/core/Generators.java import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import java.util.List; import java.util.Locale; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static io.generators.core.MoreFunctions.appendLuhnCheckDigit; import static io.generators.core.MoreFunctions.toLowerCase; import static io.generators.core.MoreFunctions.toUpperCase; import static java.lang.Math.pow; /** * Creates Generator that appends Luhn check digit (modulus 10) to the number generated by {@code partialNumberGenerator} * * @param partialAccountNumberGenerator generator of the main part of the card number * @return generator that returns card/account numbers with calculated Luhn check Digit */ public static Generator<Long> cardNumber(Generator<Long> partialAccountNumberGenerator) { return new TransformingGenerator<>(partialAccountNumberGenerator, appendLuhnCheckDigit()); } public static Generator<Integer> nDigitPositiveInteger(int digits) { checkArgument(digits > 0 && digits < 11, "Number of digits must be between 1 and 10"); int from = (int) pow(10, digits - 1); int to = (int) pow(10, digits); return new RandomPositiveIntegerGenerator(from, to); } public static <F, T> Generator<T> transform(Generator<F> delegate, Function<F, T> transformation) { return new TransformingGenerator<>(delegate, transformation); } public static Generator<String> upperCase(GeneratorOfInstance<String> delegate, Locale locale) { return transform(delegate, toUpperCase(locale)); } public static Generator<String> upperCase(GeneratorOfInstance<String> delegate) { return transform(delegate, toUpperCase()); } public static Generator<String> lowerCase(GeneratorOfInstance<String> delegate) {
return transform(delegate, toLowerCase());
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/BroadcastingGeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static Generator<Integer> positiveInts(int from, int to) { // return new RandomPositiveIntegerGenerator(from, to); // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static io.generators.core.Generators.positiveInts; import static java.util.Arrays.asList; import static org.mockito.Mockito.verify;
package io.generators.core; @RunWith(MockitoJUnitRunner.class) public class BroadcastingGeneratorTest { public static final Generator<Integer> NULL_DELEGATE = null; @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private Consumer<Integer> firstConsumer; @Mock private Consumer<Integer> secondConsumer; @Test public void shouldPublishGeneratedValuesToConsumers() { //Given
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static Generator<Integer> positiveInts(int from, int to) { // return new RandomPositiveIntegerGenerator(from, to); // } // Path: generators-core/src/test/java/io/generators/core/BroadcastingGeneratorTest.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static io.generators.core.Generators.positiveInts; import static java.util.Arrays.asList; import static org.mockito.Mockito.verify; package io.generators.core; @RunWith(MockitoJUnitRunner.class) public class BroadcastingGeneratorTest { public static final Generator<Integer> NULL_DELEGATE = null; @Rule public ExpectedException expectedException = ExpectedException.none(); @Mock private Consumer<Integer> firstConsumer; @Mock private Consumer<Integer> secondConsumer; @Test public void shouldPublishGeneratedValuesToConsumers() { //Given
Generator<Integer> generator = new BroadcastingGenerator<>(Generators.positiveInts, firstConsumer, secondConsumer);
generators-io-projects/generators
generators-core/src/main/java/io/generators/core/RandomJodaDateTimeGenerator.java
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // }
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static io.generators.core.Generators.ofInstance; import static org.joda.time.DateTime.now; import javax.annotation.Nonnull; import org.joda.time.DateTime; import org.joda.time.DateTimeZone;
package io.generators.core; /** * Generates random {@link org.joda.time.DateTime} in the time zone of the from date. * <p/> * When no constructor parameters are provided DateTime are generated in range +- 100 years in the default time zone * It also supports generating random DateTime in custom range, future and past DateTimes in cases where from DateTime is not provided it uses default time zone. * Time zone can be explicitly set to desired time zone using {@link #withTimeZone(org.joda.time.DateTimeZone)} * * * @author Tomas Klubal */ public class RandomJodaDateTimeGenerator implements Generator<DateTime> { private static final int YEAR_BOUND = 100; private static final int ZERO_DURAION = 0; private final PositiveLongRandom random = new PositiveLongRandom(); private final Generator<DateTime> from; private final Generator<DateTime> to; private final DateTimeZone timeZone; /** * Created instance generates DateTime in range -+ 100 years in the default time zone * * @see org.joda.time.DateTimeZone#getDefault() */ public RandomJodaDateTimeGenerator() { this(new DurationFromNow(-YEAR_BOUND), new DurationFromNow(+YEAR_BOUND)); } /** * Created instance generates DateTime in range <code>from</code> to <code>to</code> * * @throws IllegalArgumentException when {@code from} is after {@code to} */ public RandomJodaDateTimeGenerator(@Nonnull DateTime from, @Nonnull DateTime to) {
// Path: generators-core/src/main/java/io/generators/core/Generators.java // public static <T> Generator<T> ofInstance(T instance) { // return new GeneratorOfInstance<>(instance); // } // Path: generators-core/src/main/java/io/generators/core/RandomJodaDateTimeGenerator.java import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static io.generators.core.Generators.ofInstance; import static org.joda.time.DateTime.now; import javax.annotation.Nonnull; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; package io.generators.core; /** * Generates random {@link org.joda.time.DateTime} in the time zone of the from date. * <p/> * When no constructor parameters are provided DateTime are generated in range +- 100 years in the default time zone * It also supports generating random DateTime in custom range, future and past DateTimes in cases where from DateTime is not provided it uses default time zone. * Time zone can be explicitly set to desired time zone using {@link #withTimeZone(org.joda.time.DateTimeZone)} * * * @author Tomas Klubal */ public class RandomJodaDateTimeGenerator implements Generator<DateTime> { private static final int YEAR_BOUND = 100; private static final int ZERO_DURAION = 0; private final PositiveLongRandom random = new PositiveLongRandom(); private final Generator<DateTime> from; private final Generator<DateTime> to; private final DateTimeZone timeZone; /** * Created instance generates DateTime in range -+ 100 years in the default time zone * * @see org.joda.time.DateTimeZone#getDefault() */ public RandomJodaDateTimeGenerator() { this(new DurationFromNow(-YEAR_BOUND), new DurationFromNow(+YEAR_BOUND)); } /** * Created instance generates DateTime in range <code>from</code> to <code>to</code> * * @throws IllegalArgumentException when {@code from} is after {@code to} */ public RandomJodaDateTimeGenerator(@Nonnull DateTime from, @Nonnull DateTime to) {
this(ofInstance(from), ofInstance(to));
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/network/IPv4GeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test;
package io.generators.core.network; /** * @author Saket */ public class IPv4GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() {
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // Path: generators-core/src/test/java/io/generators/core/network/IPv4GeneratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test; package io.generators.core.network; /** * @author Saket */ public class IPv4GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() {
Generator<String> generator = new IPv4Generator();
generators-io-projects/generators
generators-core/src/test/java/io/generators/core/network/IPv4GeneratorTest.java
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test;
package io.generators.core.network; /** * @author Saket */ public class IPv4GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() { Generator<String> generator = new IPv4Generator(); for (int i = 0; i < 100; i++) { String ipAddress = generator.next(); assertThatHasValidOctets(ipAddress); } } @Test public void shouldReturnAnIPAddressUsingTheDelegateOctetGenerator() {
// Path: generators-core/src/main/java/io/generators/core/CyclicGenerator.java // public class CyclicGenerator<T> implements Generator<T> { // private final Iterator<T> iterator; // // /** // * Creates generator that cycles over provided {@code first} and {@code rest} elements // * // * @param first first element in the set of elements to cycle over // * @param rest rest of the elements // * @throws java.lang.NullPointerException when first or one of the rest elements is null // */ // @SafeVarargs // public CyclicGenerator(@Nonnull T first, @Nonnull T... rest) { // ImmutableList<T> values = ImmutableList.<T>builder() // .add(first) // .add(rest) // .build(); // // this.iterator = Iterators.cycle(values); // } // // @Override // public T next() { // return iterator.next(); // } // } // // Path: generators-core/src/main/java/io/generators/core/Generator.java // public interface Generator<T> { // // /** // * Returns generated &lt;T&gt; // * // * @return generated <T> // */ // T next(); // } // Path: generators-core/src/test/java/io/generators/core/network/IPv4GeneratorTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import io.generators.core.CyclicGenerator; import io.generators.core.Generator; import org.junit.Test; package io.generators.core.network; /** * @author Saket */ public class IPv4GeneratorTest { @Test public void shouldReturnAnIPAddressWithValidOctets() { Generator<String> generator = new IPv4Generator(); for (int i = 0; i < 100; i++) { String ipAddress = generator.next(); assertThatHasValidOctets(ipAddress); } } @Test public void shouldReturnAnIPAddressUsingTheDelegateOctetGenerator() {
Generator<String> generator = new IPv4Generator(new CyclicGenerator<>(10));
code-not-found/spring-ws
spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/client/OrderHistoryClient.java
// Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/Order.java // public class Order { // // private String orderId; // // public Order(String orderId) { // this.orderId = orderId; // } // // public String getOrderId() { // return orderId; // } // // public void setOrderId(String orderId) { // this.orderId = orderId; // } // // @Override // public String toString() { // return "Order[orderId=" + orderId + "]"; // } // } // // Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/OrderHistory.java // public class OrderHistory { // // private List<Order> orders; // // public List<Order> getOrders() { // return orders; // } // // public void setOrders(List<Order> orders) { // this.orders = orders; // } // }
import java.io.IOException; import java.util.List; import javax.xml.transform.dom.DOMResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.support.MarshallingUtils; import org.springframework.xml.xpath.NodeMapper; import org.springframework.xml.xpath.XPathExpression; import org.w3c.dom.Node; import com.codenotfound.types.orderhistory.GetOrderHistoryRequest; import com.codenotfound.types.orderhistory.ObjectFactory; import com.codenotfound.ws.model.Order; import com.codenotfound.ws.model.OrderHistory;
package com.codenotfound.ws.client; @Component public class OrderHistoryClient { private static final Logger LOGGER = LoggerFactory.getLogger(OrderHistoryClient.class); @Autowired private XPathExpression orderXPath; @Autowired private XPathExpression orderIdXPath; @Autowired private WebServiceTemplate webServiceTemplate;
// Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/Order.java // public class Order { // // private String orderId; // // public Order(String orderId) { // this.orderId = orderId; // } // // public String getOrderId() { // return orderId; // } // // public void setOrderId(String orderId) { // this.orderId = orderId; // } // // @Override // public String toString() { // return "Order[orderId=" + orderId + "]"; // } // } // // Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/OrderHistory.java // public class OrderHistory { // // private List<Order> orders; // // public List<Order> getOrders() { // return orders; // } // // public void setOrders(List<Order> orders) { // this.orders = orders; // } // } // Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/client/OrderHistoryClient.java import java.io.IOException; import java.util.List; import javax.xml.transform.dom.DOMResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.support.MarshallingUtils; import org.springframework.xml.xpath.NodeMapper; import org.springframework.xml.xpath.XPathExpression; import org.w3c.dom.Node; import com.codenotfound.types.orderhistory.GetOrderHistoryRequest; import com.codenotfound.types.orderhistory.ObjectFactory; import com.codenotfound.ws.model.Order; import com.codenotfound.ws.model.OrderHistory; package com.codenotfound.ws.client; @Component public class OrderHistoryClient { private static final Logger LOGGER = LoggerFactory.getLogger(OrderHistoryClient.class); @Autowired private XPathExpression orderXPath; @Autowired private XPathExpression orderIdXPath; @Autowired private WebServiceTemplate webServiceTemplate;
public OrderHistory getOrderHistory(String userId) throws IOException {
code-not-found/spring-ws
spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/client/OrderHistoryClient.java
// Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/Order.java // public class Order { // // private String orderId; // // public Order(String orderId) { // this.orderId = orderId; // } // // public String getOrderId() { // return orderId; // } // // public void setOrderId(String orderId) { // this.orderId = orderId; // } // // @Override // public String toString() { // return "Order[orderId=" + orderId + "]"; // } // } // // Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/OrderHistory.java // public class OrderHistory { // // private List<Order> orders; // // public List<Order> getOrders() { // return orders; // } // // public void setOrders(List<Order> orders) { // this.orders = orders; // } // }
import java.io.IOException; import java.util.List; import javax.xml.transform.dom.DOMResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.support.MarshallingUtils; import org.springframework.xml.xpath.NodeMapper; import org.springframework.xml.xpath.XPathExpression; import org.w3c.dom.Node; import com.codenotfound.types.orderhistory.GetOrderHistoryRequest; import com.codenotfound.types.orderhistory.ObjectFactory; import com.codenotfound.ws.model.Order; import com.codenotfound.ws.model.OrderHistory;
package com.codenotfound.ws.client; @Component public class OrderHistoryClient { private static final Logger LOGGER = LoggerFactory.getLogger(OrderHistoryClient.class); @Autowired private XPathExpression orderXPath; @Autowired private XPathExpression orderIdXPath; @Autowired private WebServiceTemplate webServiceTemplate; public OrderHistory getOrderHistory(String userId) throws IOException { // create the request ObjectFactory factory = new ObjectFactory(); GetOrderHistoryRequest getOrderHistoryRequest = factory.createGetOrderHistoryRequest(); getOrderHistoryRequest.setUserId(userId); // marshal the request WebServiceMessage request = webServiceTemplate.getMessageFactory().createWebServiceMessage(); MarshallingUtils.marshal(webServiceTemplate.getMarshaller(), getOrderHistoryRequest, request); // call the service DOMResult responseResult = new DOMResult(); webServiceTemplate.sendSourceAndReceiveToResult(request.getPayloadSource(), responseResult); // extract the needed elements
// Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/Order.java // public class Order { // // private String orderId; // // public Order(String orderId) { // this.orderId = orderId; // } // // public String getOrderId() { // return orderId; // } // // public void setOrderId(String orderId) { // this.orderId = orderId; // } // // @Override // public String toString() { // return "Order[orderId=" + orderId + "]"; // } // } // // Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/OrderHistory.java // public class OrderHistory { // // private List<Order> orders; // // public List<Order> getOrders() { // return orders; // } // // public void setOrders(List<Order> orders) { // this.orders = orders; // } // } // Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/client/OrderHistoryClient.java import java.io.IOException; import java.util.List; import javax.xml.transform.dom.DOMResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.ws.WebServiceMessage; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.support.MarshallingUtils; import org.springframework.xml.xpath.NodeMapper; import org.springframework.xml.xpath.XPathExpression; import org.w3c.dom.Node; import com.codenotfound.types.orderhistory.GetOrderHistoryRequest; import com.codenotfound.types.orderhistory.ObjectFactory; import com.codenotfound.ws.model.Order; import com.codenotfound.ws.model.OrderHistory; package com.codenotfound.ws.client; @Component public class OrderHistoryClient { private static final Logger LOGGER = LoggerFactory.getLogger(OrderHistoryClient.class); @Autowired private XPathExpression orderXPath; @Autowired private XPathExpression orderIdXPath; @Autowired private WebServiceTemplate webServiceTemplate; public OrderHistory getOrderHistory(String userId) throws IOException { // create the request ObjectFactory factory = new ObjectFactory(); GetOrderHistoryRequest getOrderHistoryRequest = factory.createGetOrderHistoryRequest(); getOrderHistoryRequest.setUserId(userId); // marshal the request WebServiceMessage request = webServiceTemplate.getMessageFactory().createWebServiceMessage(); MarshallingUtils.marshal(webServiceTemplate.getMarshaller(), getOrderHistoryRequest, request); // call the service DOMResult responseResult = new DOMResult(); webServiceTemplate.sendSourceAndReceiveToResult(request.getPayloadSource(), responseResult); // extract the needed elements
List<Order> orders = orderXPath.evaluate(responseResult.getNode(), new NodeMapper<Order>() {
code-not-found/spring-ws
spring-ws-client-timeout/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient;
package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // } // Path: spring-ws-client-timeout/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient; package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
private TicketAgentClient ticketAgentClient;
code-not-found/spring-ws
spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/client/ClientConfig.java
// Path: spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/interceptor/LogHttpHeaderClientInterceptor.java // public class LogHttpHeaderClientInterceptor implements ClientInterceptor { // // @Override // public void afterCompletion(MessageContext arg0, Exception arg1) // throws WebServiceClientException { // // No-op // } // // @Override // public boolean handleFault(MessageContext messageContext) throws WebServiceClientException { // // No-op // return true; // } // // @Override // public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException { // HttpLoggingUtils.logMessage("Client Request Message", messageContext.getRequest()); // // return true; // } // // @Override // public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException { // HttpLoggingUtils.logMessage("Client Response Message", messageContext.getResponse()); // // return true; // } // }
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.client.support.interceptor.ClientInterceptor; import com.codenotfound.ws.interceptor.LogHttpHeaderClientInterceptor;
package com.codenotfound.ws.client; @Configuration public class ClientConfig { @Value("${client.default-uri}") private String defaultUri; @Bean Jaxb2Marshaller jaxb2Marshaller() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setContextPath("org.example.ticketagent"); return jaxb2Marshaller; } @Bean public WebServiceTemplate webServiceTemplate() { WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); webServiceTemplate.setMarshaller(jaxb2Marshaller()); webServiceTemplate.setUnmarshaller(jaxb2Marshaller()); webServiceTemplate.setDefaultUri(defaultUri); // register the LogHttpHeaderClientInterceptor ClientInterceptor[] interceptors =
// Path: spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/interceptor/LogHttpHeaderClientInterceptor.java // public class LogHttpHeaderClientInterceptor implements ClientInterceptor { // // @Override // public void afterCompletion(MessageContext arg0, Exception arg1) // throws WebServiceClientException { // // No-op // } // // @Override // public boolean handleFault(MessageContext messageContext) throws WebServiceClientException { // // No-op // return true; // } // // @Override // public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException { // HttpLoggingUtils.logMessage("Client Request Message", messageContext.getRequest()); // // return true; // } // // @Override // public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException { // HttpLoggingUtils.logMessage("Client Response Message", messageContext.getResponse()); // // return true; // } // } // Path: spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/client/ClientConfig.java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.client.support.interceptor.ClientInterceptor; import com.codenotfound.ws.interceptor.LogHttpHeaderClientInterceptor; package com.codenotfound.ws.client; @Configuration public class ClientConfig { @Value("${client.default-uri}") private String defaultUri; @Bean Jaxb2Marshaller jaxb2Marshaller() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setContextPath("org.example.ticketagent"); return jaxb2Marshaller; } @Bean public WebServiceTemplate webServiceTemplate() { WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); webServiceTemplate.setMarshaller(jaxb2Marshaller()); webServiceTemplate.setUnmarshaller(jaxb2Marshaller()); webServiceTemplate.setDefaultUri(defaultUri); // register the LogHttpHeaderClientInterceptor ClientInterceptor[] interceptors =
new ClientInterceptor[] {new LogHttpHeaderClientInterceptor()};
code-not-found/spring-ws
spring-ws-eureka/spring-ws-ticketagent-client/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient;
package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest public class SpringWsApplicationTests { @Autowired
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // } // Path: spring-ws-eureka/spring-ws-ticketagent-client/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient; package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest public class SpringWsApplicationTests { @Autowired
private TicketAgentClient ticketAgentClient;
code-not-found/spring-ws
spring-ws-hello-world/src/test/java/com/codenotfound/SpringWsApplicationTests.java
// Path: spring-ws-hello-world/src/main/java/com/codenotfound/ws/client/HelloWorldClient.java // @Component // public class HelloWorldClient { // // private static final Logger LOGGER = // LoggerFactory.getLogger(HelloWorldClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // public String sayHello(String firstName, String lastName) { // ObjectFactory factory = new ObjectFactory(); // Person person = factory.createPerson(); // // person.setFirstName(firstName); // person.setLastName(lastName); // // LOGGER.info("Client sending person[firstName={},lastName={}]", // person.getFirstName(), person.getLastName()); // // Greeting greeting = // (Greeting) webServiceTemplate.marshalSendAndReceive(person); // // LOGGER.info("Client received greeting='{}'", // greeting.getGreeting()); // return greeting.getGreeting(); // } // }
import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.HelloWorldClient;
package com.codenotfound; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
// Path: spring-ws-hello-world/src/main/java/com/codenotfound/ws/client/HelloWorldClient.java // @Component // public class HelloWorldClient { // // private static final Logger LOGGER = // LoggerFactory.getLogger(HelloWorldClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // public String sayHello(String firstName, String lastName) { // ObjectFactory factory = new ObjectFactory(); // Person person = factory.createPerson(); // // person.setFirstName(firstName); // person.setLastName(lastName); // // LOGGER.info("Client sending person[firstName={},lastName={}]", // person.getFirstName(), person.getLastName()); // // Greeting greeting = // (Greeting) webServiceTemplate.marshalSendAndReceive(person); // // LOGGER.info("Client received greeting='{}'", // greeting.getGreeting()); // return greeting.getGreeting(); // } // } // Path: spring-ws-hello-world/src/test/java/com/codenotfound/SpringWsApplicationTests.java import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.HelloWorldClient; package com.codenotfound; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
private HelloWorldClient helloWorldClient;
code-not-found/spring-ws
spring-ws-timeout-httpclient/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient;
package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // } // Path: spring-ws-timeout-httpclient/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient; package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
private TicketAgentClient ticketAgentClient;
code-not-found/spring-ws
spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/endpoint/WebServiceConfig.java
// Path: spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/interceptor/LogHttpHeaderEndpointInterceptor.java // public class LogHttpHeaderEndpointInterceptor implements EndpointInterceptor { // // @Override // public void afterCompletion(MessageContext arg0, Object arg1, Exception arg2) throws Exception { // // No-op // } // // @Override // public boolean handleFault(MessageContext messageContext, Object arg1) throws Exception { // // No-op // return true; // } // // @Override // public boolean handleRequest(MessageContext messageContext, Object arg1) throws Exception { // HttpLoggingUtils.logMessage("Server Request Message", messageContext.getRequest()); // // return true; // } // // @Override // public boolean handleResponse(MessageContext messageContext, Object arg1) throws Exception { // HttpLoggingUtils.logMessage("Server Response Message", messageContext.getResponse()); // // return true; // } // }
import java.util.List; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.ws.config.annotation.EnableWs; import org.springframework.ws.config.annotation.WsConfigurerAdapter; import org.springframework.ws.server.EndpointInterceptor; import org.springframework.ws.transport.http.MessageDispatcherServlet; import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition; import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition; import com.codenotfound.ws.interceptor.LogHttpHeaderEndpointInterceptor;
package com.codenotfound.ws.endpoint; @EnableWs @Configuration public class WebServiceConfig extends WsConfigurerAdapter { @Bean public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) { MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(applicationContext); return new ServletRegistrationBean(servlet, "/codenotfound/ws/*"); } @Bean(name = "ticketagent") public Wsdl11Definition defaultWsdl11Definition() { SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition(); wsdl11Definition.setWsdl(new ClassPathResource("/wsdl/ticketagent.wsdl")); return wsdl11Definition; } @Override public void addInterceptors(List<EndpointInterceptor> interceptors) { // register the LogHttpHeaderEndpointInterceptor
// Path: spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/interceptor/LogHttpHeaderEndpointInterceptor.java // public class LogHttpHeaderEndpointInterceptor implements EndpointInterceptor { // // @Override // public void afterCompletion(MessageContext arg0, Object arg1, Exception arg2) throws Exception { // // No-op // } // // @Override // public boolean handleFault(MessageContext messageContext, Object arg1) throws Exception { // // No-op // return true; // } // // @Override // public boolean handleRequest(MessageContext messageContext, Object arg1) throws Exception { // HttpLoggingUtils.logMessage("Server Request Message", messageContext.getRequest()); // // return true; // } // // @Override // public boolean handleResponse(MessageContext messageContext, Object arg1) throws Exception { // HttpLoggingUtils.logMessage("Server Response Message", messageContext.getResponse()); // // return true; // } // } // Path: spring-ws-log-http-headers/src/main/java/com/codenotfound/ws/endpoint/WebServiceConfig.java import java.util.List; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.ws.config.annotation.EnableWs; import org.springframework.ws.config.annotation.WsConfigurerAdapter; import org.springframework.ws.server.EndpointInterceptor; import org.springframework.ws.transport.http.MessageDispatcherServlet; import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition; import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition; import com.codenotfound.ws.interceptor.LogHttpHeaderEndpointInterceptor; package com.codenotfound.ws.endpoint; @EnableWs @Configuration public class WebServiceConfig extends WsConfigurerAdapter { @Bean public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) { MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(applicationContext); return new ServletRegistrationBean(servlet, "/codenotfound/ws/*"); } @Bean(name = "ticketagent") public Wsdl11Definition defaultWsdl11Definition() { SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition(); wsdl11Definition.setWsdl(new ClassPathResource("/wsdl/ticketagent.wsdl")); return wsdl11Definition; } @Override public void addInterceptors(List<EndpointInterceptor> interceptors) { // register the LogHttpHeaderEndpointInterceptor
interceptors.add(new LogHttpHeaderEndpointInterceptor());
code-not-found/spring-ws
spring-ws-wsdl-url-redirect/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient;
package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
// Path: spring-ws-timeout-httpclient/src/main/java/com/codenotfound/ws/client/TicketAgentClient.java // @Component // public class TicketAgentClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(TicketAgentClient.class); // // @Autowired // private WebServiceTemplate webServiceTemplate; // // @SuppressWarnings("unchecked") // public List<BigInteger> listFlights() { // ObjectFactory factory = new ObjectFactory(); // TListFlights tListFlights = factory.createTListFlights(); // // JAXBElement<TListFlights> request = factory.createListFlightsRequest(tListFlights); // JAXBElement<TFlightsResponse> response = null; // // try { // response = (JAXBElement<TFlightsResponse>) webServiceTemplate.marshalSendAndReceive(request); // return response.getValue().getFlightNumber(); // } catch (Exception e) { // LOGGER.error(e.getMessage()); // // TODO handle the exception // return new ArrayList<>(); // } // } // } // Path: spring-ws-wsdl-url-redirect/src/test/java/com/codenotfound/ws/SpringWsApplicationTests.java import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.codenotfound.ws.client.TicketAgentClient; package com.codenotfound.ws; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) public class SpringWsApplicationTests { @Autowired
private TicketAgentClient ticketAgentClient;
code-not-found/spring-ws
spring-ws-tolerant-reader/src/test/java/com/codenotfound/ws/client/OrderHistoryClientTest.java
// Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/OrderHistory.java // public class OrderHistory { // // private List<Order> orders; // // public List<Order> getOrders() { // return orders; // } // // public void setOrders(List<Order> orders) { // this.orders = orders; // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.ws.test.client.RequestMatchers.payload; import static org.springframework.ws.test.client.ResponseCreators.withPayload; import java.io.IOException; import javax.xml.transform.Source; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.test.client.MockWebServiceServer; import org.springframework.xml.transform.StringSource; import com.codenotfound.ws.model.OrderHistory;
package com.codenotfound.ws.client; @RunWith(SpringRunner.class) @SpringBootTest public class OrderHistoryClientTest { @Autowired private OrderHistoryClient orderHistoryClient; @Autowired private WebServiceTemplate webServiceTemplate; private MockWebServiceServer mockWebServiceServer; @Before public void createServer() { mockWebServiceServer = MockWebServiceServer.createServer(webServiceTemplate); } @Test public void testGetOrderHistory() throws IOException { Source requestPayload = new StringSource( "<ns1:getOrderHistoryRequest xmlns:ns1=\"http://codenotfound.com/types/orderhistory\">" + "<ns1:userId>abc123</ns1:userId>" + "</ns1:getOrderHistoryRequest>"); Source responsePayload = new StringSource( "<ns1:getOrderHistoryResponse xmlns:ns1=\"http://codenotfound.com/types/orderhistory\">" + "<ns1:orderHistory>" + "<ns1:orderList>" + "<ns1:order><ns1:orderId>order1</ns1:orderId></ns1:order>" + "<ns1:order><ns1:orderId>order2</ns1:orderId></ns1:order>" + "<ns1:order><ns1:orderId>order3</ns1:orderId></ns1:order>" + "</ns1:orderList>" + "</ns1:orderHistory>" + "</ns1:getOrderHistoryResponse>"); mockWebServiceServer.expect(payload(requestPayload)).andRespond(withPayload(responsePayload));
// Path: spring-ws-tolerant-reader/src/main/java/com/codenotfound/ws/model/OrderHistory.java // public class OrderHistory { // // private List<Order> orders; // // public List<Order> getOrders() { // return orders; // } // // public void setOrders(List<Order> orders) { // this.orders = orders; // } // } // Path: spring-ws-tolerant-reader/src/test/java/com/codenotfound/ws/client/OrderHistoryClientTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.ws.test.client.RequestMatchers.payload; import static org.springframework.ws.test.client.ResponseCreators.withPayload; import java.io.IOException; import javax.xml.transform.Source; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.ws.client.core.WebServiceTemplate; import org.springframework.ws.test.client.MockWebServiceServer; import org.springframework.xml.transform.StringSource; import com.codenotfound.ws.model.OrderHistory; package com.codenotfound.ws.client; @RunWith(SpringRunner.class) @SpringBootTest public class OrderHistoryClientTest { @Autowired private OrderHistoryClient orderHistoryClient; @Autowired private WebServiceTemplate webServiceTemplate; private MockWebServiceServer mockWebServiceServer; @Before public void createServer() { mockWebServiceServer = MockWebServiceServer.createServer(webServiceTemplate); } @Test public void testGetOrderHistory() throws IOException { Source requestPayload = new StringSource( "<ns1:getOrderHistoryRequest xmlns:ns1=\"http://codenotfound.com/types/orderhistory\">" + "<ns1:userId>abc123</ns1:userId>" + "</ns1:getOrderHistoryRequest>"); Source responsePayload = new StringSource( "<ns1:getOrderHistoryResponse xmlns:ns1=\"http://codenotfound.com/types/orderhistory\">" + "<ns1:orderHistory>" + "<ns1:orderList>" + "<ns1:order><ns1:orderId>order1</ns1:orderId></ns1:order>" + "<ns1:order><ns1:orderId>order2</ns1:orderId></ns1:order>" + "<ns1:order><ns1:orderId>order3</ns1:orderId></ns1:order>" + "</ns1:orderList>" + "</ns1:orderHistory>" + "</ns1:getOrderHistoryResponse>"); mockWebServiceServer.expect(payload(requestPayload)).andRespond(withPayload(responsePayload));
OrderHistory orderHistory = orderHistoryClient.getOrderHistory("abc123");
greensopinion/swagger-jaxrs-maven
src/main/java/com/greensopinion/swagger/jaxrsgen/model/ServiceOperation.java
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/MoreObjects.java // public class MoreObjects { // // public static <T> T firstNonNull(T first, T second) { // return first == null ? second : first; // } // }
import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.gson.annotations.SerializedName; import com.greensopinion.swagger.jaxrsgen.MoreObjects;
} public Set<Class<?>> getModelClasses() { Set<Class<?>> modelClasses = Sets.newHashSet(); if (returnType != null && ApiTypes.isModelClass(returnType)) { modelClasses.add(ApiTypes.modelClass(returnType)); } for (Parameter parameter : getParameters()) { if (parameter.getTypeClass() != null && ApiTypes.isModelClass(parameter.getTypeClass())) { modelClasses.add(ApiTypes.modelClass(parameter.getTypeClass())); } } for (ResponseMessage responseMessage : getResponseMessages()) { if (responseMessage.getTypeClass() != null && ApiTypes.isModelClass(responseMessage.getTypeClass())) { modelClasses.add(ApiTypes.modelClass(responseMessage.getTypeClass())); } } return ImmutableSet.copyOf(modelClasses); } public static ServiceOperationBuilder builder() { return new ServiceOperationBuilder(); } @Override public int compareTo(ServiceOperation o) { return compareString().compareTo(o.compareString()); } private String compareString() {
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/MoreObjects.java // public class MoreObjects { // // public static <T> T firstNonNull(T first, T second) { // return first == null ? second : first; // } // } // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/ServiceOperation.java import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.gson.annotations.SerializedName; import com.greensopinion.swagger.jaxrsgen.MoreObjects; } public Set<Class<?>> getModelClasses() { Set<Class<?>> modelClasses = Sets.newHashSet(); if (returnType != null && ApiTypes.isModelClass(returnType)) { modelClasses.add(ApiTypes.modelClass(returnType)); } for (Parameter parameter : getParameters()) { if (parameter.getTypeClass() != null && ApiTypes.isModelClass(parameter.getTypeClass())) { modelClasses.add(ApiTypes.modelClass(parameter.getTypeClass())); } } for (ResponseMessage responseMessage : getResponseMessages()) { if (responseMessage.getTypeClass() != null && ApiTypes.isModelClass(responseMessage.getTypeClass())) { modelClasses.add(ApiTypes.modelClass(responseMessage.getTypeClass())); } } return ImmutableSet.copyOf(modelClasses); } public static ServiceOperationBuilder builder() { return new ServiceOperationBuilder(); } @Override public int compareTo(ServiceOperation o) { return compareString().compareTo(o.compareString()); } private String compareString() {
return Joiner.on(";;").join(httpMethod, path, MoreObjects.firstNonNull(nickname, ""),
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/model/Pet.java // public class Pet extends PetValues { // // @ApiModelProperty(required = true) // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // }
import java.util.List; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.greensopinion.swagger.jaxrsgen.mock.model.Pet;
/******************************************************************************* * Copyright (c) 2017 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock; @Path("/bodyWithGenericTypeParameter") public class ServiceWithBodyHavingGenericTypeParameter { @POST
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/model/Pet.java // public class Pet extends PetValues { // // @ApiModelProperty(required = true) // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java import java.util.List; import javax.ws.rs.POST; import javax.ws.rs.Path; import com.greensopinion.swagger.jaxrsgen.mock.model.Pet; /******************************************************************************* * Copyright (c) 2017 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock; @Path("/bodyWithGenericTypeParameter") public class ServiceWithBodyHavingGenericTypeParameter { @POST
public void get(List<Pet> pets) {
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/model/PetListing.java // @ApiModel(description = "A listing of pets") // public class PetListing { // // @ApiModelProperty("The 0-based start index offset.") // private final int start; // // @ApiModelProperty("The number of pets requested. May differ from the actual number of pets in the listing.") // private final int count; // // @ApiModelProperty("The total number of pets in the system that correspond to the listing.") // private final int total; // // @ApiModelProperty("The list of pet handles.") // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // }
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import com.greensopinion.swagger.jaxrsgen.mock.model.PetListing; import io.swagger.annotations.ApiOperation;
/******************************************************************************* * Copyright (c) 2015, 2016 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock; @Path("/pets") public class ServiceWithResponseReturnType { @GET
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/model/PetListing.java // @ApiModel(description = "A listing of pets") // public class PetListing { // // @ApiModelProperty("The 0-based start index offset.") // private final int start; // // @ApiModelProperty("The number of pets requested. May differ from the actual number of pets in the listing.") // private final int count; // // @ApiModelProperty("The total number of pets in the system that correspond to the listing.") // private final int total; // // @ApiModelProperty("The list of pet handles.") // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import com.greensopinion.swagger.jaxrsgen.mock.model.PetListing; import io.swagger.annotations.ApiOperation; /******************************************************************************* * Copyright (c) 2015, 2016 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock; @Path("/pets") public class ServiceWithResponseReturnType { @GET
@ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class)
greensopinion/swagger-jaxrs-maven
src/main/java/com/greensopinion/swagger/jaxrsgen/model/ApiTypes.java
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/MoreObjects.java // public class MoreObjects { // // public static <T> T firstNonNull(T first, T second) { // return first == null ? second : first; // } // }
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.URI; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.greensopinion.swagger.jaxrsgen.MoreObjects; import io.swagger.annotations.ApiModel;
&& !clazz.getPackage().getName().startsWith("com.sun.jersey.multipart"); } public static Map<String, String> calculateArrayItems(Class<?> parameterType, Type genericType) { Map<String, String> arrayItems; if (parameterType.isArray()) { String key = isModelClass(parameterType.getComponentType()) ? "$ref" : "type"; arrayItems = ImmutableMap.of(key, ApiTypes.calculateTypeName(parameterType.getComponentType())); } else if (Collection.class.isAssignableFrom(parameterType)) { String key = isModelClass(typeArgument(genericType)) ? "$ref" : "type"; arrayItems = ImmutableMap.of(key, ApiTypes.calculateTypeParameterName(genericType)); } else { return null; } return arrayItems; } public static String calculateTypeName(Class<?> parameterType) { String typeName = typeNameByClass.get(parameterType); if (typeName != null) { return typeName; } if (parameterType.isPrimitive() || parameterType.getPackage().getName().equals("java.lang")) { return "string"; } if (parameterType.getName().equals("com.sun.jersey.multipart.MultiPart")) { return "File"; } ApiModel apiModel = parameterType.getAnnotation(ApiModel.class); typeName = apiModel == null ? null : Strings.emptyToNull(apiModel.value());
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/MoreObjects.java // public class MoreObjects { // // public static <T> T firstNonNull(T first, T second) { // return first == null ? second : first; // } // } // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/ApiTypes.java import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.URI; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.greensopinion.swagger.jaxrsgen.MoreObjects; import io.swagger.annotations.ApiModel; && !clazz.getPackage().getName().startsWith("com.sun.jersey.multipart"); } public static Map<String, String> calculateArrayItems(Class<?> parameterType, Type genericType) { Map<String, String> arrayItems; if (parameterType.isArray()) { String key = isModelClass(parameterType.getComponentType()) ? "$ref" : "type"; arrayItems = ImmutableMap.of(key, ApiTypes.calculateTypeName(parameterType.getComponentType())); } else if (Collection.class.isAssignableFrom(parameterType)) { String key = isModelClass(typeArgument(genericType)) ? "$ref" : "type"; arrayItems = ImmutableMap.of(key, ApiTypes.calculateTypeParameterName(genericType)); } else { return null; } return arrayItems; } public static String calculateTypeName(Class<?> parameterType) { String typeName = typeNameByClass.get(parameterType); if (typeName != null) { return typeName; } if (parameterType.isPrimitive() || parameterType.getPackage().getName().equals("java.lang")) { return "string"; } if (parameterType.getName().equals("com.sun.jersey.multipart.MultiPart")) { return "File"; } ApiModel apiModel = parameterType.getAnnotation(ApiModel.class); typeName = apiModel == null ? null : Strings.emptyToNull(apiModel.value());
return MoreObjects.firstNonNull(typeName, parameterType.getSimpleName());
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/model/ServiceTest.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/PetService.java // @Path("pet") // @Api(value = "/pet", description = "Operations about pets") // @Produces(MediaType.APPLICATION_JSON) // public class PetService { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public PetListing list(@QueryParam("start") @DefaultValue("0") int start, // @QueryParam("count") @DefaultValue("50") int count, // @QueryParam("superSecretParam") @ApiParam(hidden = true) String superSecretParam) { // return null; // } // // @GET // @Path("{id}") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Pet retrievePet(@PathParam("id") long id) { // return null; // } // // @GET // @Path("{id}/properties") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id with specified properties.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Map<String, Object> retrievePet(@PathParam("id") long id, // @QueryParam("properties") List<String> properties) { // return null; // } // // @DELETE // @Path("/{id}") // @ApiOperation(value = "Delete pet by id", notes = "Deletes a pet by it's id.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void deletePet(@PathParam("id") long id) { // } // // @PUT // @ApiOperation(value = "Creates a new pet", notes = "Creates a new pet with the given name.", response = PetHandle.class) // public PetHandle createPet(PetValues petValues) { // return null; // } // // @POST // @Path("{id}") // @Produces(MediaType.APPLICATION_JSON) // @ApiOperation(value = "Updates a pet", notes = "Updates an existing pet with the provided details.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void updatePet(Pet pet, @PathParam("id") long id) { // } // // @POST // @Path("{id}/photo") // @Consumes(MediaType.MULTIPART_FORM_DATA) // @ApiOperation(value = "Provides a pet photo", notes = "Updates an existing pet entry with a new photo of the pet.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void postPetPhoto(@PathParam("id") long id, MultiPart multiPart) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java // @Path("/bodyWithGenericTypeParameter") // public class ServiceWithBodyHavingGenericTypeParameter { // // @POST // public void get(List<Pet> pets) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java // @Path("/pets") // public class ServiceWithResponseReturnType { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public Response listPets() { // throw new UnsupportedOperationException(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.google.gson.GsonBuilder; import com.greensopinion.swagger.jaxrsgen.mock.PetService; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithBodyHavingGenericTypeParameter; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithResponseReturnType;
/******************************************************************************* * Copyright (c) 2014, 2016 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.model; public class ServiceTest { @Test public void serializedForm() { Service service = Service.builder() .basePath("/api/latest") .path("/pets/{petId}") .description("Operations about pets") .version("1.0.1")
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/PetService.java // @Path("pet") // @Api(value = "/pet", description = "Operations about pets") // @Produces(MediaType.APPLICATION_JSON) // public class PetService { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public PetListing list(@QueryParam("start") @DefaultValue("0") int start, // @QueryParam("count") @DefaultValue("50") int count, // @QueryParam("superSecretParam") @ApiParam(hidden = true) String superSecretParam) { // return null; // } // // @GET // @Path("{id}") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Pet retrievePet(@PathParam("id") long id) { // return null; // } // // @GET // @Path("{id}/properties") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id with specified properties.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Map<String, Object> retrievePet(@PathParam("id") long id, // @QueryParam("properties") List<String> properties) { // return null; // } // // @DELETE // @Path("/{id}") // @ApiOperation(value = "Delete pet by id", notes = "Deletes a pet by it's id.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void deletePet(@PathParam("id") long id) { // } // // @PUT // @ApiOperation(value = "Creates a new pet", notes = "Creates a new pet with the given name.", response = PetHandle.class) // public PetHandle createPet(PetValues petValues) { // return null; // } // // @POST // @Path("{id}") // @Produces(MediaType.APPLICATION_JSON) // @ApiOperation(value = "Updates a pet", notes = "Updates an existing pet with the provided details.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void updatePet(Pet pet, @PathParam("id") long id) { // } // // @POST // @Path("{id}/photo") // @Consumes(MediaType.MULTIPART_FORM_DATA) // @ApiOperation(value = "Provides a pet photo", notes = "Updates an existing pet entry with a new photo of the pet.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void postPetPhoto(@PathParam("id") long id, MultiPart multiPart) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java // @Path("/bodyWithGenericTypeParameter") // public class ServiceWithBodyHavingGenericTypeParameter { // // @POST // public void get(List<Pet> pets) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java // @Path("/pets") // public class ServiceWithResponseReturnType { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public Response listPets() { // throw new UnsupportedOperationException(); // } // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/model/ServiceTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.google.gson.GsonBuilder; import com.greensopinion.swagger.jaxrsgen.mock.PetService; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithBodyHavingGenericTypeParameter; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithResponseReturnType; /******************************************************************************* * Copyright (c) 2014, 2016 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.model; public class ServiceTest { @Test public void serializedForm() { Service service = Service.builder() .basePath("/api/latest") .path("/pets/{petId}") .description("Operations about pets") .version("1.0.1")
.methods(PetService.class)
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/model/ServiceTest.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/PetService.java // @Path("pet") // @Api(value = "/pet", description = "Operations about pets") // @Produces(MediaType.APPLICATION_JSON) // public class PetService { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public PetListing list(@QueryParam("start") @DefaultValue("0") int start, // @QueryParam("count") @DefaultValue("50") int count, // @QueryParam("superSecretParam") @ApiParam(hidden = true) String superSecretParam) { // return null; // } // // @GET // @Path("{id}") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Pet retrievePet(@PathParam("id") long id) { // return null; // } // // @GET // @Path("{id}/properties") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id with specified properties.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Map<String, Object> retrievePet(@PathParam("id") long id, // @QueryParam("properties") List<String> properties) { // return null; // } // // @DELETE // @Path("/{id}") // @ApiOperation(value = "Delete pet by id", notes = "Deletes a pet by it's id.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void deletePet(@PathParam("id") long id) { // } // // @PUT // @ApiOperation(value = "Creates a new pet", notes = "Creates a new pet with the given name.", response = PetHandle.class) // public PetHandle createPet(PetValues petValues) { // return null; // } // // @POST // @Path("{id}") // @Produces(MediaType.APPLICATION_JSON) // @ApiOperation(value = "Updates a pet", notes = "Updates an existing pet with the provided details.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void updatePet(Pet pet, @PathParam("id") long id) { // } // // @POST // @Path("{id}/photo") // @Consumes(MediaType.MULTIPART_FORM_DATA) // @ApiOperation(value = "Provides a pet photo", notes = "Updates an existing pet entry with a new photo of the pet.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void postPetPhoto(@PathParam("id") long id, MultiPart multiPart) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java // @Path("/bodyWithGenericTypeParameter") // public class ServiceWithBodyHavingGenericTypeParameter { // // @POST // public void get(List<Pet> pets) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java // @Path("/pets") // public class ServiceWithResponseReturnType { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public Response listPets() { // throw new UnsupportedOperationException(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.google.gson.GsonBuilder; import com.greensopinion.swagger.jaxrsgen.mock.PetService; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithBodyHavingGenericTypeParameter; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithResponseReturnType;
/******************************************************************************* * Copyright (c) 2014, 2016 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.model; public class ServiceTest { @Test public void serializedForm() { Service service = Service.builder() .basePath("/api/latest") .path("/pets/{petId}") .description("Operations about pets") .version("1.0.1") .methods(PetService.class) .create(); assertNotNull(service); String json = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(service); assertEquals(TestResources.read(ServiceTest.class, "serializedForm.json"), json); } @Test public void serviceWithResponseReturnType() { Service service = Service.builder() .basePath("/api/latest") .path("/apath") .version("1.0.1")
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/PetService.java // @Path("pet") // @Api(value = "/pet", description = "Operations about pets") // @Produces(MediaType.APPLICATION_JSON) // public class PetService { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public PetListing list(@QueryParam("start") @DefaultValue("0") int start, // @QueryParam("count") @DefaultValue("50") int count, // @QueryParam("superSecretParam") @ApiParam(hidden = true) String superSecretParam) { // return null; // } // // @GET // @Path("{id}") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Pet retrievePet(@PathParam("id") long id) { // return null; // } // // @GET // @Path("{id}/properties") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id with specified properties.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Map<String, Object> retrievePet(@PathParam("id") long id, // @QueryParam("properties") List<String> properties) { // return null; // } // // @DELETE // @Path("/{id}") // @ApiOperation(value = "Delete pet by id", notes = "Deletes a pet by it's id.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void deletePet(@PathParam("id") long id) { // } // // @PUT // @ApiOperation(value = "Creates a new pet", notes = "Creates a new pet with the given name.", response = PetHandle.class) // public PetHandle createPet(PetValues petValues) { // return null; // } // // @POST // @Path("{id}") // @Produces(MediaType.APPLICATION_JSON) // @ApiOperation(value = "Updates a pet", notes = "Updates an existing pet with the provided details.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void updatePet(Pet pet, @PathParam("id") long id) { // } // // @POST // @Path("{id}/photo") // @Consumes(MediaType.MULTIPART_FORM_DATA) // @ApiOperation(value = "Provides a pet photo", notes = "Updates an existing pet entry with a new photo of the pet.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void postPetPhoto(@PathParam("id") long id, MultiPart multiPart) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java // @Path("/bodyWithGenericTypeParameter") // public class ServiceWithBodyHavingGenericTypeParameter { // // @POST // public void get(List<Pet> pets) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java // @Path("/pets") // public class ServiceWithResponseReturnType { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public Response listPets() { // throw new UnsupportedOperationException(); // } // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/model/ServiceTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.google.gson.GsonBuilder; import com.greensopinion.swagger.jaxrsgen.mock.PetService; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithBodyHavingGenericTypeParameter; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithResponseReturnType; /******************************************************************************* * Copyright (c) 2014, 2016 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.model; public class ServiceTest { @Test public void serializedForm() { Service service = Service.builder() .basePath("/api/latest") .path("/pets/{petId}") .description("Operations about pets") .version("1.0.1") .methods(PetService.class) .create(); assertNotNull(service); String json = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(service); assertEquals(TestResources.read(ServiceTest.class, "serializedForm.json"), json); } @Test public void serviceWithResponseReturnType() { Service service = Service.builder() .basePath("/api/latest") .path("/apath") .version("1.0.1")
.methods(ServiceWithResponseReturnType.class)
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/model/ServiceTest.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/PetService.java // @Path("pet") // @Api(value = "/pet", description = "Operations about pets") // @Produces(MediaType.APPLICATION_JSON) // public class PetService { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public PetListing list(@QueryParam("start") @DefaultValue("0") int start, // @QueryParam("count") @DefaultValue("50") int count, // @QueryParam("superSecretParam") @ApiParam(hidden = true) String superSecretParam) { // return null; // } // // @GET // @Path("{id}") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Pet retrievePet(@PathParam("id") long id) { // return null; // } // // @GET // @Path("{id}/properties") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id with specified properties.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Map<String, Object> retrievePet(@PathParam("id") long id, // @QueryParam("properties") List<String> properties) { // return null; // } // // @DELETE // @Path("/{id}") // @ApiOperation(value = "Delete pet by id", notes = "Deletes a pet by it's id.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void deletePet(@PathParam("id") long id) { // } // // @PUT // @ApiOperation(value = "Creates a new pet", notes = "Creates a new pet with the given name.", response = PetHandle.class) // public PetHandle createPet(PetValues petValues) { // return null; // } // // @POST // @Path("{id}") // @Produces(MediaType.APPLICATION_JSON) // @ApiOperation(value = "Updates a pet", notes = "Updates an existing pet with the provided details.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void updatePet(Pet pet, @PathParam("id") long id) { // } // // @POST // @Path("{id}/photo") // @Consumes(MediaType.MULTIPART_FORM_DATA) // @ApiOperation(value = "Provides a pet photo", notes = "Updates an existing pet entry with a new photo of the pet.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void postPetPhoto(@PathParam("id") long id, MultiPart multiPart) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java // @Path("/bodyWithGenericTypeParameter") // public class ServiceWithBodyHavingGenericTypeParameter { // // @POST // public void get(List<Pet> pets) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java // @Path("/pets") // public class ServiceWithResponseReturnType { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public Response listPets() { // throw new UnsupportedOperationException(); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.google.gson.GsonBuilder; import com.greensopinion.swagger.jaxrsgen.mock.PetService; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithBodyHavingGenericTypeParameter; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithResponseReturnType;
.description("Operations about pets") .version("1.0.1") .methods(PetService.class) .create(); assertNotNull(service); String json = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(service); assertEquals(TestResources.read(ServiceTest.class, "serializedForm.json"), json); } @Test public void serviceWithResponseReturnType() { Service service = Service.builder() .basePath("/api/latest") .path("/apath") .version("1.0.1") .methods(ServiceWithResponseReturnType.class) .create(); assertNotNull(service); String json = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(service); assertEquals(TestResources.read(ServiceTest.class, "serviceWithResponseReturnType.json"), json); } @Test public void serviceWithBodyHavingGenericTypeParameter() { Service service = Service.builder() .basePath("/api/latest") .path("/apath") .version("1.0.1")
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/PetService.java // @Path("pet") // @Api(value = "/pet", description = "Operations about pets") // @Produces(MediaType.APPLICATION_JSON) // public class PetService { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public PetListing list(@QueryParam("start") @DefaultValue("0") int start, // @QueryParam("count") @DefaultValue("50") int count, // @QueryParam("superSecretParam") @ApiParam(hidden = true) String superSecretParam) { // return null; // } // // @GET // @Path("{id}") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Pet retrievePet(@PathParam("id") long id) { // return null; // } // // @GET // @Path("{id}/properties") // @ApiOperation(value = "Retrieve pet by id", notes = "Retrieves a pet by it's id with specified properties.", response = Pet.class) // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public Map<String, Object> retrievePet(@PathParam("id") long id, // @QueryParam("properties") List<String> properties) { // return null; // } // // @DELETE // @Path("/{id}") // @ApiOperation(value = "Delete pet by id", notes = "Deletes a pet by it's id.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void deletePet(@PathParam("id") long id) { // } // // @PUT // @ApiOperation(value = "Creates a new pet", notes = "Creates a new pet with the given name.", response = PetHandle.class) // public PetHandle createPet(PetValues petValues) { // return null; // } // // @POST // @Path("{id}") // @Produces(MediaType.APPLICATION_JSON) // @ApiOperation(value = "Updates a pet", notes = "Updates an existing pet with the provided details.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void updatePet(Pet pet, @PathParam("id") long id) { // } // // @POST // @Path("{id}/photo") // @Consumes(MediaType.MULTIPART_FORM_DATA) // @ApiOperation(value = "Provides a pet photo", notes = "Updates an existing pet entry with a new photo of the pet.") // @ApiResponses(value = { @ApiResponse(code = 404, message = "Pet not found", response = ServerError.class) }) // public void postPetPhoto(@PathParam("id") long id, MultiPart multiPart) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithBodyHavingGenericTypeParameter.java // @Path("/bodyWithGenericTypeParameter") // public class ServiceWithBodyHavingGenericTypeParameter { // // @POST // public void get(List<Pet> pets) { // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/ServiceWithResponseReturnType.java // @Path("/pets") // public class ServiceWithResponseReturnType { // // @GET // @ApiOperation(value = "List all pets", notes = "List all pets. Results are paginated.", response = PetListing.class) // public Response listPets() { // throw new UnsupportedOperationException(); // } // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/model/ServiceTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.google.gson.GsonBuilder; import com.greensopinion.swagger.jaxrsgen.mock.PetService; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithBodyHavingGenericTypeParameter; import com.greensopinion.swagger.jaxrsgen.mock.ServiceWithResponseReturnType; .description("Operations about pets") .version("1.0.1") .methods(PetService.class) .create(); assertNotNull(service); String json = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(service); assertEquals(TestResources.read(ServiceTest.class, "serializedForm.json"), json); } @Test public void serviceWithResponseReturnType() { Service service = Service.builder() .basePath("/api/latest") .path("/apath") .version("1.0.1") .methods(ServiceWithResponseReturnType.class) .create(); assertNotNull(service); String json = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(service); assertEquals(TestResources.read(ServiceTest.class, "serviceWithResponseReturnType.json"), json); } @Test public void serviceWithBodyHavingGenericTypeParameter() { Service service = Service.builder() .basePath("/api/latest") .path("/apath") .version("1.0.1")
.methods(ServiceWithBodyHavingGenericTypeParameter.class)
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/SwaggerJaxrsGeneratorMojoTest.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/model/TestResources.java // public class TestResources { // // public static String read(Class<?> clazz, String resource) { // String filename = clazz.getSimpleName() + "_" + resource; // try (InputStream stream = clazz.getResourceAsStream(filename)) { // checkNotNull(stream, "Cannot load resource: %s", filename); // return CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8)); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import java.io.File; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.greensopinion.swagger.jaxrsgen.model.TestResources;
/******************************************************************************* * Copyright (c) 2017 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen; public class SwaggerJaxrsGeneratorMojoTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void generate() throws MojoExecutionException, MojoFailureException { SwaggerJaxrsGeneratorMojo mojo = new SwaggerJaxrsGeneratorMojo(); mojo.apiVersion = "1.0.0"; mojo.outputFolder = temporaryFolder.getRoot(); mojo.packageNames = ImmutableList.of("com.greensopinion.swagger.jaxrsgen.mock"); mojo.mavenProject = mockMavenProject(); mojo.execute(); File apiDocs = new File(temporaryFolder.getRoot(), "api-docs"); assertThat(apiDocs).exists(); assertThat(apiDocs).isDirectory(); assertFileWithContent("index.json", new File(apiDocs, "index.json")); assertFileWithContent("pets.json", new File(new File(apiDocs, "pets"), "index.json")); } private void assertFileWithContent(String resource, File file) { assertThat(file).exists(); assertThat(file).isFile();
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/model/TestResources.java // public class TestResources { // // public static String read(Class<?> clazz, String resource) { // String filename = clazz.getSimpleName() + "_" + resource; // try (InputStream stream = clazz.getResourceAsStream(filename)) { // checkNotNull(stream, "Cannot load resource: %s", filename); // return CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8)); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/SwaggerJaxrsGeneratorMojoTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import java.io.File; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.greensopinion.swagger.jaxrsgen.model.TestResources; /******************************************************************************* * Copyright (c) 2017 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen; public class SwaggerJaxrsGeneratorMojoTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void generate() throws MojoExecutionException, MojoFailureException { SwaggerJaxrsGeneratorMojo mojo = new SwaggerJaxrsGeneratorMojo(); mojo.apiVersion = "1.0.0"; mojo.outputFolder = temporaryFolder.getRoot(); mojo.packageNames = ImmutableList.of("com.greensopinion.swagger.jaxrsgen.mock"); mojo.mavenProject = mockMavenProject(); mojo.execute(); File apiDocs = new File(temporaryFolder.getRoot(), "api-docs"); assertThat(apiDocs).exists(); assertThat(apiDocs).isDirectory(); assertFileWithContent("index.json", new File(apiDocs, "index.json")); assertFileWithContent("pets.json", new File(new File(apiDocs, "pets"), "index.json")); } private void assertFileWithContent(String resource, File file) { assertThat(file).exists(); assertThat(file).isFile();
assertThat(file).hasContent(TestResources.read(SwaggerJaxrsGeneratorMojoTest.class, resource));
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // }
import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart;
/******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock.noswagger; @Path("/pet") @Produces(MediaType.APPLICATION_JSON) public class PureJaxrsPetService { @GET
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart; /******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock.noswagger; @Path("/pet") @Produces(MediaType.APPLICATION_JSON) public class PureJaxrsPetService { @GET
public PetListing list(@QueryParam("start") @DefaultValue("0") int start,
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // }
import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart;
/******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock.noswagger; @Path("/pet") @Produces(MediaType.APPLICATION_JSON) public class PureJaxrsPetService { @GET public PetListing list(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-list")
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart; /******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock.noswagger; @Path("/pet") @Produces(MediaType.APPLICATION_JSON) public class PureJaxrsPetService { @GET public PetListing list(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-list")
public List<PetHandle> listAsList(@QueryParam("start") @DefaultValue("0") int start,
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // }
import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart;
/******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock.noswagger; @Path("/pet") @Produces(MediaType.APPLICATION_JSON) public class PureJaxrsPetService { @GET public PetListing list(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-list") public List<PetHandle> listAsList(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-collection") public Collection<PetHandle> listAsCollection(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("{id}")
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart; /******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.mock.noswagger; @Path("/pet") @Produces(MediaType.APPLICATION_JSON) public class PureJaxrsPetService { @GET public PetListing list(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-list") public List<PetHandle> listAsList(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-collection") public Collection<PetHandle> listAsCollection(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("{id}")
public Pet retrievePet(@PathParam("id") long id) {
greensopinion/swagger-jaxrs-maven
src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // }
import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart;
@QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-collection") public Collection<PetHandle> listAsCollection(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("{id}") public Pet retrievePet(@PathParam("id") long id) { return null; } @GET @Path("{id}/properties") public Map<String, Object> retrievePet(@PathParam("id") long id, @QueryParam("properties") List<String> properties) { return null; } @DELETE @Path("/{id}") public void deletePet(@PathParam("id") long id) { } @PUT
// Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/Pet.java // public class Pet extends PetValues { // // private long id; // // private URI url; // // private Date created; // // public long getId() { // return id; // } // // public Date getCreated() { // return created; // } // // public URI getUrl() { // return url; // } // // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetHandle.java // public class PetHandle { // // private long id; // // private String name; // // public long getId() { // return id; // } // // public String getName() { // return name; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetListing.java // public class PetListing { // // private final int start; // // private final int count; // // private final int total; // // private final List<PetHandle> pets; // // public PetListing(int start, int count, int total, List<PetHandle> pets) { // this.start = start; // this.count = count; // this.total = total; // this.pets = ImmutableList.copyOf(checkNotNull(pets)); // } // // public int getStart() { // return start; // } // // public int getCount() { // return count; // } // // public int getTotal() { // return total; // } // // public List<PetHandle> getPets() { // return pets; // } // } // // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/model/PetValues.java // public class PetValues { // // private String name; // // private PetKind kind; // // private String notes; // // public String getName() { // return name; // } // // public PetKind getKind() { // return kind; // } // // public String getNotes() { // return notes; // } // // } // Path: src/test/java/com/greensopinion/swagger/jaxrsgen/mock/noswagger/PureJaxrsPetService.java import java.util.Collection; import java.util.List; import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.Pet; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetHandle; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetListing; import com.greensopinion.swagger.jaxrsgen.mock.noswagger.model.PetValues; import com.sun.jersey.multipart.MultiPart; @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("as-collection") public Collection<PetHandle> listAsCollection(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("50") int count) { return null; } @GET @Path("{id}") public Pet retrievePet(@PathParam("id") long id) { return null; } @GET @Path("{id}/properties") public Map<String, Object> retrievePet(@PathParam("id") long id, @QueryParam("properties") List<String> properties) { return null; } @DELETE @Path("/{id}") public void deletePet(@PathParam("id") long id) { } @PUT
public PetHandle createPet(PetValues petValues) {
greensopinion/swagger-jaxrs-maven
src/main/java/com/greensopinion/swagger/jaxrsgen/model/GsonIntrospector.java
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/SafeExecutor.java // public class SafeExecutor { // // public interface RunnableWithCheckedException { // // public void run() throws Exception; // } // // public static void run(RunnableWithCheckedException runnable) { // try { // runnable.run(); // } catch (Exception e) { // propagateAsUncheckedException(e); // } // } // // public static <T> T call(Callable<T> callable) { // try { // return callable.call(); // } catch (Exception e) { // throw propagateAsUncheckedException(e); // } // } // // private static RuntimeException propagateAsUncheckedException(Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException) e; // } // throw new RuntimeException(e); // } // } // // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/ApiModel.java // public static class Property { // // private final String type; // // private final String format; // // @SerializedName("items") // private final Map<String, String> arrayItems; // // private final String description; // // @SerializedName("enum") // private final List<String> enumeratedValues; // // public Property(String type, String format, String description, List<String> enumeratedValues, // Map<String, String> arrayItems) { // this.type = type; // this.format = format; // this.description = Strings.emptyToNull(description); // this.arrayItems = arrayItems == null ? null : ImmutableMap.copyOf(arrayItems); // this.enumeratedValues = enumeratedValues == null ? null : ImmutableList.copyOf(enumeratedValues); // } // // public String getType() { // return type; // } // // public String getFormat() { // return format; // } // // public String getDescription() { // return description; // } // // public List<String> getEnumeratedValues() { // return enumeratedValues; // } // // }
import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.greensopinion.swagger.jaxrsgen.SafeExecutor; import com.greensopinion.swagger.jaxrsgen.model.ApiModel.Property; import io.swagger.annotations.ApiModelProperty;
/******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.model; public class GsonIntrospector extends JsonIntrospector { private final FieldNamingStrategy fieldNamingStrategy = FieldNamingPolicy.IDENTITY; @Override public Set<Class<?>> fieldModelClasses(Class<?> modelClass) { Set<Class<?>> classes = Sets.newHashSet(); fieldModelClasses(classes, modelClass); return classes; } private void fieldModelClasses(Set<Class<?>> classes, Class<?> modelClass) { for (Field field : modelFields(modelClass)) { Class<?> fieldType = ApiTypes.modelClass(field.getGenericType()); if (ApiTypes.isModelClass(fieldType)) { if (classes.add(fieldType)) { fieldModelClasses(classes, fieldType); } } } } @Override public ApiModel createApiModel(Class<?> modelClass) { String name = ApiTypes.calculateTypeName(modelClass); String description = calculateDescription(modelClass);
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/SafeExecutor.java // public class SafeExecutor { // // public interface RunnableWithCheckedException { // // public void run() throws Exception; // } // // public static void run(RunnableWithCheckedException runnable) { // try { // runnable.run(); // } catch (Exception e) { // propagateAsUncheckedException(e); // } // } // // public static <T> T call(Callable<T> callable) { // try { // return callable.call(); // } catch (Exception e) { // throw propagateAsUncheckedException(e); // } // } // // private static RuntimeException propagateAsUncheckedException(Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException) e; // } // throw new RuntimeException(e); // } // } // // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/ApiModel.java // public static class Property { // // private final String type; // // private final String format; // // @SerializedName("items") // private final Map<String, String> arrayItems; // // private final String description; // // @SerializedName("enum") // private final List<String> enumeratedValues; // // public Property(String type, String format, String description, List<String> enumeratedValues, // Map<String, String> arrayItems) { // this.type = type; // this.format = format; // this.description = Strings.emptyToNull(description); // this.arrayItems = arrayItems == null ? null : ImmutableMap.copyOf(arrayItems); // this.enumeratedValues = enumeratedValues == null ? null : ImmutableList.copyOf(enumeratedValues); // } // // public String getType() { // return type; // } // // public String getFormat() { // return format; // } // // public String getDescription() { // return description; // } // // public List<String> getEnumeratedValues() { // return enumeratedValues; // } // // } // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/GsonIntrospector.java import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.greensopinion.swagger.jaxrsgen.SafeExecutor; import com.greensopinion.swagger.jaxrsgen.model.ApiModel.Property; import io.swagger.annotations.ApiModelProperty; /******************************************************************************* * Copyright (c) 2014, 2015 Tasktop Technologies. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Tasktop EULA * which accompanies this distribution, and is available at * http://tasktop.com/legal *******************************************************************************/ package com.greensopinion.swagger.jaxrsgen.model; public class GsonIntrospector extends JsonIntrospector { private final FieldNamingStrategy fieldNamingStrategy = FieldNamingPolicy.IDENTITY; @Override public Set<Class<?>> fieldModelClasses(Class<?> modelClass) { Set<Class<?>> classes = Sets.newHashSet(); fieldModelClasses(classes, modelClass); return classes; } private void fieldModelClasses(Set<Class<?>> classes, Class<?> modelClass) { for (Field field : modelFields(modelClass)) { Class<?> fieldType = ApiTypes.modelClass(field.getGenericType()); if (ApiTypes.isModelClass(fieldType)) { if (classes.add(fieldType)) { fieldModelClasses(classes, fieldType); } } } } @Override public ApiModel createApiModel(Class<?> modelClass) { String name = ApiTypes.calculateTypeName(modelClass); String description = calculateDescription(modelClass);
LinkedHashMap<String, Property> properties = Maps.newLinkedHashMap();
greensopinion/swagger-jaxrs-maven
src/main/java/com/greensopinion/swagger/jaxrsgen/model/GsonIntrospector.java
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/SafeExecutor.java // public class SafeExecutor { // // public interface RunnableWithCheckedException { // // public void run() throws Exception; // } // // public static void run(RunnableWithCheckedException runnable) { // try { // runnable.run(); // } catch (Exception e) { // propagateAsUncheckedException(e); // } // } // // public static <T> T call(Callable<T> callable) { // try { // return callable.call(); // } catch (Exception e) { // throw propagateAsUncheckedException(e); // } // } // // private static RuntimeException propagateAsUncheckedException(Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException) e; // } // throw new RuntimeException(e); // } // } // // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/ApiModel.java // public static class Property { // // private final String type; // // private final String format; // // @SerializedName("items") // private final Map<String, String> arrayItems; // // private final String description; // // @SerializedName("enum") // private final List<String> enumeratedValues; // // public Property(String type, String format, String description, List<String> enumeratedValues, // Map<String, String> arrayItems) { // this.type = type; // this.format = format; // this.description = Strings.emptyToNull(description); // this.arrayItems = arrayItems == null ? null : ImmutableMap.copyOf(arrayItems); // this.enumeratedValues = enumeratedValues == null ? null : ImmutableList.copyOf(enumeratedValues); // } // // public String getType() { // return type; // } // // public String getFormat() { // return format; // } // // public String getDescription() { // return description; // } // // public List<String> getEnumeratedValues() { // return enumeratedValues; // } // // }
import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.greensopinion.swagger.jaxrsgen.SafeExecutor; import com.greensopinion.swagger.jaxrsgen.model.ApiModel.Property; import io.swagger.annotations.ApiModelProperty;
@SuppressWarnings({ "unchecked", "rawtypes" }) private Property createApiModelProperty(Field f) { ApiModelProperty apiModelProperty = f.getAnnotation(ApiModelProperty.class); String description = null; if (apiModelProperty != null) { if (apiModelProperty.hidden()) { return null; } description = apiModelProperty.value(); } List<String> enumeratedValues = null; if (f.getType().isEnum()) { enumeratedValues = calculateEnumValues((Class<Enum>) f.getType()); } Map<String, String> arrayItems = null; if (f.getType().isArray()) { arrayItems = ImmutableMap.of("$ref", ApiTypes.calculateTypeName(f.getType().getComponentType())); } else if (Collection.class.isAssignableFrom(f.getType())) { arrayItems = ImmutableMap.of("$ref", ApiTypes.calculateTypeParameterName(f.getGenericType())); } return new Property(ApiTypes.calculateTypeName(f.getType()), ApiTypes.calculateTypeFormat(f.getType()), description, enumeratedValues, arrayItems); } private <T extends Enum<T>> List<String> calculateEnumValues(Class<T> enumClass) { List<String> enumeratedValues = Lists.newArrayList(); for (T enumConstant : enumClass.getEnumConstants()) { String fieldName = enumConstant.name(); String name = fieldName;
// Path: src/main/java/com/greensopinion/swagger/jaxrsgen/SafeExecutor.java // public class SafeExecutor { // // public interface RunnableWithCheckedException { // // public void run() throws Exception; // } // // public static void run(RunnableWithCheckedException runnable) { // try { // runnable.run(); // } catch (Exception e) { // propagateAsUncheckedException(e); // } // } // // public static <T> T call(Callable<T> callable) { // try { // return callable.call(); // } catch (Exception e) { // throw propagateAsUncheckedException(e); // } // } // // private static RuntimeException propagateAsUncheckedException(Exception e) { // if (e instanceof RuntimeException) { // throw (RuntimeException) e; // } // throw new RuntimeException(e); // } // } // // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/ApiModel.java // public static class Property { // // private final String type; // // private final String format; // // @SerializedName("items") // private final Map<String, String> arrayItems; // // private final String description; // // @SerializedName("enum") // private final List<String> enumeratedValues; // // public Property(String type, String format, String description, List<String> enumeratedValues, // Map<String, String> arrayItems) { // this.type = type; // this.format = format; // this.description = Strings.emptyToNull(description); // this.arrayItems = arrayItems == null ? null : ImmutableMap.copyOf(arrayItems); // this.enumeratedValues = enumeratedValues == null ? null : ImmutableList.copyOf(enumeratedValues); // } // // public String getType() { // return type; // } // // public String getFormat() { // return format; // } // // public String getDescription() { // return description; // } // // public List<String> getEnumeratedValues() { // return enumeratedValues; // } // // } // Path: src/main/java/com/greensopinion/swagger/jaxrsgen/model/GsonIntrospector.java import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingStrategy; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.greensopinion.swagger.jaxrsgen.SafeExecutor; import com.greensopinion.swagger.jaxrsgen.model.ApiModel.Property; import io.swagger.annotations.ApiModelProperty; @SuppressWarnings({ "unchecked", "rawtypes" }) private Property createApiModelProperty(Field f) { ApiModelProperty apiModelProperty = f.getAnnotation(ApiModelProperty.class); String description = null; if (apiModelProperty != null) { if (apiModelProperty.hidden()) { return null; } description = apiModelProperty.value(); } List<String> enumeratedValues = null; if (f.getType().isEnum()) { enumeratedValues = calculateEnumValues((Class<Enum>) f.getType()); } Map<String, String> arrayItems = null; if (f.getType().isArray()) { arrayItems = ImmutableMap.of("$ref", ApiTypes.calculateTypeName(f.getType().getComponentType())); } else if (Collection.class.isAssignableFrom(f.getType())) { arrayItems = ImmutableMap.of("$ref", ApiTypes.calculateTypeParameterName(f.getGenericType())); } return new Property(ApiTypes.calculateTypeName(f.getType()), ApiTypes.calculateTypeFormat(f.getType()), description, enumeratedValues, arrayItems); } private <T extends Enum<T>> List<String> calculateEnumValues(Class<T> enumClass) { List<String> enumeratedValues = Lists.newArrayList(); for (T enumConstant : enumClass.getEnumConstants()) { String fieldName = enumConstant.name(); String name = fieldName;
SerializedName annotation = SafeExecutor
apache/log4j-extras
src/main/java/org/apache/log4j/receivers/net/UDPAppender.java
// Path: src/main/java/org/apache/log4j/component/helpers/Constants.java // public interface Constants { // // /** // * log4j package name string literal. // */ // String LOG4J_PACKAGE_NAME = "org.apache.log4j"; // // /** // * The name of the default repository is "default" (without the quotes). // */ // String DEFAULT_REPOSITORY_NAME = "default"; // // /** // * application string literal. // */ // String APPLICATION_KEY = "application"; // /** // * hostname string literal. // */ // String HOSTNAME_KEY = "hostname"; // /** // * receiver string literal. // */ // String RECEIVER_NAME_KEY = "receiver"; // /** // * log4jid string literal. // */ // String LOG4J_ID_KEY = "log4jid"; // /** // * time stamp pattern string literal. // */ // String TIMESTAMP_RULE_FORMAT = "yyyy/MM/dd HH:mm:ss"; // // /** // * The default property file name for automatic configuration. // */ // String DEFAULT_CONFIGURATION_FILE = "log4j.properties"; // /** // * The default XML configuration file name for automatic configuration. // */ // String DEFAULT_XML_CONFIGURATION_FILE = "log4j.xml"; // /** // * log4j.configuration string literal. // */ // String DEFAULT_CONFIGURATION_KEY = "log4j.configuration"; // /** // * log4j.configuratorClass string literal. // */ // String CONFIGURATOR_CLASS_KEY = "log4j.configuratorClass"; // // /** // * JNDI context name string literal. // */ // String JNDI_CONTEXT_NAME = "java:comp/env/log4j/context-name"; // // /** // * TEMP_LIST_APPENDER string literal. // */ // String TEMP_LIST_APPENDER_NAME = "TEMP_LIST_APPENDER"; // /** // * TEMP_CONSOLE_APPENDER string literal. // */ // String TEMP_CONSOLE_APPENDER_NAME = "TEMP_CONSOLE_APPENDER"; // /** // * Codes URL string literal. // */ // String CODES_HREF = // "http://logging.apache.org/log4j/docs/codes.html"; // // // /** // * ABSOLUTE string literal. // */ // String ABSOLUTE_FORMAT = "ABSOLUTE"; // /** // * SimpleTimePattern for ABSOLUTE. // */ // String ABSOLUTE_TIME_PATTERN = "HH:mm:ss,SSS"; // // /** // * SimpleTimePattern for ABSOLUTE. // */ // String SIMPLE_TIME_PATTERN = "HH:mm:ss"; // // /** // * DATE string literal. // */ // String DATE_AND_TIME_FORMAT = "DATE"; // /** // * SimpleTimePattern for DATE. // */ // String DATE_AND_TIME_PATTERN = "dd MMM yyyy HH:mm:ss,SSS"; // // /** // * ISO8601 string literal. // */ // String ISO8601_FORMAT = "ISO8601"; // /** // * SimpleTimePattern for ISO8601. // */ // String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; // }
import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.xml.XMLLayout; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException;
activateOptions(); } /** Sends UDP packets to the <code>address</code> and <code>port</code>. */ public UDPAppender(final String host, final int port) { super(false); this.port = port; this.address = getAddressByName(host); this.remoteHost = host; activateOptions(); } /** Open the UDP sender for the <b>RemoteHost</b> and <b>Port</b>. */ public void activateOptions() { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { try { hostname = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException uhe2) { hostname = "unknown"; } } //allow system property of application to be primary if (application == null) {
// Path: src/main/java/org/apache/log4j/component/helpers/Constants.java // public interface Constants { // // /** // * log4j package name string literal. // */ // String LOG4J_PACKAGE_NAME = "org.apache.log4j"; // // /** // * The name of the default repository is "default" (without the quotes). // */ // String DEFAULT_REPOSITORY_NAME = "default"; // // /** // * application string literal. // */ // String APPLICATION_KEY = "application"; // /** // * hostname string literal. // */ // String HOSTNAME_KEY = "hostname"; // /** // * receiver string literal. // */ // String RECEIVER_NAME_KEY = "receiver"; // /** // * log4jid string literal. // */ // String LOG4J_ID_KEY = "log4jid"; // /** // * time stamp pattern string literal. // */ // String TIMESTAMP_RULE_FORMAT = "yyyy/MM/dd HH:mm:ss"; // // /** // * The default property file name for automatic configuration. // */ // String DEFAULT_CONFIGURATION_FILE = "log4j.properties"; // /** // * The default XML configuration file name for automatic configuration. // */ // String DEFAULT_XML_CONFIGURATION_FILE = "log4j.xml"; // /** // * log4j.configuration string literal. // */ // String DEFAULT_CONFIGURATION_KEY = "log4j.configuration"; // /** // * log4j.configuratorClass string literal. // */ // String CONFIGURATOR_CLASS_KEY = "log4j.configuratorClass"; // // /** // * JNDI context name string literal. // */ // String JNDI_CONTEXT_NAME = "java:comp/env/log4j/context-name"; // // /** // * TEMP_LIST_APPENDER string literal. // */ // String TEMP_LIST_APPENDER_NAME = "TEMP_LIST_APPENDER"; // /** // * TEMP_CONSOLE_APPENDER string literal. // */ // String TEMP_CONSOLE_APPENDER_NAME = "TEMP_CONSOLE_APPENDER"; // /** // * Codes URL string literal. // */ // String CODES_HREF = // "http://logging.apache.org/log4j/docs/codes.html"; // // // /** // * ABSOLUTE string literal. // */ // String ABSOLUTE_FORMAT = "ABSOLUTE"; // /** // * SimpleTimePattern for ABSOLUTE. // */ // String ABSOLUTE_TIME_PATTERN = "HH:mm:ss,SSS"; // // /** // * SimpleTimePattern for ABSOLUTE. // */ // String SIMPLE_TIME_PATTERN = "HH:mm:ss"; // // /** // * DATE string literal. // */ // String DATE_AND_TIME_FORMAT = "DATE"; // /** // * SimpleTimePattern for DATE. // */ // String DATE_AND_TIME_PATTERN = "dd MMM yyyy HH:mm:ss,SSS"; // // /** // * ISO8601 string literal. // */ // String ISO8601_FORMAT = "ISO8601"; // /** // * SimpleTimePattern for ISO8601. // */ // String ISO8601_PATTERN = "yyyy-MM-dd HH:mm:ss,SSS"; // } // Path: src/main/java/org/apache/log4j/receivers/net/UDPAppender.java import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.component.helpers.Constants; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.xml.XMLLayout; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; activateOptions(); } /** Sends UDP packets to the <code>address</code> and <code>port</code>. */ public UDPAppender(final String host, final int port) { super(false); this.port = port; this.address = getAddressByName(host); this.remoteHost = host; activateOptions(); } /** Open the UDP sender for the <b>RemoteHost</b> and <b>Port</b>. */ public void activateOptions() { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { try { hostname = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException uhe2) { hostname = "unknown"; } } //allow system property of application to be primary if (application == null) {
application = System.getProperty(Constants.APPLICATION_KEY);
apache/log4j-extras
src/main/java/org/apache/log4j/rolling/FixedWindowRollingPolicy.java
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // }
import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.helpers.LogLog;
} return new RolloverDescriptionImpl(newActiveFile, append, null, null); } /** * {@inheritDoc} */ public RolloverDescription rollover(final String currentFileName) { if (maxIndex >= 0) { int purgeStart = minIndex; if (!explicitActiveFile) { purgeStart++; } if (!purge(purgeStart, maxIndex)) { return null; } StringBuffer buf = new StringBuffer(); formatFileName(new Integer(purgeStart), buf); String renameTo = buf.toString(); String compressedName = renameTo; Action compressAction = null; if (renameTo.endsWith(".gz")) { renameTo = renameTo.substring(0, renameTo.length() - 3); compressAction =
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // } // Path: src/main/java/org/apache/log4j/rolling/FixedWindowRollingPolicy.java import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.helpers.LogLog; } return new RolloverDescriptionImpl(newActiveFile, append, null, null); } /** * {@inheritDoc} */ public RolloverDescription rollover(final String currentFileName) { if (maxIndex >= 0) { int purgeStart = minIndex; if (!explicitActiveFile) { purgeStart++; } if (!purge(purgeStart, maxIndex)) { return null; } StringBuffer buf = new StringBuffer(); formatFileName(new Integer(purgeStart), buf); String renameTo = buf.toString(); String compressedName = renameTo; Action compressAction = null; if (renameTo.endsWith(".gz")) { renameTo = renameTo.substring(0, renameTo.length() - 3); compressAction =
new GZCompressAction(
apache/log4j-extras
src/main/java/org/apache/log4j/rolling/FixedWindowRollingPolicy.java
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // }
import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.helpers.LogLog;
if (maxIndex >= 0) { int purgeStart = minIndex; if (!explicitActiveFile) { purgeStart++; } if (!purge(purgeStart, maxIndex)) { return null; } StringBuffer buf = new StringBuffer(); formatFileName(new Integer(purgeStart), buf); String renameTo = buf.toString(); String compressedName = renameTo; Action compressAction = null; if (renameTo.endsWith(".gz")) { renameTo = renameTo.substring(0, renameTo.length() - 3); compressAction = new GZCompressAction( new File(renameTo), new File(compressedName), true); } else if (renameTo.endsWith(".zip")) { renameTo = renameTo.substring(0, renameTo.length() - 4); compressAction = new ZipCompressAction( new File(renameTo), new File(compressedName), true); }
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // } // Path: src/main/java/org/apache/log4j/rolling/FixedWindowRollingPolicy.java import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.helpers.LogLog; if (maxIndex >= 0) { int purgeStart = minIndex; if (!explicitActiveFile) { purgeStart++; } if (!purge(purgeStart, maxIndex)) { return null; } StringBuffer buf = new StringBuffer(); formatFileName(new Integer(purgeStart), buf); String renameTo = buf.toString(); String compressedName = renameTo; Action compressAction = null; if (renameTo.endsWith(".gz")) { renameTo = renameTo.substring(0, renameTo.length() - 3); compressAction = new GZCompressAction( new File(renameTo), new File(compressedName), true); } else if (renameTo.endsWith(".zip")) { renameTo = renameTo.substring(0, renameTo.length() - 4); compressAction = new ZipCompressAction( new File(renameTo), new File(compressedName), true); }
FileRenameAction renameAction =
apache/log4j-extras
src/test/java/org/apache/log4j/rolling/helper/FileNamePatternTestCase.java
// Path: src/main/java/org/apache/log4j/rolling/RollingPolicyBase.java // public abstract class RollingPolicyBase // implements RollingPolicy, OptionHandler { // /** // * Error message. // */ // private static final String FNP_NOT_SET = // "The FileNamePattern option must be set before using RollingPolicy. "; // // /** // * Reference for error message. // */ // private static final String SEE_FNP_NOT_SET = // "See also http://logging.apache.org/log4j/codes.html#tbr_fnp_not_set"; // // /** // * File name pattern converters. // */ // private PatternConverter[] patternConverters; // // /** // * File name field specifiers. // */ // private ExtrasFormattingInfo[] patternFields; // // /** // * File name pattern. // */ // private String fileNamePatternStr; // // /** // * Active file name may be null. // * Duplicates FileAppender.file and should be removed. // */ // protected String activeFileName; // // /** // * {@inheritDoc} // */ // public void activateOptions() { // // find out period from the filename pattern // if (fileNamePatternStr != null) { // parseFileNamePattern(); // } else { // LogLog.warn(FNP_NOT_SET); // LogLog.warn(SEE_FNP_NOT_SET); // throw new IllegalStateException(FNP_NOT_SET + SEE_FNP_NOT_SET); // } // // } // // /** // * Set file name pattern. // * @param fnp file name pattern. // */ // public void setFileNamePattern(String fnp) { // fileNamePatternStr = fnp; // } // // /** // * Get file name pattern. // * @return file name pattern. // */ // public String getFileNamePattern() { // return fileNamePatternStr; // } // // /** // * ActiveFileName can be left unset, i.e. as null. // * @param afn active file name. // * @deprecated Duplicates FileAppender.file and should be removed // */ // public void setActiveFileName(String afn) { // activeFileName = afn; // } // // /** // * Return the value of the <b>ActiveFile</b> option. // * @deprecated Duplicates FileAppender.file and should be removed // * @return active file name. // */ // public String getActiveFileName() { // return activeFileName; // } // // /** // * Parse file name pattern. // */ // protected final void parseFileNamePattern() { // List converters = new ArrayList(); // List fields = new ArrayList(); // // ExtrasPatternParser.parse( // fileNamePatternStr, converters, fields, null, // ExtrasPatternParser.getFileNamePatternRules()); // patternConverters = new PatternConverter[converters.size()]; // patternConverters = // (PatternConverter[]) converters.toArray(patternConverters); // patternFields = new ExtrasFormattingInfo[converters.size()]; // patternFields = (ExtrasFormattingInfo[]) fields.toArray(patternFields); // } // // /** // * Format file name. // * // * @param obj object to be evaluted in formatting, may not be null. // * @param buf string buffer to which formatted file name is appended, may not be null. // */ // protected final void formatFileName( // final Object obj, final StringBuffer buf) { // for (int i = 0; i < patternConverters.length; i++) { // int fieldStart = buf.length(); // patternConverters[i].format(obj, buf); // // if (patternFields[i] != null) { // patternFields[i].format(fieldStart, buf); // } // } // } // // protected final PatternConverter getDatePatternConverter() { // for (int i = 0; i < patternConverters.length; i++) { // if (patternConverters[i] instanceof DatePatternConverter) { // return patternConverters[i]; // } // } // return null; // // } // // protected final PatternConverter getIntegerPatternConverter() { // for (int i = 0; i < patternConverters.length; i++) { // if (patternConverters[i] instanceof IntegerPatternConverter) { // return patternConverters[i]; // } // } // return null; // } // // }
import junit.framework.TestCase; import org.apache.log4j.rolling.RollingPolicyBase; import org.apache.log4j.rolling.RolloverDescription; import java.util.Calendar;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.rolling.helper; /** * Tests for FileNamePattern. * * @author Ceki * @author Curt Arnold * */ public final class FileNamePatternTestCase extends TestCase { /** * Construct new test. * @param name test name */ public FileNamePatternTestCase(final String name) { super(name); }
// Path: src/main/java/org/apache/log4j/rolling/RollingPolicyBase.java // public abstract class RollingPolicyBase // implements RollingPolicy, OptionHandler { // /** // * Error message. // */ // private static final String FNP_NOT_SET = // "The FileNamePattern option must be set before using RollingPolicy. "; // // /** // * Reference for error message. // */ // private static final String SEE_FNP_NOT_SET = // "See also http://logging.apache.org/log4j/codes.html#tbr_fnp_not_set"; // // /** // * File name pattern converters. // */ // private PatternConverter[] patternConverters; // // /** // * File name field specifiers. // */ // private ExtrasFormattingInfo[] patternFields; // // /** // * File name pattern. // */ // private String fileNamePatternStr; // // /** // * Active file name may be null. // * Duplicates FileAppender.file and should be removed. // */ // protected String activeFileName; // // /** // * {@inheritDoc} // */ // public void activateOptions() { // // find out period from the filename pattern // if (fileNamePatternStr != null) { // parseFileNamePattern(); // } else { // LogLog.warn(FNP_NOT_SET); // LogLog.warn(SEE_FNP_NOT_SET); // throw new IllegalStateException(FNP_NOT_SET + SEE_FNP_NOT_SET); // } // // } // // /** // * Set file name pattern. // * @param fnp file name pattern. // */ // public void setFileNamePattern(String fnp) { // fileNamePatternStr = fnp; // } // // /** // * Get file name pattern. // * @return file name pattern. // */ // public String getFileNamePattern() { // return fileNamePatternStr; // } // // /** // * ActiveFileName can be left unset, i.e. as null. // * @param afn active file name. // * @deprecated Duplicates FileAppender.file and should be removed // */ // public void setActiveFileName(String afn) { // activeFileName = afn; // } // // /** // * Return the value of the <b>ActiveFile</b> option. // * @deprecated Duplicates FileAppender.file and should be removed // * @return active file name. // */ // public String getActiveFileName() { // return activeFileName; // } // // /** // * Parse file name pattern. // */ // protected final void parseFileNamePattern() { // List converters = new ArrayList(); // List fields = new ArrayList(); // // ExtrasPatternParser.parse( // fileNamePatternStr, converters, fields, null, // ExtrasPatternParser.getFileNamePatternRules()); // patternConverters = new PatternConverter[converters.size()]; // patternConverters = // (PatternConverter[]) converters.toArray(patternConverters); // patternFields = new ExtrasFormattingInfo[converters.size()]; // patternFields = (ExtrasFormattingInfo[]) fields.toArray(patternFields); // } // // /** // * Format file name. // * // * @param obj object to be evaluted in formatting, may not be null. // * @param buf string buffer to which formatted file name is appended, may not be null. // */ // protected final void formatFileName( // final Object obj, final StringBuffer buf) { // for (int i = 0; i < patternConverters.length; i++) { // int fieldStart = buf.length(); // patternConverters[i].format(obj, buf); // // if (patternFields[i] != null) { // patternFields[i].format(fieldStart, buf); // } // } // } // // protected final PatternConverter getDatePatternConverter() { // for (int i = 0; i < patternConverters.length; i++) { // if (patternConverters[i] instanceof DatePatternConverter) { // return patternConverters[i]; // } // } // return null; // // } // // protected final PatternConverter getIntegerPatternConverter() { // for (int i = 0; i < patternConverters.length; i++) { // if (patternConverters[i] instanceof IntegerPatternConverter) { // return patternConverters[i]; // } // } // return null; // } // // } // Path: src/test/java/org/apache/log4j/rolling/helper/FileNamePatternTestCase.java import junit.framework.TestCase; import org.apache.log4j.rolling.RollingPolicyBase; import org.apache.log4j.rolling.RolloverDescription; import java.util.Calendar; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.rolling.helper; /** * Tests for FileNamePattern. * * @author Ceki * @author Curt Arnold * */ public final class FileNamePatternTestCase extends TestCase { /** * Construct new test. * @param name test name */ public FileNamePatternTestCase(final String name) { super(name); }
private static class FileNameTestRollingPolicy extends RollingPolicyBase {
apache/log4j-extras
src/main/java/org/apache/log4j/rolling/TimeBasedRollingPolicy.java
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // }
import java.io.File; import java.util.Date; import org.apache.log4j.Appender; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.spi.LoggingEvent;
*/ public RolloverDescription rollover(final String currentActiveFile) { long n = System.currentTimeMillis(); nextCheck = ((n / 1000) + 1) * 1000; StringBuffer buf = new StringBuffer(); formatFileName(new Date(n), buf); String newFileName = buf.toString(); // // if file names haven't changed, no rollover // if (newFileName.equals(lastFileName)) { return null; } Action renameAction = null; Action compressAction = null; String lastBaseName = lastFileName.substring(0, lastFileName.length() - suffixLength); String nextActiveFile = newFileName.substring(0, newFileName.length() - suffixLength); // // if currentActiveFile is not lastBaseName then // active file name is not following file pattern // and requires a rename plus maintaining the same name if (!currentActiveFile.equals(lastBaseName)) { renameAction =
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // } // Path: src/main/java/org/apache/log4j/rolling/TimeBasedRollingPolicy.java import java.io.File; import java.util.Date; import org.apache.log4j.Appender; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.spi.LoggingEvent; */ public RolloverDescription rollover(final String currentActiveFile) { long n = System.currentTimeMillis(); nextCheck = ((n / 1000) + 1) * 1000; StringBuffer buf = new StringBuffer(); formatFileName(new Date(n), buf); String newFileName = buf.toString(); // // if file names haven't changed, no rollover // if (newFileName.equals(lastFileName)) { return null; } Action renameAction = null; Action compressAction = null; String lastBaseName = lastFileName.substring(0, lastFileName.length() - suffixLength); String nextActiveFile = newFileName.substring(0, newFileName.length() - suffixLength); // // if currentActiveFile is not lastBaseName then // active file name is not following file pattern // and requires a rename plus maintaining the same name if (!currentActiveFile.equals(lastBaseName)) { renameAction =
new FileRenameAction(
apache/log4j-extras
src/main/java/org/apache/log4j/rolling/TimeBasedRollingPolicy.java
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // }
import java.io.File; import java.util.Date; import org.apache.log4j.Appender; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.spi.LoggingEvent;
String newFileName = buf.toString(); // // if file names haven't changed, no rollover // if (newFileName.equals(lastFileName)) { return null; } Action renameAction = null; Action compressAction = null; String lastBaseName = lastFileName.substring(0, lastFileName.length() - suffixLength); String nextActiveFile = newFileName.substring(0, newFileName.length() - suffixLength); // // if currentActiveFile is not lastBaseName then // active file name is not following file pattern // and requires a rename plus maintaining the same name if (!currentActiveFile.equals(lastBaseName)) { renameAction = new FileRenameAction( new File(currentActiveFile), new File(lastBaseName), true); nextActiveFile = currentActiveFile; } if (suffixLength == 3) { compressAction =
// Path: src/main/java/org/apache/log4j/rolling/helper/FileRenameAction.java // public final class FileRenameAction extends ActionBase { // /** // * Source. // */ // private final File source; // // /** // * Destination. // */ // private final File destination; // // /** // * If true, rename empty files, otherwise delete empty files. // */ // private final boolean renameEmptyFiles; // // /** // * Creates an FileRenameAction. // * // * @param src current file name. // * @param dst new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // */ // public FileRenameAction(final File src, final File dst, boolean renameEmptyFiles) { // source = src; // destination = dst; // this.renameEmptyFiles = renameEmptyFiles; // } // // /** // * Rename file. // * // * @return true if successfully renamed. // */ // public boolean execute() { // return execute(source, destination, renameEmptyFiles); // } // // /** // * Rename file. // * @param source current file name. // * @param destination new file name. // * @param renameEmptyFiles if true, rename file even if empty, otherwise delete empty files. // * @return true if successfully renamed. // */ // public static boolean execute(final File source, final File destination, boolean renameEmptyFiles) { // if (renameEmptyFiles || source.length() > 0) { // return source.renameTo(destination); // } // return source.delete(); // } // } // // Path: src/main/java/org/apache/log4j/rolling/helper/GZCompressAction.java // public final class GZCompressAction extends ActionBase { // /** // * Source file. // */ // private final File source; // // /** // * Destination file. // */ // private final File destination; // // /** // * If true, attempt to delete file on completion. // */ // private final boolean deleteSource; // // // /** // * Create new instance of GZCompressAction. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // */ // public GZCompressAction( // final File source, final File destination, final boolean deleteSource) { // if (source == null) { // throw new NullPointerException("source"); // } // // if (destination == null) { // throw new NullPointerException("destination"); // } // // this.source = source; // this.destination = destination; // this.deleteSource = deleteSource; // } // // /** // * Compress. // * @return true if successfully compressed. // * @throws IOException on IO exception. // */ // public boolean execute() throws IOException { // return execute(source, destination, deleteSource); // } // // /** // * Compress a file. // * // * @param source file to compress, may not be null. // * @param destination compressed file, may not be null. // * @param deleteSource if true, attempt to delete file on completion. Failure to delete // * does not cause an exception to be thrown or affect return value. // * @return true if source file compressed. // * @throws IOException on IO exception. // */ // public static boolean execute( // final File source, final File destination, final boolean deleteSource) // throws IOException { // if (source.exists()) { // FileInputStream fis = new FileInputStream(source); // FileOutputStream fos = new FileOutputStream(destination); // GZIPOutputStream gzos = new GZIPOutputStream(fos); // byte[] inbuf = new byte[8102]; // int n; // // while ((n = fis.read(inbuf)) != -1) { // gzos.write(inbuf, 0, n); // } // // gzos.close(); // fis.close(); // // if (deleteSource && !source.delete()) { // LogLog.warn("Unable to delete " + source.toString() + "."); // } // // return true; // } // // return false; // } // // // /** // * Capture exception. // * // * @param ex exception. // */ // protected void reportException(final Exception ex) { // LogLog.warn("Exception during compression of '" + source.toString() + "'.", ex); // } // // } // Path: src/main/java/org/apache/log4j/rolling/TimeBasedRollingPolicy.java import java.io.File; import java.util.Date; import org.apache.log4j.Appender; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.rolling.helper.Action; import org.apache.log4j.rolling.helper.FileRenameAction; import org.apache.log4j.rolling.helper.GZCompressAction; import org.apache.log4j.rolling.helper.ZipCompressAction; import org.apache.log4j.spi.LoggingEvent; String newFileName = buf.toString(); // // if file names haven't changed, no rollover // if (newFileName.equals(lastFileName)) { return null; } Action renameAction = null; Action compressAction = null; String lastBaseName = lastFileName.substring(0, lastFileName.length() - suffixLength); String nextActiveFile = newFileName.substring(0, newFileName.length() - suffixLength); // // if currentActiveFile is not lastBaseName then // active file name is not following file pattern // and requires a rename plus maintaining the same name if (!currentActiveFile.equals(lastBaseName)) { renameAction = new FileRenameAction( new File(currentActiveFile), new File(lastBaseName), true); nextActiveFile = currentActiveFile; } if (suffixLength == 3) { compressAction =
new GZCompressAction(
apache/log4j-extras
src/main/java/org/apache/log4j/component/plugins/PluginRegistry.java
// Path: src/main/java/org/apache/log4j/component/spi/LoggerRepositoryEx.java // public interface LoggerRepositoryEx extends LoggerRepository { // /** // Add a {@link LoggerRepositoryEventListener} to the repository. The // listener will be called when repository events occur. // @param listener event listener, may not be null. // */ // void addLoggerRepositoryEventListener( // LoggerRepositoryEventListener listener); // // /** // Remove a {@link LoggerRepositoryEventListener} from the repository. // @param listener listener. // */ // void removeLoggerRepositoryEventListener( // LoggerRepositoryEventListener listener); // // /** // Add a {@link LoggerEventListener} to the repository. The listener // will be called when repository events occur. // @param listener listener, may not be null. // */ // void addLoggerEventListener(LoggerEventListener listener); // // /** // Remove a {@link LoggerEventListener} from the repository. // @param listener listener, may not be null. // */ // void removeLoggerEventListener(LoggerEventListener listener); // // /** // * Get the name of this logger repository. // * @return name, may not be null. // */ // String getName(); // // /** // * A logger repository is a named entity. // * @param repoName new name, may not be null. // */ // void setName(String repoName); // // /** // * Is the current configuration of the repository in its original (pristine) // * state? // * @return true if repository is in original state. // * // */ // boolean isPristine(); // // /** // * Set the pristine flag. // * @param state state // * @see #isPristine // */ // void setPristine(boolean state); // // /** // Requests that a appender removed event be sent to any registered // {@link LoggerEventListener}. // @param logger The logger from which the appender was removed. // @param appender The appender removed from the logger. // */ // void fireRemoveAppenderEvent(Category logger, Appender appender); // // /** // Requests that a level changed event be sent to any registered // {@link LoggerEventListener}. // @param logger The logger which changed levels. // */ // void fireLevelChangedEvent(Logger logger); // // /** // Requests that a configuration changed event be sent to any registered // {@link LoggerRepositoryEventListener}. // */ // void fireConfigurationChangedEvent(); // // /** // * Return the PluginRegisty for this LoggerRepository. // * @return plug in registry. // */ // PluginRegistry getPluginRegistry(); // // /** // * Return the {@link Scheduler} for this LoggerRepository. // * @return scheduler. // */ // Scheduler getScheduler(); // // /** // * Get the properties specific for this repository. // * @return property map. // */ // Map getProperties(); // // /** // * Get the property of this repository. // * @param key property key. // * @return key value or null if not set. // */ // String getProperty(String key); // // /** // * Set a property of this repository. // * @param key key, may not be null. // * @param value new value, if null, property will be removed. // */ // void setProperty(String key, String value); // // /** // * Errors which cannot be logged, go to the error list. // * // * @return List // */ // List getErrorList(); // // /** // * Errors which cannot be logged, go to the error list. // * // * @param errorItem an ErrorItem to add to the error list // */ // void addErrorItem(ErrorItem errorItem); // // /** // * A LoggerRepository can also act as a store for various objects used // * by log4j components. // * // * @param key key, may not be null. // * @return The object stored under 'key'. // */ // Object getObject(String key); // // /** // * Store an object under 'key'. If no object can be found, null is returned. // * // * @param key key, may not be null. // * @param value value, may be null. // */ // void putObject(String key, Object value); // // /** // * Sets the logger factory used by LoggerRepository.getLogger(String). // * @param loggerFactory factory to use, may not be null // */ // void setLoggerFactory(LoggerFactory loggerFactory); // // /** // * Returns the logger factory used by // * LoggerRepository.getLogger(String). // * // * @return non-null factory // */ // LoggerFactory getLoggerFactory(); // // }
import org.apache.log4j.component.spi.LoggerRepositoryEventListener; import org.apache.log4j.component.spi.LoggerRepositoryEx; import org.apache.log4j.spi.LoggerRepository; import java.util.*;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.component.plugins; /** * This is a registry for Plugin instances. It provides methods to * start and stop plugin objects individually and to stop all * plugins for a repository. * * @author Mark Womack * @author Paul Smith */ public final class PluginRegistry { /** * The pluginMap is keyed by plugin name and contains plugins as values. * key=plugin.getName, value=plugin */ private final Map pluginMap; /** * Logger repository. */
// Path: src/main/java/org/apache/log4j/component/spi/LoggerRepositoryEx.java // public interface LoggerRepositoryEx extends LoggerRepository { // /** // Add a {@link LoggerRepositoryEventListener} to the repository. The // listener will be called when repository events occur. // @param listener event listener, may not be null. // */ // void addLoggerRepositoryEventListener( // LoggerRepositoryEventListener listener); // // /** // Remove a {@link LoggerRepositoryEventListener} from the repository. // @param listener listener. // */ // void removeLoggerRepositoryEventListener( // LoggerRepositoryEventListener listener); // // /** // Add a {@link LoggerEventListener} to the repository. The listener // will be called when repository events occur. // @param listener listener, may not be null. // */ // void addLoggerEventListener(LoggerEventListener listener); // // /** // Remove a {@link LoggerEventListener} from the repository. // @param listener listener, may not be null. // */ // void removeLoggerEventListener(LoggerEventListener listener); // // /** // * Get the name of this logger repository. // * @return name, may not be null. // */ // String getName(); // // /** // * A logger repository is a named entity. // * @param repoName new name, may not be null. // */ // void setName(String repoName); // // /** // * Is the current configuration of the repository in its original (pristine) // * state? // * @return true if repository is in original state. // * // */ // boolean isPristine(); // // /** // * Set the pristine flag. // * @param state state // * @see #isPristine // */ // void setPristine(boolean state); // // /** // Requests that a appender removed event be sent to any registered // {@link LoggerEventListener}. // @param logger The logger from which the appender was removed. // @param appender The appender removed from the logger. // */ // void fireRemoveAppenderEvent(Category logger, Appender appender); // // /** // Requests that a level changed event be sent to any registered // {@link LoggerEventListener}. // @param logger The logger which changed levels. // */ // void fireLevelChangedEvent(Logger logger); // // /** // Requests that a configuration changed event be sent to any registered // {@link LoggerRepositoryEventListener}. // */ // void fireConfigurationChangedEvent(); // // /** // * Return the PluginRegisty for this LoggerRepository. // * @return plug in registry. // */ // PluginRegistry getPluginRegistry(); // // /** // * Return the {@link Scheduler} for this LoggerRepository. // * @return scheduler. // */ // Scheduler getScheduler(); // // /** // * Get the properties specific for this repository. // * @return property map. // */ // Map getProperties(); // // /** // * Get the property of this repository. // * @param key property key. // * @return key value or null if not set. // */ // String getProperty(String key); // // /** // * Set a property of this repository. // * @param key key, may not be null. // * @param value new value, if null, property will be removed. // */ // void setProperty(String key, String value); // // /** // * Errors which cannot be logged, go to the error list. // * // * @return List // */ // List getErrorList(); // // /** // * Errors which cannot be logged, go to the error list. // * // * @param errorItem an ErrorItem to add to the error list // */ // void addErrorItem(ErrorItem errorItem); // // /** // * A LoggerRepository can also act as a store for various objects used // * by log4j components. // * // * @param key key, may not be null. // * @return The object stored under 'key'. // */ // Object getObject(String key); // // /** // * Store an object under 'key'. If no object can be found, null is returned. // * // * @param key key, may not be null. // * @param value value, may be null. // */ // void putObject(String key, Object value); // // /** // * Sets the logger factory used by LoggerRepository.getLogger(String). // * @param loggerFactory factory to use, may not be null // */ // void setLoggerFactory(LoggerFactory loggerFactory); // // /** // * Returns the logger factory used by // * LoggerRepository.getLogger(String). // * // * @return non-null factory // */ // LoggerFactory getLoggerFactory(); // // } // Path: src/main/java/org/apache/log4j/component/plugins/PluginRegistry.java import org.apache.log4j.component.spi.LoggerRepositoryEventListener; import org.apache.log4j.component.spi.LoggerRepositoryEx; import org.apache.log4j.spi.LoggerRepository; import java.util.*; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.component.plugins; /** * This is a registry for Plugin instances. It provides methods to * start and stop plugin objects individually and to stop all * plugins for a repository. * * @author Mark Womack * @author Paul Smith */ public final class PluginRegistry { /** * The pluginMap is keyed by plugin name and contains plugins as values. * key=plugin.getName, value=plugin */ private final Map pluginMap; /** * Logger repository. */
private final LoggerRepositoryEx loggerRepository;
apache/log4j-extras
src/main/java/org/apache/log4j/receivers/net/MulticastReceiver.java
// Path: src/main/java/org/apache/log4j/component/plugins/Receiver.java // public abstract class Receiver extends PluginSkeleton implements Thresholdable { // /** // * Threshold level. // */ // protected Level thresholdLevel; // // /** // * Create new instance. // */ // protected Receiver() { // super(); // } // // /** // * Sets the receiver theshold to the given level. // * // * @param level The threshold level events must equal or be greater // * than before further processing can be done. // */ // public void setThreshold(final Level level) { // Level oldValue = this.thresholdLevel; // thresholdLevel = level; // firePropertyChange("threshold", oldValue, this.thresholdLevel); // } // // /** // * Gets the current threshold setting of the receiver. // * // * @return Level The current threshold level of the receiver. // */ // public Level getThreshold() { // return thresholdLevel; // } // // /** // * Returns true if the given level is equals or greater than the current // * threshold value of the receiver. // * // * @param level The level to test against the receiver threshold. // * @return boolean True if level is equal or greater than the // * receiver threshold. // */ // public boolean isAsSevereAsThreshold(final Level level) { // return ((thresholdLevel == null) // || level.isGreaterOrEqual(thresholdLevel)); // } // // /** // * Posts the logging event to a logger in the configured logger // * repository. // * // * @param event the log event to post to the local log4j environment. // */ // public void doPost(final LoggingEvent event) { // // if event does not meet threshold, exit now // if (!isAsSevereAsThreshold(event.getLevel())) { // return; // } // // // get the "local" logger for this event from the // // configured repository. // Logger localLogger = // getLoggerRepository().getLogger(event.getLoggerName()); // // // if the logger level is greater or equal to the level // // of the event, use the logger to append the event. // if (event.getLevel() // .isGreaterOrEqual(localLogger.getEffectiveLevel())) { // // call the loggers appenders to process the event // localLogger.callAppenders(event); // } // } // } // // Path: src/main/java/org/apache/log4j/receivers/spi/Decoder.java // public interface Decoder { // /** // * Decode events from document. // * @param document document to decode. // * @return list of LoggingEvent instances. // */ // Vector decodeEvents(String document); // // /** // * Decode event from string. // * @param event string representation of event // * @return event // */ // LoggingEvent decode(String event); // // /** // * Decode event from document retrieved from URL. // * @param url url of document // * @return list of LoggingEvent instances. // * @throws IOException if IO error resolving document. // */ // Vector decode(URL url) throws IOException; // // /** // * Sets additional properties. // * @param additionalProperties map of additional properties. // */ // void setAdditionalProperties(Map additionalProperties); // }
import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.net.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.receivers.net; /** * Multicast-based receiver. Accepts LoggingEvents encoded using * MulticastAppender and XMLLayout. The the XML data is converted * back to a LoggingEvent and is posted. * * @author Scott Deboy <[email protected]> * */ public class MulticastReceiver extends Receiver implements PortBased, AddressBased, Pauseable { private static final int PACKET_LENGTH = 16384; private int port; private String address; private String encoding; private MulticastSocket socket = null; //default to log4j xml decoder private String decoder = "org.apache.log4j.xml.XMLDecoder";
// Path: src/main/java/org/apache/log4j/component/plugins/Receiver.java // public abstract class Receiver extends PluginSkeleton implements Thresholdable { // /** // * Threshold level. // */ // protected Level thresholdLevel; // // /** // * Create new instance. // */ // protected Receiver() { // super(); // } // // /** // * Sets the receiver theshold to the given level. // * // * @param level The threshold level events must equal or be greater // * than before further processing can be done. // */ // public void setThreshold(final Level level) { // Level oldValue = this.thresholdLevel; // thresholdLevel = level; // firePropertyChange("threshold", oldValue, this.thresholdLevel); // } // // /** // * Gets the current threshold setting of the receiver. // * // * @return Level The current threshold level of the receiver. // */ // public Level getThreshold() { // return thresholdLevel; // } // // /** // * Returns true if the given level is equals or greater than the current // * threshold value of the receiver. // * // * @param level The level to test against the receiver threshold. // * @return boolean True if level is equal or greater than the // * receiver threshold. // */ // public boolean isAsSevereAsThreshold(final Level level) { // return ((thresholdLevel == null) // || level.isGreaterOrEqual(thresholdLevel)); // } // // /** // * Posts the logging event to a logger in the configured logger // * repository. // * // * @param event the log event to post to the local log4j environment. // */ // public void doPost(final LoggingEvent event) { // // if event does not meet threshold, exit now // if (!isAsSevereAsThreshold(event.getLevel())) { // return; // } // // // get the "local" logger for this event from the // // configured repository. // Logger localLogger = // getLoggerRepository().getLogger(event.getLoggerName()); // // // if the logger level is greater or equal to the level // // of the event, use the logger to append the event. // if (event.getLevel() // .isGreaterOrEqual(localLogger.getEffectiveLevel())) { // // call the loggers appenders to process the event // localLogger.callAppenders(event); // } // } // } // // Path: src/main/java/org/apache/log4j/receivers/spi/Decoder.java // public interface Decoder { // /** // * Decode events from document. // * @param document document to decode. // * @return list of LoggingEvent instances. // */ // Vector decodeEvents(String document); // // /** // * Decode event from string. // * @param event string representation of event // * @return event // */ // LoggingEvent decode(String event); // // /** // * Decode event from document retrieved from URL. // * @param url url of document // * @return list of LoggingEvent instances. // * @throws IOException if IO error resolving document. // */ // Vector decode(URL url) throws IOException; // // /** // * Sets additional properties. // * @param additionalProperties map of additional properties. // */ // void setAdditionalProperties(Map additionalProperties); // } // Path: src/main/java/org/apache/log4j/receivers/net/MulticastReceiver.java import org.apache.log4j.component.plugins.Pauseable; import org.apache.log4j.component.plugins.Receiver; import org.apache.log4j.net.ZeroConfSupport; import org.apache.log4j.receivers.spi.Decoder; import org.apache.log4j.spi.LoggingEvent; import java.io.IOException; import java.net.*; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.receivers.net; /** * Multicast-based receiver. Accepts LoggingEvents encoded using * MulticastAppender and XMLLayout. The the XML data is converted * back to a LoggingEvent and is posted. * * @author Scott Deboy <[email protected]> * */ public class MulticastReceiver extends Receiver implements PortBased, AddressBased, Pauseable { private static final int PACKET_LENGTH = 16384; private int port; private String address; private String encoding; private MulticastSocket socket = null; //default to log4j xml decoder private String decoder = "org.apache.log4j.xml.XMLDecoder";
private Decoder decoderImpl;
jsr377/jsr377-api
jsr377-api/src/main/java/javax/application/converter/spi/ConverterProvider.java
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // }
import javax.application.converter.Converter;
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.converter.spi; /** * @author Andres Almiray */ public interface ConverterProvider<T> { Class<T> getTargetType();
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // Path: jsr377-api/src/main/java/javax/application/converter/spi/ConverterProvider.java import javax.application.converter.Converter; /* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.converter.spi; /** * @author Andres Almiray */ public interface ConverterProvider<T> { Class<T> getTargetType();
Class<? extends Converter<T>> getConverterType();
jsr377/jsr377-api
jsr377-api/src/main/java/javax/application/configuration/Configured.java
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // }
import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.configuration; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Configured { String NO_VALUE = "javax.application.configuration.Configured.NO_VALUE"; String value(); String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // } // Path: jsr377-api/src/main/java/javax/application/configuration/Configured.java import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.configuration; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Configured { String NO_VALUE = "javax.application.configuration.Configured.NO_VALUE"; String value(); String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
Class<? extends Converter<?>> converter() default NoopConverter.class;
jsr377/jsr377-api
jsr377-api/src/main/java/javax/application/configuration/Configured.java
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // }
import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.configuration; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Configured { String NO_VALUE = "javax.application.configuration.Configured.NO_VALUE"; String value(); String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // } // Path: jsr377-api/src/main/java/javax/application/configuration/Configured.java import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.configuration; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Configured { String NO_VALUE = "javax.application.configuration.Configured.NO_VALUE"; String value(); String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
Class<? extends Converter<?>> converter() default NoopConverter.class;
jsr377/jsr377-api
jsr377-api/src/main/java/javax/application/resources/InjectedResource.java
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // }
import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.resources; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface InjectedResource { String NO_VALUE = "javax.application.resources.InjectedResource.NO_VALUE"; String value() default ""; String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // } // Path: jsr377-api/src/main/java/javax/application/resources/InjectedResource.java import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.resources; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface InjectedResource { String NO_VALUE = "javax.application.resources.InjectedResource.NO_VALUE"; String value() default ""; String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
Class<? extends Converter<?>> converter() default NoopConverter.class;
jsr377/jsr377-api
jsr377-api/src/main/java/javax/application/resources/InjectedResource.java
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // }
import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.resources; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface InjectedResource { String NO_VALUE = "javax.application.resources.InjectedResource.NO_VALUE"; String value() default ""; String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
// Path: jsr377-api/src/main/java/javax/application/converter/Converter.java // public interface Converter<T> { // /** // * Converts the input argument to the given type {@code T}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the converted value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to the target type. // */ // T fromObject(Object value) throws ConversionException; // // /** // * Converts the input argument to the a {@code String}. // * // * @param value the value to be converted. May be {@code null}. // * // * @return the {@code String} representation of the given value. May be {@code null}. // * // * @throws ConversionException if the given value could not be converted to a String. // */ // default String toString(T value) throws ConversionException { // return Objects.toString(value, null); // } // } // // Path: jsr377-api/src/main/java/javax/application/converter/NoopConverter.java // public class NoopConverter implements Converter<Object> { // @Override // public Object fromObject(Object value) throws ConversionException { // return value; // } // } // Path: jsr377-api/src/main/java/javax/application/resources/InjectedResource.java import javax.application.converter.Converter; import javax.application.converter.NoopConverter; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * 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 javax.application.resources; /** * @author Andres Almiray */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface InjectedResource { String NO_VALUE = "javax.application.resources.InjectedResource.NO_VALUE"; String value() default ""; String[] args() default {}; String defaultValue() default NO_VALUE; String format() default "";
Class<? extends Converter<?>> converter() default NoopConverter.class;
Simdea/gmlrva
gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/GenericMultipleLayoutAdapter.java
// Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/threading/BackgroundDiffUtilWorker.java // @AllArgsConstructor // public final class BackgroundDiffUtilWorker implements Runnable { // // private final List<? extends IGenericRecyclerViewLayout> mOldDataSet; // private final List<? extends IGenericRecyclerViewLayout> mNewDataSet; // private final Context mContext; // private final GenericMultipleLayoutAdapter mAdapter; // // /** {@inheritDoc} */ // @WorkerThread // @Override // public void run() { // final DiffUtil.DiffResult diffResult // = DiffUtil.calculateDiff(new GmlrvaDiffCallback(this.mOldDataSet, this.mNewDataSet)); // if (mContext != null) { // ((Activity) mContext).runOnUiThread(new UpdateUiDiffUtilResult(this.mNewDataSet, diffResult, mAdapter)); // } // } // // } // // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/diff/GenericPayload.java // public static final String UPDATE_ITEM = "UPDATE_ITEM";
import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.ViewGroup; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import pt.simdea.gmlrva.lib.threading.BackgroundDiffUtilWorker; import static pt.simdea.gmlrva.lib.diff.GenericPayload.UPDATE_ITEM;
@IntRange(from = 0) final int holderInfoAction) { final List<IGenericRecyclerViewLayout> newList = new ArrayList<>(mPendingUpdates.isEmpty() ? mDataSet : mPendingUpdates.peekLast()); if (!newList.isEmpty() && newList.contains(item)) { notifyItemChanged(newList.indexOf(item), holderInfoAction); } } /** * Procedure meant to prepare an update this adapter's entire data set. * This procedure checks for the changes made to this adapter's data set and applies these changes exclusively, * meaning there are no wasted operations. * Allows for update queueing and recursion. * @param items the list of Generic Layout Implementation items for the data set. */ @UiThread public void updateList(@NonNull final List<? extends IGenericRecyclerViewLayout> items) { mPendingUpdates.add(items); if (mPendingUpdates.size() == 1) { innerUpdateList(items); // no pending update, so execute the update } } /** * Procedure meant to update this adapter's entire data set. * Makes use of a background thread to execute the update operation and off load work from the UIThread. * @param items the list of Generic Layout Implementation items for the data set. */ @UiThread private void innerUpdateList(@NonNull final List<? extends IGenericRecyclerViewLayout> items) {
// Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/threading/BackgroundDiffUtilWorker.java // @AllArgsConstructor // public final class BackgroundDiffUtilWorker implements Runnable { // // private final List<? extends IGenericRecyclerViewLayout> mOldDataSet; // private final List<? extends IGenericRecyclerViewLayout> mNewDataSet; // private final Context mContext; // private final GenericMultipleLayoutAdapter mAdapter; // // /** {@inheritDoc} */ // @WorkerThread // @Override // public void run() { // final DiffUtil.DiffResult diffResult // = DiffUtil.calculateDiff(new GmlrvaDiffCallback(this.mOldDataSet, this.mNewDataSet)); // if (mContext != null) { // ((Activity) mContext).runOnUiThread(new UpdateUiDiffUtilResult(this.mNewDataSet, diffResult, mAdapter)); // } // } // // } // // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/diff/GenericPayload.java // public static final String UPDATE_ITEM = "UPDATE_ITEM"; // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/GenericMultipleLayoutAdapter.java import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.ViewGroup; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import pt.simdea.gmlrva.lib.threading.BackgroundDiffUtilWorker; import static pt.simdea.gmlrva.lib.diff.GenericPayload.UPDATE_ITEM; @IntRange(from = 0) final int holderInfoAction) { final List<IGenericRecyclerViewLayout> newList = new ArrayList<>(mPendingUpdates.isEmpty() ? mDataSet : mPendingUpdates.peekLast()); if (!newList.isEmpty() && newList.contains(item)) { notifyItemChanged(newList.indexOf(item), holderInfoAction); } } /** * Procedure meant to prepare an update this adapter's entire data set. * This procedure checks for the changes made to this adapter's data set and applies these changes exclusively, * meaning there are no wasted operations. * Allows for update queueing and recursion. * @param items the list of Generic Layout Implementation items for the data set. */ @UiThread public void updateList(@NonNull final List<? extends IGenericRecyclerViewLayout> items) { mPendingUpdates.add(items); if (mPendingUpdates.size() == 1) { innerUpdateList(items); // no pending update, so execute the update } } /** * Procedure meant to update this adapter's entire data set. * Makes use of a background thread to execute the update operation and off load work from the UIThread. * @param items the list of Generic Layout Implementation items for the data set. */ @UiThread private void innerUpdateList(@NonNull final List<? extends IGenericRecyclerViewLayout> items) {
mHandler.post(new BackgroundDiffUtilWorker(mDataSet, items, mContext, this));
Simdea/gmlrva
gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/GenericMultipleLayoutAdapter.java
// Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/threading/BackgroundDiffUtilWorker.java // @AllArgsConstructor // public final class BackgroundDiffUtilWorker implements Runnable { // // private final List<? extends IGenericRecyclerViewLayout> mOldDataSet; // private final List<? extends IGenericRecyclerViewLayout> mNewDataSet; // private final Context mContext; // private final GenericMultipleLayoutAdapter mAdapter; // // /** {@inheritDoc} */ // @WorkerThread // @Override // public void run() { // final DiffUtil.DiffResult diffResult // = DiffUtil.calculateDiff(new GmlrvaDiffCallback(this.mOldDataSet, this.mNewDataSet)); // if (mContext != null) { // ((Activity) mContext).runOnUiThread(new UpdateUiDiffUtilResult(this.mNewDataSet, diffResult, mAdapter)); // } // } // // } // // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/diff/GenericPayload.java // public static final String UPDATE_ITEM = "UPDATE_ITEM";
import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.ViewGroup; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import pt.simdea.gmlrva.lib.threading.BackgroundDiffUtilWorker; import static pt.simdea.gmlrva.lib.diff.GenericPayload.UPDATE_ITEM;
private void skipQueuedUpdates() { if (mPendingUpdates.size() > 1) { /* More than one update queued */ final List<? extends IGenericRecyclerViewLayout> lastList = mPendingUpdates.peekLast(); mPendingUpdates.clear(); mPendingUpdates.add(lastList); } } /** * Procedure meant to apply a given payload to this adapter's data set. * @param payloads the payload list object with the updates. * @param position the adapter's position to be updated. */ private void applyPayloads(@NonNull final List<Object> payloads, final int position) { for (final Object payload : payloads) { if (payload instanceof Bundle) { applyBundledPayloads((Bundle) payloads.get(0), position); } } } /** * Procedure meant to apply a {@link DiffUtil} result payload to this adapter's data set. * @param bundledPayloads the {@link Bundle} list object with the updates. * @param position the adapter's position to be updated. */ private void applyBundledPayloads(@Nullable final Bundle bundledPayloads, final int position) { if (bundledPayloads != null && bundledPayloads.keySet() != null) { for (final String key : bundledPayloads.keySet()) {
// Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/threading/BackgroundDiffUtilWorker.java // @AllArgsConstructor // public final class BackgroundDiffUtilWorker implements Runnable { // // private final List<? extends IGenericRecyclerViewLayout> mOldDataSet; // private final List<? extends IGenericRecyclerViewLayout> mNewDataSet; // private final Context mContext; // private final GenericMultipleLayoutAdapter mAdapter; // // /** {@inheritDoc} */ // @WorkerThread // @Override // public void run() { // final DiffUtil.DiffResult diffResult // = DiffUtil.calculateDiff(new GmlrvaDiffCallback(this.mOldDataSet, this.mNewDataSet)); // if (mContext != null) { // ((Activity) mContext).runOnUiThread(new UpdateUiDiffUtilResult(this.mNewDataSet, diffResult, mAdapter)); // } // } // // } // // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/diff/GenericPayload.java // public static final String UPDATE_ITEM = "UPDATE_ITEM"; // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/GenericMultipleLayoutAdapter.java import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.UiThread; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.ViewGroup; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import pt.simdea.gmlrva.lib.threading.BackgroundDiffUtilWorker; import static pt.simdea.gmlrva.lib.diff.GenericPayload.UPDATE_ITEM; private void skipQueuedUpdates() { if (mPendingUpdates.size() > 1) { /* More than one update queued */ final List<? extends IGenericRecyclerViewLayout> lastList = mPendingUpdates.peekLast(); mPendingUpdates.clear(); mPendingUpdates.add(lastList); } } /** * Procedure meant to apply a given payload to this adapter's data set. * @param payloads the payload list object with the updates. * @param position the adapter's position to be updated. */ private void applyPayloads(@NonNull final List<Object> payloads, final int position) { for (final Object payload : payloads) { if (payload instanceof Bundle) { applyBundledPayloads((Bundle) payloads.get(0), position); } } } /** * Procedure meant to apply a {@link DiffUtil} result payload to this adapter's data set. * @param bundledPayloads the {@link Bundle} list object with the updates. * @param position the adapter's position to be updated. */ private void applyBundledPayloads(@Nullable final Bundle bundledPayloads, final int position) { if (bundledPayloads != null && bundledPayloads.keySet() != null) { for (final String key : bundledPayloads.keySet()) {
if (UPDATE_ITEM.equals(key)) {
Simdea/gmlrva
gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/decoration/helpers/DecoratorDrawOverManager.java
// Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/decoration/decorators/SimpleDividerItemDecoration.java // public class SimpleDividerItemDecoration extends GenericItemDecoration<SimpleDividerItemDecorationSpec> { // // @NonNull // private final DecoratorDrawOverManager mDrawOverManager = new DecoratorDrawOverManager(); // // @IntRange(from = 0) // private int mTopSpacing; // @IntRange(from = 0) // private int mBottomSpacing; // @IntRange(from = 0) // private int mStartSpacing; // @IntRange(from = 0) // private int mEndSpacing; // @IntRange(from = 0, to = 5) // private int mDividerPosition; // // @Nullable // private Drawable mDivider; // @Nullable // private Paint mDrawnDivider; // // /** // * Instantiates a new SimpleDividerItemDecoration. // * @param configurationSpec a valid {@link ItemDecorationSpec} containing this item decoration specification. // */ // public SimpleDividerItemDecoration(@NonNull final SimpleDividerItemDecorationSpec configurationSpec) { // super(configurationSpec); // } // // /** {@inheritDoc} */ // @Override // public void getItemOffsets(@NonNull final Rect outRect, @NonNull final View view, // @NonNull final RecyclerView parent, @NonNull final RecyclerView.State state) { // outRect.top = mTopSpacing; // outRect.bottom = mBottomSpacing; // outRect.left = mStartSpacing; // outRect.right = mEndSpacing; // } // // /** {@inheritDoc} */ // @Override // public void onDrawOver(@NonNull final Canvas canvas, @NonNull final RecyclerView parent, // @NonNull final RecyclerView.State state) { // if (mDivider != null) { // mDrawOverManager.applyDrawableDivider(canvas, parent, mDivider, mDividerPosition); // } else if (mDrawnDivider != null) { // mDrawOverManager.applyDrawnDivider(canvas, parent, state, mDrawnDivider, mDividerPosition); // } // } // // /** {@inheritDoc} */ // @Override // protected void applySpec(@NonNull final SimpleDividerItemDecorationSpec configurationSpec) { // /* Get Spacing Rules */ // mTopSpacing = configurationSpec.getTopSpacing(); // mBottomSpacing = configurationSpec.getBottomSpacing(); // mStartSpacing = configurationSpec.getStartSpacing(); // mEndSpacing = configurationSpec.getEndSpacing(); // // /* Get Divider Rules */ // mDivider = configurationSpec.getDivider(); // mDividerPosition = configurationSpec.getDividerPosition(); // mDrawnDivider = configurationSpec.getDrawnDivider(); // } // // } // // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/utilities/GMLRVAConstants.java // @SuppressWarnings("WeakerAccess") // public final class GMLRVAConstants { // // /** Exception Messages */ // public static final String ASSERTION_ERROR = "Instantiating utility class."; // public static final String UNSUPPORTED_ERROR = "Unsupported operation."; // // /** // * Instantiates a new GMLRVAConstants. // * Private to prevent instantiation. // * @throws AssertionError if this constructor is ever called. Utility classes should not be instantiated. // */ // private GMLRVAConstants() { // throw new AssertionError(ASSERTION_ERROR); // Throw an exception if this *is* ever called // } // // }
import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import lombok.NoArgsConstructor; import pt.simdea.gmlrva.lib.decoration.decorators.SimpleDividerItemDecoration; import pt.simdea.gmlrva.lib.utilities.GMLRVAConstants;
* @param parent the parent {@link RecyclerView} for the applied {@link SimpleDividerItemDecoration}. * @param divider the divider's target {@link Drawable} value. * @param position the divider's target position. This value is ranged. * See {@link GenericDecorationDividerPosition} for more information. * @throws UnsupportedOperationException if the given {@link GenericDecorationDividerPosition} is invalid. */ public void applyDrawableDivider(@NonNull final Canvas canvas, @NonNull final RecyclerView parent, @NonNull final Drawable divider, @IntRange(from = 0, to = 5) final int position) { switch (position) { case GenericDecorationDividerPosition.POSITION_TOP: mDrawableDividerHelper.drawDrawableDividerPositionTop(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_BOTTOM: mDrawableDividerHelper.drawDrawableDividerPositionBottom(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_START: mDrawableDividerHelper.drawDrawableDividerPositionStart(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_END: mDrawableDividerHelper.drawDrawableDividerPositionEnd(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_START_END: mDrawableDividerHelper.drawDrawableDividerPositionStart(canvas, parent, divider); mDrawableDividerHelper.drawDrawableDividerPositionEnd(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_TOP_BOTTOM: mDrawableDividerHelper.drawDrawableDividerPositionTop(canvas, parent, divider); mDrawableDividerHelper.drawDrawableDividerPositionBottom(canvas, parent, divider); break; default:
// Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/decoration/decorators/SimpleDividerItemDecoration.java // public class SimpleDividerItemDecoration extends GenericItemDecoration<SimpleDividerItemDecorationSpec> { // // @NonNull // private final DecoratorDrawOverManager mDrawOverManager = new DecoratorDrawOverManager(); // // @IntRange(from = 0) // private int mTopSpacing; // @IntRange(from = 0) // private int mBottomSpacing; // @IntRange(from = 0) // private int mStartSpacing; // @IntRange(from = 0) // private int mEndSpacing; // @IntRange(from = 0, to = 5) // private int mDividerPosition; // // @Nullable // private Drawable mDivider; // @Nullable // private Paint mDrawnDivider; // // /** // * Instantiates a new SimpleDividerItemDecoration. // * @param configurationSpec a valid {@link ItemDecorationSpec} containing this item decoration specification. // */ // public SimpleDividerItemDecoration(@NonNull final SimpleDividerItemDecorationSpec configurationSpec) { // super(configurationSpec); // } // // /** {@inheritDoc} */ // @Override // public void getItemOffsets(@NonNull final Rect outRect, @NonNull final View view, // @NonNull final RecyclerView parent, @NonNull final RecyclerView.State state) { // outRect.top = mTopSpacing; // outRect.bottom = mBottomSpacing; // outRect.left = mStartSpacing; // outRect.right = mEndSpacing; // } // // /** {@inheritDoc} */ // @Override // public void onDrawOver(@NonNull final Canvas canvas, @NonNull final RecyclerView parent, // @NonNull final RecyclerView.State state) { // if (mDivider != null) { // mDrawOverManager.applyDrawableDivider(canvas, parent, mDivider, mDividerPosition); // } else if (mDrawnDivider != null) { // mDrawOverManager.applyDrawnDivider(canvas, parent, state, mDrawnDivider, mDividerPosition); // } // } // // /** {@inheritDoc} */ // @Override // protected void applySpec(@NonNull final SimpleDividerItemDecorationSpec configurationSpec) { // /* Get Spacing Rules */ // mTopSpacing = configurationSpec.getTopSpacing(); // mBottomSpacing = configurationSpec.getBottomSpacing(); // mStartSpacing = configurationSpec.getStartSpacing(); // mEndSpacing = configurationSpec.getEndSpacing(); // // /* Get Divider Rules */ // mDivider = configurationSpec.getDivider(); // mDividerPosition = configurationSpec.getDividerPosition(); // mDrawnDivider = configurationSpec.getDrawnDivider(); // } // // } // // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/utilities/GMLRVAConstants.java // @SuppressWarnings("WeakerAccess") // public final class GMLRVAConstants { // // /** Exception Messages */ // public static final String ASSERTION_ERROR = "Instantiating utility class."; // public static final String UNSUPPORTED_ERROR = "Unsupported operation."; // // /** // * Instantiates a new GMLRVAConstants. // * Private to prevent instantiation. // * @throws AssertionError if this constructor is ever called. Utility classes should not be instantiated. // */ // private GMLRVAConstants() { // throw new AssertionError(ASSERTION_ERROR); // Throw an exception if this *is* ever called // } // // } // Path: gmlrva-lib/src/main/java/pt/simdea/gmlrva/lib/decoration/helpers/DecoratorDrawOverManager.java import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import lombok.NoArgsConstructor; import pt.simdea.gmlrva.lib.decoration.decorators.SimpleDividerItemDecoration; import pt.simdea.gmlrva.lib.utilities.GMLRVAConstants; * @param parent the parent {@link RecyclerView} for the applied {@link SimpleDividerItemDecoration}. * @param divider the divider's target {@link Drawable} value. * @param position the divider's target position. This value is ranged. * See {@link GenericDecorationDividerPosition} for more information. * @throws UnsupportedOperationException if the given {@link GenericDecorationDividerPosition} is invalid. */ public void applyDrawableDivider(@NonNull final Canvas canvas, @NonNull final RecyclerView parent, @NonNull final Drawable divider, @IntRange(from = 0, to = 5) final int position) { switch (position) { case GenericDecorationDividerPosition.POSITION_TOP: mDrawableDividerHelper.drawDrawableDividerPositionTop(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_BOTTOM: mDrawableDividerHelper.drawDrawableDividerPositionBottom(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_START: mDrawableDividerHelper.drawDrawableDividerPositionStart(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_END: mDrawableDividerHelper.drawDrawableDividerPositionEnd(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_START_END: mDrawableDividerHelper.drawDrawableDividerPositionStart(canvas, parent, divider); mDrawableDividerHelper.drawDrawableDividerPositionEnd(canvas, parent, divider); break; case GenericDecorationDividerPosition.POSITION_TOP_BOTTOM: mDrawableDividerHelper.drawDrawableDividerPositionTop(canvas, parent, divider); mDrawableDividerHelper.drawDrawableDividerPositionBottom(canvas, parent, divider); break; default:
throw new UnsupportedOperationException(GMLRVAConstants.UNSUPPORTED_ERROR);
SergiusIW/collider
demos-core/src/com/matthewmichelotti/collider/demos/comps/CIndicator.java
// Path: demos-core/src/com/matthewmichelotti/collider/demos/Component.java // public abstract class Component implements Comparable<Component> { // private static int NEXT_ID = 0; // private final int id; // private HBPositioned hitBox; // // protected Component(HBPositioned hitBox) { // if(hitBox == null) throw new IllegalArgumentException(); // this.hitBox = hitBox; // hitBox.setOwner(this); // id = NEXT_ID++; // Game.engine.addComp(this); // } // // protected final void delete() { // if(hitBox == null) return; // Game.engine.removeComp(this); // hitBox.free(); // hitBox = null; // } // // protected final boolean isInBounds() {return Game.engine.isInBounds(hitBox);} // public final boolean isDeleted() {return hitBox == null;} // public final int getId() {return id;} // // public final HBPositioned hitBox() {return hitBox;} // public final HBCircle circ() {return (HBCircle)hitBox;} // public final HBRect rect() {return (HBRect)hitBox;} // public final boolean isRect() {return hitBox instanceof HBRect;} // public final boolean isCirc() {return hitBox instanceof HBCircle;} // // public abstract void onCollide(Component other); // public abstract void onSeparate(Component other); // public abstract boolean canInteract(Component other); // public abstract boolean interactsWithBullets(); // public abstract Color getColor(); // public String getMessage() {return null;} // // @Override public final int compareTo(Component o) { // return id - o.id; // } // } // // Path: demos-core/src/com/matthewmichelotti/collider/demos/Game.java // public class Game { // public final static GameEngine engine = new GameEngine(); // public final static Random rand = new Random(); // // private Game() {} // }
import com.badlogic.gdx.graphics.Color; import com.matthewmichelotti.collider.demos.Component; import com.matthewmichelotti.collider.demos.Game;
/* * Copyright 2013-2014 Matthew D. Michelotti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewmichelotti.collider.demos.comps; /** * Indicates how many bullets are overlapping with this Component. * @author Matthew Michelotti */ public class CIndicator extends Component { private static Color LO_COLOR = new Color(0.0f, 0.0f, 0.3f, 1.0f); private static Color HI_COLOR = new Color(0.2f, 0.8f, 1.0f, 1.0f); private int overlaps = 0; private Color blendColor = new Color(); public CIndicator(double x, double y, boolean isRect) {
// Path: demos-core/src/com/matthewmichelotti/collider/demos/Component.java // public abstract class Component implements Comparable<Component> { // private static int NEXT_ID = 0; // private final int id; // private HBPositioned hitBox; // // protected Component(HBPositioned hitBox) { // if(hitBox == null) throw new IllegalArgumentException(); // this.hitBox = hitBox; // hitBox.setOwner(this); // id = NEXT_ID++; // Game.engine.addComp(this); // } // // protected final void delete() { // if(hitBox == null) return; // Game.engine.removeComp(this); // hitBox.free(); // hitBox = null; // } // // protected final boolean isInBounds() {return Game.engine.isInBounds(hitBox);} // public final boolean isDeleted() {return hitBox == null;} // public final int getId() {return id;} // // public final HBPositioned hitBox() {return hitBox;} // public final HBCircle circ() {return (HBCircle)hitBox;} // public final HBRect rect() {return (HBRect)hitBox;} // public final boolean isRect() {return hitBox instanceof HBRect;} // public final boolean isCirc() {return hitBox instanceof HBCircle;} // // public abstract void onCollide(Component other); // public abstract void onSeparate(Component other); // public abstract boolean canInteract(Component other); // public abstract boolean interactsWithBullets(); // public abstract Color getColor(); // public String getMessage() {return null;} // // @Override public final int compareTo(Component o) { // return id - o.id; // } // } // // Path: demos-core/src/com/matthewmichelotti/collider/demos/Game.java // public class Game { // public final static GameEngine engine = new GameEngine(); // public final static Random rand = new Random(); // // private Game() {} // } // Path: demos-core/src/com/matthewmichelotti/collider/demos/comps/CIndicator.java import com.badlogic.gdx.graphics.Color; import com.matthewmichelotti.collider.demos.Component; import com.matthewmichelotti.collider.demos.Game; /* * Copyright 2013-2014 Matthew D. Michelotti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewmichelotti.collider.demos.comps; /** * Indicates how many bullets are overlapping with this Component. * @author Matthew Michelotti */ public class CIndicator extends Component { private static Color LO_COLOR = new Color(0.0f, 0.0f, 0.3f, 1.0f); private static Color HI_COLOR = new Color(0.2f, 0.8f, 1.0f, 1.0f); private int overlaps = 0; private Color blendColor = new Color(); public CIndicator(double x, double y, boolean isRect) {
super(isRect ? Game.engine.makeRect() : Game.engine.makeCircle());
moagrius/TileView
tileview/src/main/java/com/moagrius/tileview/Tile.java
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Looper; import android.os.Process; import android.util.Log; import com.moagrius.tileview.io.StreamProvider; import java.io.InputStream; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor;
package com.moagrius.tileview; public class Tile implements Runnable { private static final int UNSCALED_SAMPLE_SIZE = 1; enum State { IDLE, DECODING, DECODED } // variable (settable) private int mRow; private int mColumn; private int mImageSample = 1; private Detail mDetail; // variable (computed) private volatile State mState = State.IDLE; private Bitmap mBitmap; private int mRetries; // lazy private String mCacheKey; // final default private final Rect mDestinationRect = new Rect(); private final BitmapFactory.Options mDrawingOptions = new TileOptions(false); private final BitmapFactory.Options mMeasureOptions = new TileOptions(true); // final private final int mSize; private final DrawingView mDrawingView; private final Listener mListener;
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // } // Path: tileview/src/main/java/com/moagrius/tileview/Tile.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Looper; import android.os.Process; import android.util.Log; import com.moagrius.tileview.io.StreamProvider; import java.io.InputStream; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; package com.moagrius.tileview; public class Tile implements Runnable { private static final int UNSCALED_SAMPLE_SIZE = 1; enum State { IDLE, DECODING, DECODED } // variable (settable) private int mRow; private int mColumn; private int mImageSample = 1; private Detail mDetail; // variable (computed) private volatile State mState = State.IDLE; private Bitmap mBitmap; private int mRetries; // lazy private String mCacheKey; // final default private final Rect mDestinationRect = new Rect(); private final BitmapFactory.Options mDrawingOptions = new TileOptions(false); private final BitmapFactory.Options mMeasureOptions = new TileOptions(true); // final private final int mSize; private final DrawingView mDrawingView; private final Listener mListener;
private final StreamProvider mStreamProvider;
moagrius/TileView
tileview/src/main/java/com/moagrius/tileview/TileView.java
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // } // // Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProviderAssets.java // public class StreamProviderAssets implements StreamProvider { // @Override // public InputStream getStream(int column, int row, Context context, Object data) throws IOException { // String file = String.format(Locale.US, (String) data, column, row); // return context.getAssets().open(file); // } // } // // Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // }
import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.moagrius.tileview.io.StreamProvider; import com.moagrius.tileview.io.StreamProviderAssets; import com.moagrius.utils.Maths; import com.moagrius.widget.ScalingScrollView; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
package com.moagrius.tileview; public class TileView extends ScalingScrollView implements Handler.Callback, ScalingScrollView.ScaleChangedListener, Tile.DrawingView, Tile.Listener, TilingBitmapView.Provider { // constants private static final int RENDER_THROTTLE_ID = 0; private static final int RENDER_THROTTLE_INTERVAL = 15; private static final short DEFAULT_TILE_SIZE = 256; // variables (settable) private int mZoom = 0; private int mImageSample = 1; // sample will always be one unless we don't have a defined detail level, then its 1 shl for every zoom level from the last defined detail private int mTileSize = DEFAULT_TILE_SIZE; private boolean mIsPrepared; private boolean mHasRunOnReady; private Detail mCurrentDetail; private ScrollScaleState mScrollScaleState; private Set<Listener> mListeners = new LinkedHashSet<>(); private Set<ReadyListener> mReadyListeners = new LinkedHashSet<>(); private Set<TouchListener> mTouchListeners = new LinkedHashSet<>(); private Set<CanvasDecorator> mCanvasDecorators = new LinkedHashSet<>(); private TileDecodeErrorListener mTileDecodeErrorListener; // variables (from build or attach) private FixedSizeViewGroup mContainer; private TilingBitmapView mTilingBitmapView; private BitmapCache mDiskCache; private BitmapCache mMemoryCache; private BitmapPool mBitmapPool;
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // } // // Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProviderAssets.java // public class StreamProviderAssets implements StreamProvider { // @Override // public InputStream getStream(int column, int row, Context context, Object data) throws IOException { // String file = String.format(Locale.US, (String) data, column, row); // return context.getAssets().open(file); // } // } // // Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // } // Path: tileview/src/main/java/com/moagrius/tileview/TileView.java import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.moagrius.tileview.io.StreamProvider; import com.moagrius.tileview.io.StreamProviderAssets; import com.moagrius.utils.Maths; import com.moagrius.widget.ScalingScrollView; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; package com.moagrius.tileview; public class TileView extends ScalingScrollView implements Handler.Callback, ScalingScrollView.ScaleChangedListener, Tile.DrawingView, Tile.Listener, TilingBitmapView.Provider { // constants private static final int RENDER_THROTTLE_ID = 0; private static final int RENDER_THROTTLE_INTERVAL = 15; private static final short DEFAULT_TILE_SIZE = 256; // variables (settable) private int mZoom = 0; private int mImageSample = 1; // sample will always be one unless we don't have a defined detail level, then its 1 shl for every zoom level from the last defined detail private int mTileSize = DEFAULT_TILE_SIZE; private boolean mIsPrepared; private boolean mHasRunOnReady; private Detail mCurrentDetail; private ScrollScaleState mScrollScaleState; private Set<Listener> mListeners = new LinkedHashSet<>(); private Set<ReadyListener> mReadyListeners = new LinkedHashSet<>(); private Set<TouchListener> mTouchListeners = new LinkedHashSet<>(); private Set<CanvasDecorator> mCanvasDecorators = new LinkedHashSet<>(); private TileDecodeErrorListener mTileDecodeErrorListener; // variables (from build or attach) private FixedSizeViewGroup mContainer; private TilingBitmapView mTilingBitmapView; private BitmapCache mDiskCache; private BitmapCache mMemoryCache; private BitmapPool mBitmapPool;
private StreamProvider mStreamProvider;
moagrius/TileView
tileview/src/main/java/com/moagrius/tileview/TileView.java
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // } // // Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProviderAssets.java // public class StreamProviderAssets implements StreamProvider { // @Override // public InputStream getStream(int column, int row, Context context, Object data) throws IOException { // String file = String.format(Locale.US, (String) data, column, row); // return context.getAssets().open(file); // } // } // // Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // }
import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.moagrius.tileview.io.StreamProvider; import com.moagrius.tileview.io.StreamProviderAssets; import com.moagrius.utils.Maths; import com.moagrius.widget.ScalingScrollView; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
} } private void updateViewportAndComputeTilesThrottled() { if (!mRenderThrottle.hasMessages(RENDER_THROTTLE_ID)) { mRenderThrottle.sendEmptyMessageDelayed(RENDER_THROTTLE_ID, RENDER_THROTTLE_INTERVAL); } } private void updateViewport() { mViewport.left = getScrollX(); mViewport.top = getScrollY(); mViewport.right = mViewport.left + getMeasuredWidth(); mViewport.bottom = mViewport.top + getMeasuredHeight(); updateScaledViewport(); } private void updateScaledViewport() { // set unfilled to entire viewport, virtualized to scale float scale = getScale(); mScaledViewport.set( (int) (mViewport.left / scale), (int) (mViewport.top / scale), (int) (mViewport.right / scale), (int) (mViewport.bottom / scale) ); } public void populateTileGridFromViewport() { float tileSize = mTileSize * getScale() * mCurrentDetail.getSample();
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // } // // Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProviderAssets.java // public class StreamProviderAssets implements StreamProvider { // @Override // public InputStream getStream(int column, int row, Context context, Object data) throws IOException { // String file = String.format(Locale.US, (String) data, column, row); // return context.getAssets().open(file); // } // } // // Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // } // Path: tileview/src/main/java/com/moagrius/tileview/TileView.java import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.moagrius.tileview.io.StreamProvider; import com.moagrius.tileview.io.StreamProviderAssets; import com.moagrius.utils.Maths; import com.moagrius.widget.ScalingScrollView; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; } } private void updateViewportAndComputeTilesThrottled() { if (!mRenderThrottle.hasMessages(RENDER_THROTTLE_ID)) { mRenderThrottle.sendEmptyMessageDelayed(RENDER_THROTTLE_ID, RENDER_THROTTLE_INTERVAL); } } private void updateViewport() { mViewport.left = getScrollX(); mViewport.top = getScrollY(); mViewport.right = mViewport.left + getMeasuredWidth(); mViewport.bottom = mViewport.top + getMeasuredHeight(); updateScaledViewport(); } private void updateScaledViewport() { // set unfilled to entire viewport, virtualized to scale float scale = getScale(); mScaledViewport.set( (int) (mViewport.left / scale), (int) (mViewport.top / scale), (int) (mViewport.right / scale), (int) (mViewport.bottom / scale) ); } public void populateTileGridFromViewport() { float tileSize = mTileSize * getScale() * mCurrentDetail.getSample();
mGrid.rows.start = Maths.roundDownWithStep(mViewport.top / tileSize, mImageSample);
moagrius/TileView
tileview/src/main/java/com/moagrius/tileview/TileView.java
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // } // // Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProviderAssets.java // public class StreamProviderAssets implements StreamProvider { // @Override // public InputStream getStream(int column, int row, Context context, Object data) throws IOException { // String file = String.format(Locale.US, (String) data, column, row); // return context.getAssets().open(file); // } // } // // Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // }
import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.moagrius.tileview.io.StreamProvider; import com.moagrius.tileview.io.StreamProviderAssets; import com.moagrius.utils.Maths; import com.moagrius.widget.ScalingScrollView; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
return this; } public Builder setStreamProvider(StreamProvider streamProvider) { mStreamProvider = streamProvider; return this; } public Builder installPlugin(Plugin plugin) { mTileView.mPlugins.put(plugin.getClass(), plugin); plugin.install(mTileView); return this; } public void build() { buildAsync(); } private void buildAsync() { new Thread(this::buildSync).start(); } private void buildSync() { Activity activity = (Activity) mTileView.getContext(); if (activity == null) { Log.d("TileView", "could not not cast context to activity during preparation"); return; } // if the user provided a custom provider, use that, otherwise default to assets if (mStreamProvider == null) {
// Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProvider.java // public interface StreamProvider { // InputStream getStream(int column, int row, Context context, Object data) throws Exception; // } // // Path: tileview/src/main/java/com/moagrius/tileview/io/StreamProviderAssets.java // public class StreamProviderAssets implements StreamProvider { // @Override // public InputStream getStream(int column, int row, Context context, Object data) throws IOException { // String file = String.format(Locale.US, (String) data, column, row); // return context.getAssets().open(file); // } // } // // Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // } // Path: tileview/src/main/java/com/moagrius/tileview/TileView.java import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Region; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.moagrius.tileview.io.StreamProvider; import com.moagrius.tileview.io.StreamProviderAssets; import com.moagrius.utils.Maths; import com.moagrius.widget.ScalingScrollView; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; return this; } public Builder setStreamProvider(StreamProvider streamProvider) { mStreamProvider = streamProvider; return this; } public Builder installPlugin(Plugin plugin) { mTileView.mPlugins.put(plugin.getClass(), plugin); plugin.install(mTileView); return this; } public void build() { buildAsync(); } private void buildAsync() { new Thread(this::buildSync).start(); } private void buildSync() { Activity activity = (Activity) mTileView.getContext(); if (activity == null) { Log.d("TileView", "could not not cast context to activity during preparation"); return; } // if the user provided a custom provider, use that, otherwise default to assets if (mStreamProvider == null) {
mStreamProvider = new StreamProviderAssets();
moagrius/TileView
tileview/src/main/java/com/moagrius/tileview/Detail.java
// Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // }
import com.moagrius.utils.Maths;
package com.moagrius.tileview; /** * ZOOM PERCENT SAMPLE * 0 100% 1 * 1 50% 2 * 2 25% 4 * 3 12.5% 8 * 4 6.25% 16 * 5 3.125% 32 * ... * handy math: * get percent from zoom: (1 >> zoom) / 1f (number of digits is precision, so (100 >> zoom) / 100f will give .012 * get percent from sample: 1 / sample * get sample from zoom: 1 << zoom * get zoom from sample: Maths.log2(sample) */ public class Detail { public static int getZoomFromPercent(float percent) {
// Path: tileview/src/main/java/com/moagrius/utils/Maths.java // public class Maths { // // public static final double LOG_2 = Math.log(2); // // public static double log2(int n) { // return Math.log(n) / LOG_2; // } // // public static int roundWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return Math.round(value / step) * step; // } // // public static int roundUpWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.ceil(value / step) * step; // } // // public static int roundDownWithStep(float value, int step) { // if (value == 0) { // return 0; // } // return (int) Math.floor(value / step) * step; // } // // public static float divideSafely(int dividend, float divisor) { // if (dividend == 0 || divisor == 0) { // return 0; // } // return dividend / divisor; // } // // } // Path: tileview/src/main/java/com/moagrius/tileview/Detail.java import com.moagrius.utils.Maths; package com.moagrius.tileview; /** * ZOOM PERCENT SAMPLE * 0 100% 1 * 1 50% 2 * 2 25% 4 * 3 12.5% 8 * 4 6.25% 16 * 5 3.125% 32 * ... * handy math: * get percent from zoom: (1 >> zoom) / 1f (number of digits is precision, so (100 >> zoom) / 100f will give .012 * get percent from sample: 1 / sample * get sample from zoom: 1 << zoom * get zoom from sample: Maths.log2(sample) */ public class Detail { public static int getZoomFromPercent(float percent) {
return (int) Maths.log2((int) (1 / percent));
moagrius/TileView
demo/src/main/java/com/moagrius/MainActivity.java
// Path: demo/src/main/java/com/moagrius/helpers/FileCopier.java // public class FileCopier { // // private File mDirectory; // private String mPreferencesKey; // private Listener mListener; // // public FileCopier(File directory, String preferencesKey, Listener listener) { // mDirectory = directory; // mPreferencesKey = preferencesKey; // mListener = listener; // } // // public void copyFiles(Activity activity) throws Exception { // Log.d("TV", "about to copy asset tiles to " + mDirectory); // Helpers.saveBooleanPreference(activity, mPreferencesKey, false); // AssetManager assetManager = activity.getAssets(); // String[] assetPaths = assetManager.list("tiles"); // for (String assetPath : assetPaths) { // InputStream assetStream = assetManager.open("tiles/" + assetPath); // File dest = new File(mDirectory, assetPath); // FileOutputStream outputStream = new FileOutputStream(dest); // Helpers.copyStreams(assetStream, outputStream); // Log.d("TV", assetPath + " copied to " + dest); // activity.runOnUiThread(() -> mListener.onProgress(dest)); // } // activity.runOnUiThread(() -> mListener.onComplete(mDirectory)); // Helpers.saveBooleanPreference(activity, mPreferencesKey, true); // Log.d("TV", "done copying files"); // } // // public void copyFilesAsync(Activity activity) { // new Thread(() -> { // try { // copyFiles(activity); // } catch (Exception e) { // mListener.onError(e); // } // }).start(); // } // // public interface Listener { // void onProgress(File file); // void onComplete(File directory); // void onError(Throwable throwable); // } // // } // // Path: demo/src/main/java/com/moagrius/helpers/Helpers.java // public class Helpers { // // public static final String EXTERNAL_STORAGE_KEY = "external"; // public static final String INTERNAL_STORAGE_KEY = "internal"; // // private static final String PREFS_FILE_NAME = "preferences"; // // public static void copyStreams(InputStream inputStream, OutputStream outputStream) throws IOException { // try { // int data = inputStream.read(); // while (data != -1) { // outputStream.write(data); // data = inputStream.read(); // } // } finally { // inputStream.close(); // outputStream.close(); // } // } // // public static void saveBooleanPreference(Context context, String key, boolean value) { // SharedPreferences preferences = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE); // SharedPreferences.Editor editor = preferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // public static boolean getBooleanPreference(Context context, String key) { // return context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE).getBoolean(key, false); // } // // }
import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.widget.Toast; import com.moagrius.helpers.FileCopier; import com.moagrius.helpers.Helpers; import java.io.File;
package com.moagrius; public class MainActivity extends Activity implements FileCopier.Listener { private static final int WRITE_REQUEST_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
// Path: demo/src/main/java/com/moagrius/helpers/FileCopier.java // public class FileCopier { // // private File mDirectory; // private String mPreferencesKey; // private Listener mListener; // // public FileCopier(File directory, String preferencesKey, Listener listener) { // mDirectory = directory; // mPreferencesKey = preferencesKey; // mListener = listener; // } // // public void copyFiles(Activity activity) throws Exception { // Log.d("TV", "about to copy asset tiles to " + mDirectory); // Helpers.saveBooleanPreference(activity, mPreferencesKey, false); // AssetManager assetManager = activity.getAssets(); // String[] assetPaths = assetManager.list("tiles"); // for (String assetPath : assetPaths) { // InputStream assetStream = assetManager.open("tiles/" + assetPath); // File dest = new File(mDirectory, assetPath); // FileOutputStream outputStream = new FileOutputStream(dest); // Helpers.copyStreams(assetStream, outputStream); // Log.d("TV", assetPath + " copied to " + dest); // activity.runOnUiThread(() -> mListener.onProgress(dest)); // } // activity.runOnUiThread(() -> mListener.onComplete(mDirectory)); // Helpers.saveBooleanPreference(activity, mPreferencesKey, true); // Log.d("TV", "done copying files"); // } // // public void copyFilesAsync(Activity activity) { // new Thread(() -> { // try { // copyFiles(activity); // } catch (Exception e) { // mListener.onError(e); // } // }).start(); // } // // public interface Listener { // void onProgress(File file); // void onComplete(File directory); // void onError(Throwable throwable); // } // // } // // Path: demo/src/main/java/com/moagrius/helpers/Helpers.java // public class Helpers { // // public static final String EXTERNAL_STORAGE_KEY = "external"; // public static final String INTERNAL_STORAGE_KEY = "internal"; // // private static final String PREFS_FILE_NAME = "preferences"; // // public static void copyStreams(InputStream inputStream, OutputStream outputStream) throws IOException { // try { // int data = inputStream.read(); // while (data != -1) { // outputStream.write(data); // data = inputStream.read(); // } // } finally { // inputStream.close(); // outputStream.close(); // } // } // // public static void saveBooleanPreference(Context context, String key, boolean value) { // SharedPreferences preferences = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE); // SharedPreferences.Editor editor = preferences.edit(); // editor.putBoolean(key, value); // editor.apply(); // } // // public static boolean getBooleanPreference(Context context, String key) { // return context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE).getBoolean(key, false); // } // // } // Path: demo/src/main/java/com/moagrius/MainActivity.java import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.widget.Toast; import com.moagrius.helpers.FileCopier; import com.moagrius.helpers.Helpers; import java.io.File; package com.moagrius; public class MainActivity extends Activity implements FileCopier.Listener { private static final int WRITE_REQUEST_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
findViewById(R.id.textview_demos_tileview_internal).setOnClickListener(view -> showStorageDemoOrWarning(Helpers.INTERNAL_STORAGE_KEY, getFilesDir(), TileViewDemoInternalStorage.class));
sregg/spotify-tv
app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple;
@Override public boolean hasOverlappingRendering() { return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mAttachedToWindow = true; if (mImageView.getAlpha() == 0) fadeIn(); BusProvider.getInstance().register(this); } @Override protected void onDetachedFromWindow() { mAttachedToWindow = false; mImageView.animate().cancel(); mImageView.setAlpha(1f); BusProvider.unregister(this); super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // } // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple; @Override public boolean hasOverlappingRendering() { return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mAttachedToWindow = true; if (mImageView.getAlpha() == 0) fadeIn(); BusProvider.getInstance().register(this); } @Override protected void onDetachedFromWindow() { mAttachedToWindow = false; mImageView.animate().cancel(); mImageView.setAlpha(1f); BusProvider.unregister(this); super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe
public void onTrackChanged(OnTrackChanged onTrackChanged) {
sregg/spotify-tv
app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple;
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mAttachedToWindow = true; if (mImageView.getAlpha() == 0) fadeIn(); BusProvider.getInstance().register(this); } @Override protected void onDetachedFromWindow() { mAttachedToWindow = false; mImageView.animate().cancel(); mImageView.setAlpha(1f); BusProvider.unregister(this); super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // } // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple; @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mAttachedToWindow = true; if (mImageView.getAlpha() == 0) fadeIn(); BusProvider.getInstance().register(this); } @Override protected void onDetachedFromWindow() { mAttachedToWindow = false; mImageView.animate().cancel(); mImageView.setAlpha(1f); BusProvider.unregister(this); super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe
public void onPlay(OnPlay onPlay) {
sregg/spotify-tv
app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple;
@Override protected void onDetachedFromWindow() { mAttachedToWindow = false; mImageView.animate().cancel(); mImageView.setAlpha(1f); BusProvider.unregister(this); super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe public void onPlay(OnPlay onPlay) { if (isSelf(onPlay)) { mNowPlayingView.startAnimation(); } } @SuppressWarnings("unused") @Subscribe
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // } // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple; @Override protected void onDetachedFromWindow() { mAttachedToWindow = false; mImageView.animate().cancel(); mImageView.setAlpha(1f); BusProvider.unregister(this); super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe public void onPlay(OnPlay onPlay) { if (isSelf(onPlay)) { mNowPlayingView.startAnimation(); } } @SuppressWarnings("unused") @Subscribe
public void onPause(OnPause onPause) {
sregg/spotify-tv
app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple;
super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe public void onPlay(OnPlay onPlay) { if (isSelf(onPlay)) { mNowPlayingView.startAnimation(); } } @SuppressWarnings("unused") @Subscribe public void onPause(OnPause onPause) { if (isSelf(onPause)) { mNowPlayingView.stopAnimations(); } }
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // } // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple; super.onDetachedFromWindow(); } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe public void onPlay(OnPlay onPlay) { if (isSelf(onPlay)) { mNowPlayingView.startAnimation(); } } @SuppressWarnings("unused") @Subscribe public void onPause(OnPause onPause) { if (isSelf(onPause)) { mNowPlayingView.stopAnimations(); } }
private boolean isSelf(AbsPlayingEvent playingEvent) {
sregg/spotify-tv
app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple;
} public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe public void onPlay(OnPlay onPlay) { if (isSelf(onPlay)) { mNowPlayingView.startAnimation(); } } @SuppressWarnings("unused") @Subscribe public void onPause(OnPause onPause) { if (isSelf(onPause)) { mNowPlayingView.stopAnimations(); } } private boolean isSelf(AbsPlayingEvent playingEvent) {
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/AbsPlayingEvent.java // public class AbsPlayingEvent { // private final ContentState mContentState; // // public AbsPlayingEvent(ContentState contentState) { // mContentState = contentState; // } // // public ContentState getPlayingState() { // return mContentState; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/ContentState.java // public class ContentState { // private final String mCurrentObjectUri; // private final List<TrackSimple> mTracksQueue; // private String mCurrentTrackUri; // private List<String> mTrackUrisQueue; // private TrackSimple mCurrentTrack; // // public ContentState(String currentObjectUri, String currentTrackUri, List<String> trackUrisQueue, List<TrackSimple> tracksQueue) { // mCurrentObjectUri = currentObjectUri; // mCurrentTrackUri = currentTrackUri; // mTrackUrisQueue = trackUrisQueue; // mTracksQueue = tracksQueue; // } // // /** // * @return the currently playing object (can be a playlist, an album or a single track) // */ // public String getCurrentObjectUri() { // return mCurrentObjectUri; // } // // public void setCurrentTrackUri(String currentTrackUri) { // mCurrentTrackUri = currentTrackUri; // } // // public boolean isCurrentObject(String objectUri) { // return mCurrentObjectUri.equals(objectUri); // } // // public boolean isCurrentTrack(String trackUri) { // return mCurrentTrackUri.equals(trackUri); // } // // public List<String> getTrackUrisQueue() { // return mTrackUrisQueue; // } // // public void setCurrentTrack(TrackSimple currentTrack) { // mCurrentTrack = currentTrack; // } // // public TrackSimple getCurrentTrack() { // return mCurrentTrack; // } // // public List<TrackSimple> getTracksQueue() { // return mTracksQueue; // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPause.java // public class OnPause extends AbsPlayingEvent { // // public OnPause(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnPlay.java // public class OnPlay extends AbsPlayingEvent { // public OnPlay(ContentState contentState) { // super(contentState); // } // } // // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/events/OnTrackChanged.java // public class OnTrackChanged extends AbsPlayingEvent { // public OnTrackChanged(ContentState contentState) { // super(contentState); // } // } // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/views/SpotifyCardView.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.v17.leanback.widget.BaseCardView; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.squareup.otto.Subscribe; import com.sregg.android.tv.spotifyPlayer.BusProvider; import com.sregg.android.tv.spotifyPlayer.R; import com.sregg.android.tv.spotifyPlayer.events.AbsPlayingEvent; import com.sregg.android.tv.spotifyPlayer.events.ContentState; import com.sregg.android.tv.spotifyPlayer.events.OnPause; import com.sregg.android.tv.spotifyPlayer.events.OnPlay; import com.sregg.android.tv.spotifyPlayer.events.OnTrackChanged; import com.sregg.android.tv.spotifyPlayer.utils.Utils; import kaaes.spotify.webapi.android.models.TrackSimple; } public void setItem(Object item) { mItem = item; mUri = Utils.getUriFromSpotiyObject(item); } @SuppressWarnings("unused") @Subscribe public void onTrackChanged(OnTrackChanged onTrackChanged) { initNowPlaying(isSelf(onTrackChanged)); } @SuppressWarnings("unused") @Subscribe public void onPlay(OnPlay onPlay) { if (isSelf(onPlay)) { mNowPlayingView.startAnimation(); } } @SuppressWarnings("unused") @Subscribe public void onPause(OnPause onPause) { if (isSelf(onPause)) { mNowPlayingView.stopAnimations(); } } private boolean isSelf(AbsPlayingEvent playingEvent) {
ContentState contentState = playingEvent.getPlayingState();
sregg/spotify-tv
app/src/main/java/com/sregg/android/tv/spotifyPlayer/controllers/MediaButtonReceiver.java
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/enums/Control.java // public enum Control { // PLAY("{fa-play}"), // PAUSE("{fa-pause}"), // NEXT("{fa-step-forward}"), // PREVIOUS("{fa-step-backward}"), // STOP("{fa-stop}"), // SHUFFLE("{fa-random}"), // FAST_FORWARD("{fa-fast-forward}"), // REWIND("{fa-rewind}"); // // private final String mFontId; // // Control(String fontId) { // mFontId = fontId; // } // // public String getFontId() { // return mFontId; // } // }
import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.support.v4.media.session.MediaSessionCompat; import android.view.KeyEvent; import com.sregg.android.tv.spotifyPlayer.enums.Control; import timber.log.Timber;
package com.sregg.android.tv.spotifyPlayer.controllers; /** * Created by gw111zz on 24/01/2016. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class MediaButtonReceiver extends MediaSessionCompat.Callback { private static final String TAG = "MediaButtonReceiver"; private final SpotifyPlayerController mPlayer; public MediaButtonReceiver(SpotifyPlayerController player) { mPlayer = player; } @Override public boolean onMediaButtonEvent(Intent mediaButtonIntent) { final KeyEvent event = (KeyEvent) mediaButtonIntent.getExtras().get(Intent.EXTRA_KEY_EVENT); Timber.d("onMediaButtonEvent: %s", (event == null ? "null" : event)); if (event == null) { return super.onMediaButtonEvent(mediaButtonIntent); } if (event.getAction() == KeyEvent.ACTION_DOWN) { final int keyCode = event.getKeyCode(); switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PLAY:
// Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/enums/Control.java // public enum Control { // PLAY("{fa-play}"), // PAUSE("{fa-pause}"), // NEXT("{fa-step-forward}"), // PREVIOUS("{fa-step-backward}"), // STOP("{fa-stop}"), // SHUFFLE("{fa-random}"), // FAST_FORWARD("{fa-fast-forward}"), // REWIND("{fa-rewind}"); // // private final String mFontId; // // Control(String fontId) { // mFontId = fontId; // } // // public String getFontId() { // return mFontId; // } // } // Path: app/src/main/java/com/sregg/android/tv/spotifyPlayer/controllers/MediaButtonReceiver.java import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.support.v4.media.session.MediaSessionCompat; import android.view.KeyEvent; import com.sregg.android.tv.spotifyPlayer.enums.Control; import timber.log.Timber; package com.sregg.android.tv.spotifyPlayer.controllers; /** * Created by gw111zz on 24/01/2016. */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class MediaButtonReceiver extends MediaSessionCompat.Callback { private static final String TAG = "MediaButtonReceiver"; private final SpotifyPlayerController mPlayer; public MediaButtonReceiver(SpotifyPlayerController player) { mPlayer = player; } @Override public boolean onMediaButtonEvent(Intent mediaButtonIntent) { final KeyEvent event = (KeyEvent) mediaButtonIntent.getExtras().get(Intent.EXTRA_KEY_EVENT); Timber.d("onMediaButtonEvent: %s", (event == null ? "null" : event)); if (event == null) { return super.onMediaButtonEvent(mediaButtonIntent); } if (event.getAction() == KeyEvent.ACTION_DOWN) { final int keyCode = event.getKeyCode(); switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PLAY:
mPlayer.onControlClick(Control.PLAY);
dstjacques/JHotKeys
examples/GlobalHotKeyExample.java
// Path: src/main/java/com/dstjacques/jhotkeys/JHotKeys.java // public class JHotKeys // { // public JHotKeyController control; // // public JHotKeys(String libPath) // { // String os = System.getProperty("os.name").toLowerCase(); // // if(os.indexOf("win") > -1) // { // this.control = new WindowsHotKeyController(libPath); // } // else if(os.indexOf("nux") > -1 || os.indexOf("nix") > -1) // { // this.control = new UnixHotKeyController(libPath); // } // else // { // System.out.println("Operating system not supported"); // this.control = null; // } // } // // public void registerHotKey(int id, int modifier, int key) // { // this.control.registerHotKey(id, modifier, key); // } // // public void unregisterHotKey(int id) // { // this.control.unregisterHotKey(id); // } // // public void addHotKeyListener(JHotKeyListener l) // { // this.control.addHotKeyListener(l); // } // // } // // Path: src/main/java/com/dstjacques/jhotkeys/JHotKeyListener.java // public interface JHotKeyListener // { // public void onHotKey(int id); // }
import com.dstjacques.jhotkeys.JHotKeys; import com.dstjacques.jhotkeys.JHotKeyListener;
public class GlobalHotKeyExample { public static void main(String[] args) { // Initialize an object with global hotkey support // and tell it where the "lib" folder with native // libraries are
// Path: src/main/java/com/dstjacques/jhotkeys/JHotKeys.java // public class JHotKeys // { // public JHotKeyController control; // // public JHotKeys(String libPath) // { // String os = System.getProperty("os.name").toLowerCase(); // // if(os.indexOf("win") > -1) // { // this.control = new WindowsHotKeyController(libPath); // } // else if(os.indexOf("nux") > -1 || os.indexOf("nix") > -1) // { // this.control = new UnixHotKeyController(libPath); // } // else // { // System.out.println("Operating system not supported"); // this.control = null; // } // } // // public void registerHotKey(int id, int modifier, int key) // { // this.control.registerHotKey(id, modifier, key); // } // // public void unregisterHotKey(int id) // { // this.control.unregisterHotKey(id); // } // // public void addHotKeyListener(JHotKeyListener l) // { // this.control.addHotKeyListener(l); // } // // } // // Path: src/main/java/com/dstjacques/jhotkeys/JHotKeyListener.java // public interface JHotKeyListener // { // public void onHotKey(int id); // } // Path: examples/GlobalHotKeyExample.java import com.dstjacques.jhotkeys.JHotKeys; import com.dstjacques.jhotkeys.JHotKeyListener; public class GlobalHotKeyExample { public static void main(String[] args) { // Initialize an object with global hotkey support // and tell it where the "lib" folder with native // libraries are
JHotKeys hotkeys = new JHotKeys("../lib");
dstjacques/JHotKeys
examples/GlobalHotKeyExample.java
// Path: src/main/java/com/dstjacques/jhotkeys/JHotKeys.java // public class JHotKeys // { // public JHotKeyController control; // // public JHotKeys(String libPath) // { // String os = System.getProperty("os.name").toLowerCase(); // // if(os.indexOf("win") > -1) // { // this.control = new WindowsHotKeyController(libPath); // } // else if(os.indexOf("nux") > -1 || os.indexOf("nix") > -1) // { // this.control = new UnixHotKeyController(libPath); // } // else // { // System.out.println("Operating system not supported"); // this.control = null; // } // } // // public void registerHotKey(int id, int modifier, int key) // { // this.control.registerHotKey(id, modifier, key); // } // // public void unregisterHotKey(int id) // { // this.control.unregisterHotKey(id); // } // // public void addHotKeyListener(JHotKeyListener l) // { // this.control.addHotKeyListener(l); // } // // } // // Path: src/main/java/com/dstjacques/jhotkeys/JHotKeyListener.java // public interface JHotKeyListener // { // public void onHotKey(int id); // }
import com.dstjacques.jhotkeys.JHotKeys; import com.dstjacques.jhotkeys.JHotKeyListener;
public class GlobalHotKeyExample { public static void main(String[] args) { // Initialize an object with global hotkey support // and tell it where the "lib" folder with native // libraries are JHotKeys hotkeys = new JHotKeys("../lib"); // Global hotkey on pressing 'A' hotkeys.registerHotKey(0, 0, (int)'A'); // Global hotkey on pressing 'WIN_KEY' + 'B' hotkeys.registerHotKey(1, 8, (int)'B');
// Path: src/main/java/com/dstjacques/jhotkeys/JHotKeys.java // public class JHotKeys // { // public JHotKeyController control; // // public JHotKeys(String libPath) // { // String os = System.getProperty("os.name").toLowerCase(); // // if(os.indexOf("win") > -1) // { // this.control = new WindowsHotKeyController(libPath); // } // else if(os.indexOf("nux") > -1 || os.indexOf("nix") > -1) // { // this.control = new UnixHotKeyController(libPath); // } // else // { // System.out.println("Operating system not supported"); // this.control = null; // } // } // // public void registerHotKey(int id, int modifier, int key) // { // this.control.registerHotKey(id, modifier, key); // } // // public void unregisterHotKey(int id) // { // this.control.unregisterHotKey(id); // } // // public void addHotKeyListener(JHotKeyListener l) // { // this.control.addHotKeyListener(l); // } // // } // // Path: src/main/java/com/dstjacques/jhotkeys/JHotKeyListener.java // public interface JHotKeyListener // { // public void onHotKey(int id); // } // Path: examples/GlobalHotKeyExample.java import com.dstjacques.jhotkeys.JHotKeys; import com.dstjacques.jhotkeys.JHotKeyListener; public class GlobalHotKeyExample { public static void main(String[] args) { // Initialize an object with global hotkey support // and tell it where the "lib" folder with native // libraries are JHotKeys hotkeys = new JHotKeys("../lib"); // Global hotkey on pressing 'A' hotkeys.registerHotKey(0, 0, (int)'A'); // Global hotkey on pressing 'WIN_KEY' + 'B' hotkeys.registerHotKey(1, 8, (int)'B');
JHotKeyListener hotkeyListener = new JHotKeyListener(){
MiniDigger/projecttd
core/src/me/minidigger/projecttd/ProjectTD.java
// Path: core/src/me/minidigger/projecttd/screens/MainMenuScreen.java // public class MainMenuScreen implements Screen { // // private Stage stage; // // @Override // public void show() { // stage = new Stage(); // Gdx.input.setInputProcessor(stage); // // VisUI.load(); // // VisTable table = new VisTable(true); // // VisTextButton newGameButton = new VisTextButton("New game"); // newGameButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 100, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // newGameButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // GameScreen gameScreen = new GameScreen(); // gameScreen.level = LevelManager.getInstance().getLevels().get(0); // ((Game) Gdx.app.getApplicationListener()).setScreen(gameScreen); // } // }); // table.add(newGameButton); // stage.addActor(newGameButton); // // VisTextButton levelSelectButton = new VisTextButton("Level Select"); // levelSelectButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 50, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // levelSelectButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // ((Game) Gdx.app.getApplicationListener()).setScreen(new LevelSelectScreen()); // } // }); // table.add(levelSelectButton); // stage.addActor(levelSelectButton); // // VisTextButton levelEditorButton = new VisTextButton("Level Editor"); // levelEditorButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 0, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // levelEditorButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // System.out.println("level editor");//TODO level editor // } // }); // table.add(levelEditorButton); // stage.addActor(levelEditorButton); // // VisTextButton settingsButton = new VisTextButton("Settings"); // settingsButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) - 50, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // settingsButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // ((Game) Gdx.app.getApplicationListener()).setScreen(new OptionsScreen()); // } // }); // table.add(settingsButton); // stage.addActor(settingsButton); // // VisTextButton creditsButton = new VisTextButton("Credits"); // creditsButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) - 100, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // creditsButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // ((Game) Gdx.app.getApplicationListener()).setScreen(new CreditsScreen()); // } // }); // table.add(creditsButton); // stage.addActor(creditsButton); // // VisTextButton quitButton = new VisTextButton("Quit"); // quitButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) - 150, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // quitButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // Gdx.app.exit(); // } // }); // table.add(quitButton); // stage.addActor(quitButton); // } // // @Override // public void render(float delta) { // Gdx.gl.glClearColor(1, 1, 1, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // // stage.act(); // stage.draw(); // } // // @Override // public void resize(int width, int height) { // // } // // @Override // public void pause() { // // } // // @Override // public void resume() { // // } // // @Override // public void hide() { // VisUI.dispose(); // } // // @Override // public void dispose() { // } // }
import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import me.minidigger.projecttd.screens.MainMenuScreen;
package me.minidigger.projecttd; public class ProjectTD extends Game { public static final int V_WIDTH = 640; public static final int V_HEIGHT = 480; @Override public void create() { //Gdx.app.setLogLevel(Application.LOG_DEBUG);
// Path: core/src/me/minidigger/projecttd/screens/MainMenuScreen.java // public class MainMenuScreen implements Screen { // // private Stage stage; // // @Override // public void show() { // stage = new Stage(); // Gdx.input.setInputProcessor(stage); // // VisUI.load(); // // VisTable table = new VisTable(true); // // VisTextButton newGameButton = new VisTextButton("New game"); // newGameButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 100, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // newGameButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // GameScreen gameScreen = new GameScreen(); // gameScreen.level = LevelManager.getInstance().getLevels().get(0); // ((Game) Gdx.app.getApplicationListener()).setScreen(gameScreen); // } // }); // table.add(newGameButton); // stage.addActor(newGameButton); // // VisTextButton levelSelectButton = new VisTextButton("Level Select"); // levelSelectButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 50, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // levelSelectButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // ((Game) Gdx.app.getApplicationListener()).setScreen(new LevelSelectScreen()); // } // }); // table.add(levelSelectButton); // stage.addActor(levelSelectButton); // // VisTextButton levelEditorButton = new VisTextButton("Level Editor"); // levelEditorButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 0, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // levelEditorButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // System.out.println("level editor");//TODO level editor // } // }); // table.add(levelEditorButton); // stage.addActor(levelEditorButton); // // VisTextButton settingsButton = new VisTextButton("Settings"); // settingsButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) - 50, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // settingsButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // ((Game) Gdx.app.getApplicationListener()).setScreen(new OptionsScreen()); // } // }); // table.add(settingsButton); // stage.addActor(settingsButton); // // VisTextButton creditsButton = new VisTextButton("Credits"); // creditsButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) - 100, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // creditsButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // ((Game) Gdx.app.getApplicationListener()).setScreen(new CreditsScreen()); // } // }); // table.add(creditsButton); // stage.addActor(creditsButton); // // VisTextButton quitButton = new VisTextButton("Quit"); // quitButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) - 150, 200, 50); // // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); // quitButton.addListener(new ClickListener() { // @Override // public void clicked(InputEvent event, float x, float y) { // Gdx.app.exit(); // } // }); // table.add(quitButton); // stage.addActor(quitButton); // } // // @Override // public void render(float delta) { // Gdx.gl.glClearColor(1, 1, 1, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // // stage.act(); // stage.draw(); // } // // @Override // public void resize(int width, int height) { // // } // // @Override // public void pause() { // // } // // @Override // public void resume() { // // } // // @Override // public void hide() { // VisUI.dispose(); // } // // @Override // public void dispose() { // } // } // Path: core/src/me/minidigger/projecttd/ProjectTD.java import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import me.minidigger.projecttd.screens.MainMenuScreen; package me.minidigger.projecttd; public class ProjectTD extends Game { public static final int V_WIDTH = 640; public static final int V_HEIGHT = 480; @Override public void create() { //Gdx.app.setLogLevel(Application.LOG_DEBUG);
setScreen(new MainMenuScreen());
MiniDigger/projecttd
core/src/me/minidigger/projecttd/level/LevelManager.java
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors;
package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f);
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // } // Path: core/src/me/minidigger/projecttd/level/LevelManager.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors; package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f);
Wave wave = new WaveBuilder().waveType(WaveType.NORMAL).name("Wave 1").points(100).money(10)
MiniDigger/projecttd
core/src/me/minidigger/projecttd/level/LevelManager.java
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors;
package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f);
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // } // Path: core/src/me/minidigger/projecttd/level/LevelManager.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors; package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f);
Wave wave = new WaveBuilder().waveType(WaveType.NORMAL).name("Wave 1").points(100).money(10)
MiniDigger/projecttd
core/src/me/minidigger/projecttd/level/LevelManager.java
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors;
package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f);
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // } // Path: core/src/me/minidigger/projecttd/level/LevelManager.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors; package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f);
Wave wave = new WaveBuilder().waveType(WaveType.NORMAL).name("Wave 1").points(100).money(10)
MiniDigger/projecttd
core/src/me/minidigger/projecttd/level/LevelManager.java
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors;
package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f); Wave wave = new WaveBuilder().waveType(WaveType.NORMAL).name("Wave 1").points(100).money(10)
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // // Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveBuilder.java // public class WaveBuilder { // // private Wave wave = new Wave(); // // public WaveGroupBuilder group() { // return new WaveGroupBuilder(this); // } // // public WaveBuilder name(String name) { // wave.setName(name); // return this; // } // // public WaveBuilder waveType(WaveType type) { // wave.setType(type); // return this; // } // // public WaveBuilder points(int points) { // wave.setPoints(points); // return this; // } // // public WaveBuilder money(float amount) { // wave.setMoney(amount); // return this; // } // // public WaveBuilder group(WaveGroup group) { // wave.addGroup(group); // return this; // } // // public Wave build() { // checkNotNull(wave.getName(), "You need to specify a name for the wave using name()"); // checkNotNull(wave.getGroups(), "You need to specify at least one group for this wave using group()"); // // return wave; // } // } // // Path: core/src/me/minidigger/projecttd/wave/WaveType.java // public enum WaveType { // // NORMAL, // BOSS; // /* TODO add more special wave types */ // } // Path: core/src/me/minidigger/projecttd/level/LevelManager.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.minidigger.projecttd.entities.Minion; import me.minidigger.projecttd.wave.Wave; import me.minidigger.projecttd.wave.WaveBuilder; import me.minidigger.projecttd.wave.WaveType; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.logging.FileHandler; import java.util.stream.Collectors; package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class LevelManager { private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private List<Level> levels = new ArrayList<>(); private LevelManager() { load(); } public List<Level> getLevels() { if (levels.size() == 0) { Vector2 spawn = new Vector2(1.5f, 9.5f); Vector2 goal = new Vector2(39.5f, 5.5f); Wave wave = new WaveBuilder().waveType(WaveType.NORMAL).name("Wave 1").points(100).money(10)
.group().delay(5).interval(1).health(100).speed(6).type(Minion.MinionType.LAND).count(10).sprite(Minion.SPRITE).spawn(spawn).goal(goal).finish()
MiniDigger/projecttd
core/src/me/minidigger/projecttd/systems/MovementSystem.java
// Path: core/src/me/minidigger/projecttd/components/TransformComponent.java // public class TransformComponent implements Component, Pool.Poolable { // // public Vector2 position; // public float rotation = 0f; // // @Override // public void reset() { // position = new Vector2(); // rotation = 0f; // } // } // // Path: core/src/me/minidigger/projecttd/components/VelocityComponent.java // public class VelocityComponent implements Component, Pool.Poolable { // // public Vector2 linear = new Vector2(); // public float angular = 0f; // // @Override // public void reset() { // linear = new Vector2(); // angular = 0f; // } // }
import com.badlogic.ashley.core.ComponentMapper; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import me.minidigger.projecttd.components.TransformComponent; import me.minidigger.projecttd.components.VelocityComponent;
package me.minidigger.projecttd.systems; /** * Created by Martin on 02.04.2017. */ public class MovementSystem extends IteratingSystem { private ComponentMapper<TransformComponent> pm = ComponentMapper.getFor(TransformComponent.class);
// Path: core/src/me/minidigger/projecttd/components/TransformComponent.java // public class TransformComponent implements Component, Pool.Poolable { // // public Vector2 position; // public float rotation = 0f; // // @Override // public void reset() { // position = new Vector2(); // rotation = 0f; // } // } // // Path: core/src/me/minidigger/projecttd/components/VelocityComponent.java // public class VelocityComponent implements Component, Pool.Poolable { // // public Vector2 linear = new Vector2(); // public float angular = 0f; // // @Override // public void reset() { // linear = new Vector2(); // angular = 0f; // } // } // Path: core/src/me/minidigger/projecttd/systems/MovementSystem.java import com.badlogic.ashley.core.ComponentMapper; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import me.minidigger.projecttd.components.TransformComponent; import me.minidigger.projecttd.components.VelocityComponent; package me.minidigger.projecttd.systems; /** * Created by Martin on 02.04.2017. */ public class MovementSystem extends IteratingSystem { private ComponentMapper<TransformComponent> pm = ComponentMapper.getFor(TransformComponent.class);
private ComponentMapper<VelocityComponent> vm = ComponentMapper.getFor(VelocityComponent.class);
MiniDigger/projecttd
core/src/me/minidigger/projecttd/level/Level.java
// Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // }
import me.minidigger.projecttd.wave.Wave; import java.util.List;
package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class Level { private String name; private String file; private String author; private String thumbnail;
// Path: core/src/me/minidigger/projecttd/wave/Wave.java // public class Wave { // // private List<WaveGroup> groups; // private String name; // private WaveType type = WaveType.NORMAL; // private int points = 100; // private float money = 10; // // public void addGroup(WaveGroup group) { // if (groups == null) { // groups = new ArrayList<>(); // } // groups.add(group); // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setType(WaveType type) { // this.type = type; // } // // public WaveType getType() { // return type; // } // // public void setPoints(int points) { // this.points = points; // } // // public int getPoints() { // return points; // } // // public void setMoney(float money) { // this.money = money; // } // // public float getMoney() { // return money; // } // // public List<WaveGroup> getGroups() { // return groups; // } // // public void setGroups(List<WaveGroup> groups) { // this.groups = groups; // } // } // Path: core/src/me/minidigger/projecttd/level/Level.java import me.minidigger.projecttd.wave.Wave; import java.util.List; package me.minidigger.projecttd.level; /** * Created by Martin on 29/04/2017. */ public class Level { private String name; private String file; private String author; private String thumbnail;
private List<Wave> waves;
MiniDigger/projecttd
core/src/me/minidigger/projecttd/screens/MainMenuScreen.java
// Path: core/src/me/minidigger/projecttd/level/LevelManager.java // public class LevelManager { // // private Gson gson = new GsonBuilder().setPrettyPrinting().create(); // private List<Level> levels = new ArrayList<>(); // // private LevelManager() { // load(); // } // // public List<Level> getLevels() { // if (levels.size() == 0) { // Vector2 spawn = new Vector2(1.5f, 9.5f); // Vector2 goal = new Vector2(39.5f, 5.5f); // Wave wave = new WaveBuilder().waveType(WaveType.NORMAL).name("Wave 1").points(100).money(10) // .group().delay(5).interval(1).health(100).speed(6).type(Minion.MinionType.LAND).count(10).sprite(Minion.SPRITE).spawn(spawn).goal(goal).finish() // .group().delay(20).interval(2).health(300).speed(4).type(Minion.MinionType.LAND).count(5).sprite(Minion.SPRITE).spawn(spawn).goal(goal).finish() // .group().delay(30).interval(1).health(1000).speed(2).type(Minion.MinionType.LAND).count(1).sprite(Minion.SPRITE).spawn(spawn).goal(goal).finish() // .build(); // List<Wave> waves = new ArrayList<>(); // waves.add(wave); // // levels.add(new Level("Map 1", "map01.tmx", "MiniDigger", "badlogic.jpg", waves)); // // levels.add(new Level("Map 2", "map02.tmx", "MiniDigger", "badlogic.jpg", waves)); // // //DEBUG DEBUG // try (Writer writer = Gdx.files.absolute("maps/map01.json").writer(false)) { // gson.toJson(levels.get(0), writer); // } catch (IOException ex) { // } // try (Writer writer = Gdx.files.absolute("maps/map02.json").writer(false)) { // gson.toJson(levels.get(1), writer); // } catch (IOException ex) { // } // // load(); // } // return levels; // } // // public void load() { // levels = Arrays.stream(Gdx.files.internal("maps").list()) // .filter(f -> f.extension().equalsIgnoreCase("json")) // .map(f -> gson.fromJson(f.reader(), Level.class)) // .filter(Objects::nonNull) // .collect(Collectors.toList()); // // Gdx.app.log("DEBUG", "Loaded " + levels.size() + " levels"); // } // // private static LevelManager instance = new LevelManager(); // // public static LevelManager getInstance() { // return instance; // } // }
import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.kotcrab.vis.ui.VisUI; import com.kotcrab.vis.ui.widget.VisTable; import com.kotcrab.vis.ui.widget.VisTextButton; import me.minidigger.projecttd.level.LevelManager;
package me.minidigger.projecttd.screens; /** * Created by Martin on 29/04/2017. */ public class MainMenuScreen implements Screen { private Stage stage; @Override public void show() { stage = new Stage(); Gdx.input.setInputProcessor(stage); VisUI.load(); VisTable table = new VisTable(true); VisTextButton newGameButton = new VisTextButton("New game"); newGameButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 100, 200, 50); // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); newGameButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { GameScreen gameScreen = new GameScreen();
// Path: core/src/me/minidigger/projecttd/level/LevelManager.java // public class LevelManager { // // private Gson gson = new GsonBuilder().setPrettyPrinting().create(); // private List<Level> levels = new ArrayList<>(); // // private LevelManager() { // load(); // } // // public List<Level> getLevels() { // if (levels.size() == 0) { // Vector2 spawn = new Vector2(1.5f, 9.5f); // Vector2 goal = new Vector2(39.5f, 5.5f); // Wave wave = new WaveBuilder().waveType(WaveType.NORMAL).name("Wave 1").points(100).money(10) // .group().delay(5).interval(1).health(100).speed(6).type(Minion.MinionType.LAND).count(10).sprite(Minion.SPRITE).spawn(spawn).goal(goal).finish() // .group().delay(20).interval(2).health(300).speed(4).type(Minion.MinionType.LAND).count(5).sprite(Minion.SPRITE).spawn(spawn).goal(goal).finish() // .group().delay(30).interval(1).health(1000).speed(2).type(Minion.MinionType.LAND).count(1).sprite(Minion.SPRITE).spawn(spawn).goal(goal).finish() // .build(); // List<Wave> waves = new ArrayList<>(); // waves.add(wave); // // levels.add(new Level("Map 1", "map01.tmx", "MiniDigger", "badlogic.jpg", waves)); // // levels.add(new Level("Map 2", "map02.tmx", "MiniDigger", "badlogic.jpg", waves)); // // //DEBUG DEBUG // try (Writer writer = Gdx.files.absolute("maps/map01.json").writer(false)) { // gson.toJson(levels.get(0), writer); // } catch (IOException ex) { // } // try (Writer writer = Gdx.files.absolute("maps/map02.json").writer(false)) { // gson.toJson(levels.get(1), writer); // } catch (IOException ex) { // } // // load(); // } // return levels; // } // // public void load() { // levels = Arrays.stream(Gdx.files.internal("maps").list()) // .filter(f -> f.extension().equalsIgnoreCase("json")) // .map(f -> gson.fromJson(f.reader(), Level.class)) // .filter(Objects::nonNull) // .collect(Collectors.toList()); // // Gdx.app.log("DEBUG", "Loaded " + levels.size() + " levels"); // } // // private static LevelManager instance = new LevelManager(); // // public static LevelManager getInstance() { // return instance; // } // } // Path: core/src/me/minidigger/projecttd/screens/MainMenuScreen.java import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.kotcrab.vis.ui.VisUI; import com.kotcrab.vis.ui.widget.VisTable; import com.kotcrab.vis.ui.widget.VisTextButton; import me.minidigger.projecttd.level.LevelManager; package me.minidigger.projecttd.screens; /** * Created by Martin on 29/04/2017. */ public class MainMenuScreen implements Screen { private Stage stage; @Override public void show() { stage = new Stage(); Gdx.input.setInputProcessor(stage); VisUI.load(); VisTable table = new VisTable(true); VisTextButton newGameButton = new VisTextButton("New game"); newGameButton.setBounds((Gdx.graphics.getWidth() / 2f) - 100, (Gdx.graphics.getHeight() / 2f) + 100, 200, 50); // newGameButton.setPosition(Gdx.graphics.getWidth() / 2 - Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 2); newGameButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { GameScreen gameScreen = new GameScreen();
gameScreen.level = LevelManager.getInstance().getLevels().get(0);
MiniDigger/projecttd
core/src/me/minidigger/projecttd/wave/WaveGroupBuilder.java
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // }
import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; import com.google.common.base.Preconditions; import me.minidigger.projecttd.entities.Minion;
package me.minidigger.projecttd.wave; /** * Created by Martin on 13/05/2017. */ public class WaveGroupBuilder { private WaveGroup group = new WaveGroup(); private WaveBuilder builder; WaveGroupBuilder(WaveBuilder builder) { this.builder = builder; } public WaveGroupBuilder delay(float delay) { group.setDelay(delay); return this; } public WaveGroupBuilder interval(float interval) { group.setInterval(interval); return this; } public WaveGroupBuilder count(int count) { group.setCount(count); return this; } public WaveGroupBuilder health(float health) { group.setHealth(health); return this; } public WaveGroupBuilder speed(float speed) { group.setSpeed(speed); return this; }
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public class Minion { // // public static PooledEngine ENGINE; // public static Sprite SPRITE; // // public static Entity newMinion(Vector2 spawn) { // Entity entity = ENGINE.createEntity(); // // SpriteComponent spriteComponent = ENGINE.createComponent(SpriteComponent.class); // spriteComponent.sprite = SPRITE; // entity.add(spriteComponent); // // VelocityComponent velocityComponent = ENGINE.createComponent(VelocityComponent.class); // entity.add(velocityComponent); // // TransformComponent transformComponent = ENGINE.createComponent(TransformComponent.class); // transformComponent.position = spawn; // entity.add(transformComponent); // // HealthComponent healthComponent = ENGINE.createComponent(HealthComponent.class); // healthComponent.health = 100; // entity.add(healthComponent); // // PathComponent pathComponent = ENGINE.createComponent(PathComponent.class); // entity.add(pathComponent); // // MinionComponent minionComponent = ENGINE.createComponent(MinionComponent.class); // entity.add(minionComponent); // // ENGINE.addEntity(entity); // return entity; // } // // public enum MinionType{ // LAND, // WATER, // AIR; // } // } // Path: core/src/me/minidigger/projecttd/wave/WaveGroupBuilder.java import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; import com.google.common.base.Preconditions; import me.minidigger.projecttd.entities.Minion; package me.minidigger.projecttd.wave; /** * Created by Martin on 13/05/2017. */ public class WaveGroupBuilder { private WaveGroup group = new WaveGroup(); private WaveBuilder builder; WaveGroupBuilder(WaveBuilder builder) { this.builder = builder; } public WaveGroupBuilder delay(float delay) { group.setDelay(delay); return this; } public WaveGroupBuilder interval(float interval) { group.setInterval(interval); return this; } public WaveGroupBuilder count(int count) { group.setCount(count); return this; } public WaveGroupBuilder health(float health) { group.setHealth(health); return this; } public WaveGroupBuilder speed(float speed) { group.setSpeed(speed); return this; }
public WaveGroupBuilder type(Minion.MinionType type) {
MiniDigger/projecttd
desktop/src/me/minidigger/projecttd/desktop/DesktopLauncher.java
// Path: core/src/me/minidigger/projecttd/ProjectTD.java // public class ProjectTD extends Game { // // public static final int V_WIDTH = 640; // public static final int V_HEIGHT = 480; // // @Override // public void create() { // //Gdx.app.setLogLevel(Application.LOG_DEBUG); // setScreen(new MainMenuScreen()); // } // }
import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import me.minidigger.projecttd.ProjectTD;
package me.minidigger.projecttd.desktop; public class DesktopLauncher { public static void main(String[] arg) { //System.setProperty("org.lwjgl.util.Debug", "true"); LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
// Path: core/src/me/minidigger/projecttd/ProjectTD.java // public class ProjectTD extends Game { // // public static final int V_WIDTH = 640; // public static final int V_HEIGHT = 480; // // @Override // public void create() { // //Gdx.app.setLogLevel(Application.LOG_DEBUG); // setScreen(new MainMenuScreen()); // } // } // Path: desktop/src/me/minidigger/projecttd/desktop/DesktopLauncher.java import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import me.minidigger.projecttd.ProjectTD; package me.minidigger.projecttd.desktop; public class DesktopLauncher { public static void main(String[] arg) { //System.setProperty("org.lwjgl.util.Debug", "true"); LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = ProjectTD.V_WIDTH;
MiniDigger/projecttd
core/src/me/minidigger/projecttd/components/TurretComponent.java
// Path: core/src/me/minidigger/projecttd/systems/TurretSystem.java // public interface TargetSelectionStrategy { // TargetSelectionStrategy NEAREST = (current, data, dst, target) -> { // boolean exp = data == -1 || dst <= data; // return exp ? Pair.of(target, dst) : Pair.of(current, data); // }; // // TargetSelectionStrategy FURTHEST = (current, data, dst, target) -> { // boolean exp = data == -1 || dst > data; // return exp ? Pair.of(target, dst) : Pair.of(current, data); // }; // // TargetSelectionStrategy FIRST = (current, data, dst, target) -> { // float tilesToGoal = pathM.get(target).tilesToGoal; // boolean exp = data == -1 || tilesToGoal <= data; // return exp ? Pair.of(target, tilesToGoal) : Pair.of(current, data); // }; // // TargetSelectionStrategy LAST = (current, data, dst, target) -> { // float tilesToGoal = pathM.get(target).tilesToGoal; // boolean exp = data == -1 || tilesToGoal > data; // return exp ? Pair.of(target, tilesToGoal) : Pair.of(current, data); // }; // // TargetSelectionStrategy MIN_HEALTH = (current, data, dst, target) -> { // float health = healthM.get(target).health; // boolean exp = data == -1 || health <= data; // return exp ? Pair.of(target, health) : Pair.of(current, data); // }; // // TargetSelectionStrategy MAX_HEALTH = (current, data, dst, target) -> { // float health = healthM.get(target).health; // boolean exp = data == -1 || health > data; // return exp ? Pair.of(target, health) : Pair.of(current, data); // }; // // Pair<Entity, Float> calculate(Entity currentFav, float currentFavData, float dst, Entity target); // }
import com.badlogic.ashley.core.Component; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.utils.Pool.Poolable; import me.minidigger.projecttd.systems.TurretSystem.TargetSelectionStrategy;
package me.minidigger.projecttd.components; /** * Created by Martin on 29/04/2017. */ public class TurretComponent implements Component, Poolable { public Entity target; public float range = 2; public float attackSpeed = 1;
// Path: core/src/me/minidigger/projecttd/systems/TurretSystem.java // public interface TargetSelectionStrategy { // TargetSelectionStrategy NEAREST = (current, data, dst, target) -> { // boolean exp = data == -1 || dst <= data; // return exp ? Pair.of(target, dst) : Pair.of(current, data); // }; // // TargetSelectionStrategy FURTHEST = (current, data, dst, target) -> { // boolean exp = data == -1 || dst > data; // return exp ? Pair.of(target, dst) : Pair.of(current, data); // }; // // TargetSelectionStrategy FIRST = (current, data, dst, target) -> { // float tilesToGoal = pathM.get(target).tilesToGoal; // boolean exp = data == -1 || tilesToGoal <= data; // return exp ? Pair.of(target, tilesToGoal) : Pair.of(current, data); // }; // // TargetSelectionStrategy LAST = (current, data, dst, target) -> { // float tilesToGoal = pathM.get(target).tilesToGoal; // boolean exp = data == -1 || tilesToGoal > data; // return exp ? Pair.of(target, tilesToGoal) : Pair.of(current, data); // }; // // TargetSelectionStrategy MIN_HEALTH = (current, data, dst, target) -> { // float health = healthM.get(target).health; // boolean exp = data == -1 || health <= data; // return exp ? Pair.of(target, health) : Pair.of(current, data); // }; // // TargetSelectionStrategy MAX_HEALTH = (current, data, dst, target) -> { // float health = healthM.get(target).health; // boolean exp = data == -1 || health > data; // return exp ? Pair.of(target, health) : Pair.of(current, data); // }; // // Pair<Entity, Float> calculate(Entity currentFav, float currentFavData, float dst, Entity target); // } // Path: core/src/me/minidigger/projecttd/components/TurretComponent.java import com.badlogic.ashley.core.Component; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.utils.Pool.Poolable; import me.minidigger.projecttd.systems.TurretSystem.TargetSelectionStrategy; package me.minidigger.projecttd.components; /** * Created by Martin on 29/04/2017. */ public class TurretComponent implements Component, Poolable { public Entity target; public float range = 2; public float attackSpeed = 1;
public TargetSelectionStrategy strategy = TargetSelectionStrategy.FIRST;
MiniDigger/projecttd
html/src/me/minidigger/projecttd/client/HtmlLauncher.java
// Path: core/src/me/minidigger/projecttd/ProjectTD.java // public class ProjectTD extends Game { // // public static final int V_WIDTH = 640; // public static final int V_HEIGHT = 480; // // @Override // public void create() { // //Gdx.app.setLogLevel(Application.LOG_DEBUG); // setScreen(new MainMenuScreen()); // } // }
import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import me.minidigger.projecttd.ProjectTD;
package me.minidigger.projecttd.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig() {
// Path: core/src/me/minidigger/projecttd/ProjectTD.java // public class ProjectTD extends Game { // // public static final int V_WIDTH = 640; // public static final int V_HEIGHT = 480; // // @Override // public void create() { // //Gdx.app.setLogLevel(Application.LOG_DEBUG); // setScreen(new MainMenuScreen()); // } // } // Path: html/src/me/minidigger/projecttd/client/HtmlLauncher.java import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import me.minidigger.projecttd.ProjectTD; package me.minidigger.projecttd.client; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig() {
return new GwtApplicationConfiguration(ProjectTD.V_WIDTH, ProjectTD.V_HEIGHT);
MiniDigger/projecttd
core/src/me/minidigger/projecttd/wave/WaveGroup.java
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public enum MinionType{ // LAND, // WATER, // AIR; // }
import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; import me.minidigger.projecttd.entities.Minion.MinionType;
package me.minidigger.projecttd.wave; public class WaveGroup { private float delay = 0; private float interval = 0; private float health = 0; private float speed = 0;
// Path: core/src/me/minidigger/projecttd/entities/Minion.java // public enum MinionType{ // LAND, // WATER, // AIR; // } // Path: core/src/me/minidigger/projecttd/wave/WaveGroup.java import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; import me.minidigger.projecttd.entities.Minion.MinionType; package me.minidigger.projecttd.wave; public class WaveGroup { private float delay = 0; private float interval = 0; private float health = 0; private float speed = 0;
private MinionType type = MinionType.LAND;