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
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/parse/GetLikesCall.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/ApiCall.java // public abstract class ApiCall { // // protected ApiResponseCallback responseCallback; // // public ApiCall(ApiResponseCallback responseCallback) { // this.responseCallback = responseCallback; // } // // public abstract void call(); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/parse/response/GetLikesResponse.java // public class GetLikesResponse { // private static final int NO_EXIST = 0; // // Map<String, Integer> likes = new HashMap<String, Integer>(); // // public void add(String userId, int numLikes) { // likes.put(userId, numLikes); // } // // public int getNumLikes(String userId) { // if (likes.containsKey(userId)) { // return likes.get(userId); // } else { // return NO_EXIST; // } // } // // public Map<String, Integer> getAllLikers() { // return Collections.unmodifiableMap(likes); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // }
import com.flipper83.protohipster.feed.datasource.api.call.ApiCall; import com.flipper83.protohipster.feed.datasource.api.call.parse.response.GetLikesResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import java.util.List;
package com.flipper83.protohipster.feed.datasource.api.call.parse; /** * Obtain the number of likes for the users */ public class GetLikesCall extends ApiCall { private static final String LOGTAG = "GetLikesCall"; private final List<String> userIds; public GetLikesCall(List<String> userIds, ApiResponseCallback<GetLikesResponse> responseCallback) { super(responseCallback); this.userIds = userIds; } @Override public void call() { ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseLikeTableDefinitions.PARSE_LIKE_TABLE); query.whereContainedIn(ParseLikeTableDefinitions.PARSE_LIKE_USER_ID, userIds); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> parseLikes, ParseException e) { if (e == null) { GetLikesResponse response = new GetLikesResponse(); for (ParseObject likeObject : parseLikes) { String userId = likeObject.getString(ParseLikeTableDefinitions.PARSE_LIKE_USER_ID); int numLikes = likeObject.getInt(ParseLikeTableDefinitions.PARSE_LIKE_NUM_LIKES); response.add(userId, numLikes); } responseCallback.complete(response); } else {
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/ApiCall.java // public abstract class ApiCall { // // protected ApiResponseCallback responseCallback; // // public ApiCall(ApiResponseCallback responseCallback) { // this.responseCallback = responseCallback; // } // // public abstract void call(); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/parse/response/GetLikesResponse.java // public class GetLikesResponse { // private static final int NO_EXIST = 0; // // Map<String, Integer> likes = new HashMap<String, Integer>(); // // public void add(String userId, int numLikes) { // likes.put(userId, numLikes); // } // // public int getNumLikes(String userId) { // if (likes.containsKey(userId)) { // return likes.get(userId); // } else { // return NO_EXIST; // } // } // // public Map<String, Integer> getAllLikers() { // return Collections.unmodifiableMap(likes); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/parse/GetLikesCall.java import com.flipper83.protohipster.feed.datasource.api.call.ApiCall; import com.flipper83.protohipster.feed.datasource.api.call.parse.response.GetLikesResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import java.util.List; package com.flipper83.protohipster.feed.datasource.api.call.parse; /** * Obtain the number of likes for the users */ public class GetLikesCall extends ApiCall { private static final String LOGTAG = "GetLikesCall"; private final List<String> userIds; public GetLikesCall(List<String> userIds, ApiResponseCallback<GetLikesResponse> responseCallback) { super(responseCallback); this.userIds = userIds; } @Override public void call() { ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseLikeTableDefinitions.PARSE_LIKE_TABLE); query.whereContainedIn(ParseLikeTableDefinitions.PARSE_LIKE_USER_ID, userIds); query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> parseLikes, ParseException e) { if (e == null) { GetLikesResponse response = new GetLikesResponse(); for (ParseObject likeObject : parseLikes) { String userId = likeObject.getString(ParseLikeTableDefinitions.PARSE_LIKE_USER_ID); int numLikes = likeObject.getInt(ParseLikeTableDefinitions.PARSE_LIKE_NUM_LIKES); response.add(userId, numLikes); } responseCallback.complete(response); } else {
LoggerProvider.getLogger().d(LOGTAG, "Error retrying info from parse");
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // }
import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named;
package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest")
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest")
Api api;
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // }
import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named;
package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api;
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api;
private Collection<GetUserCallback> getUserCallbacks =
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // }
import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named;
package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api; private Collection<GetUserCallback> getUserCallbacks = Collections.synchronizedCollection(new ArrayList<GetUserCallback>()); UserDataSourceImp(Api api) { this.api = api; } @Override public void getUsers(GetUserCallback callback) { getUserCallbacks.add(callback);
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api; private Collection<GetUserCallback> getUserCallbacks = Collections.synchronizedCollection(new ArrayList<GetUserCallback>()); UserDataSourceImp(Api api) { this.api = api; } @Override public void getUsers(GetUserCallback callback) { getUserCallbacks.add(callback);
api.call(new GetFeedCall(this));
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // }
import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named;
package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api; private Collection<GetUserCallback> getUserCallbacks = Collections.synchronizedCollection(new ArrayList<GetUserCallback>()); UserDataSourceImp(Api api) { this.api = api; } @Override public void getUsers(GetUserCallback callback) { getUserCallbacks.add(callback); api.call(new GetFeedCall(this)); } @Override public void complete(List<UserApiEntry> response) {
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api; private Collection<GetUserCallback> getUserCallbacks = Collections.synchronizedCollection(new ArrayList<GetUserCallback>()); UserDataSourceImp(Api api) { this.api = api; } @Override public void getUsers(GetUserCallback callback) { getUserCallbacks.add(callback); api.call(new GetFeedCall(this)); } @Override public void complete(List<UserApiEntry> response) {
List<Hipster> hipsters = new ArrayList<Hipster>();
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // }
import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named;
package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api; private Collection<GetUserCallback> getUserCallbacks = Collections.synchronizedCollection(new ArrayList<GetUserCallback>()); UserDataSourceImp(Api api) { this.api = api; } @Override public void getUsers(GetUserCallback callback) { getUserCallbacks.add(callback); api.call(new GetFeedCall(this)); } @Override public void complete(List<UserApiEntry> response) { List<Hipster> hipsters = new ArrayList<Hipster>(); for (UserApiEntry userApiEntry : response) {
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/Api.java // public interface Api { // void call(ApiCall apiCall); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java // public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { // private static final int MAX_USERS = 5; // private static final String LOGTAG = "GetFeedCall"; // private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); // private GetFeedRequest request; // private int page; // // public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { // super(apiResponseCallback); // } // // @Override // public void call(RestAdapter restAdapter) { // page = 0; // responseBuffer.clear(); // // request = restAdapter.create(GetFeedRequest.class); // request.getRandomUsers(MAX_USERS, page, this); // } // // @Override // public void success(GetFeedResponse apiUsers, Response response) { // responseBuffer.addAll(apiUsers.getResults()); // if (responseBuffer.size() >= MAX_USERS) { // super.responseCallback.complete(responseBuffer); // } else { // page++; // request.getRandomUsers(MAX_USERS, page, this); // } // } // // @Override // public void failure(RetrofitError retrofitError) { // //TODO notify api error. // LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody()); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApi.java // public class UserApi { // // private UserApiName name; // private String email; // private UserApiPicture picture; // // public UserApiName getName() { // return name; // } // // public String getEmail() { // return email; // } // // public UserApiPicture getPicture() { // return picture; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/module/UserDataSourceImp.java import android.util.Log; import com.flipper83.protohipster.feed.datasource.api.Api; import com.flipper83.protohipster.feed.datasource.api.call.rest.GetFeedCall; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApi; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Named; package com.flipper83.protohipster.feed.datasource.module; /** * implementation for UserDataSource */ class UserDataSourceImp implements UserDataSource, ApiResponseCallback<List<UserApiEntry>> { @Inject @Named("ApiRest") Api api; private Collection<GetUserCallback> getUserCallbacks = Collections.synchronizedCollection(new ArrayList<GetUserCallback>()); UserDataSourceImp(Api api) { this.api = api; } @Override public void getUsers(GetUserCallback callback) { getUserCallbacks.add(callback); api.call(new GetFeedCall(this)); } @Override public void complete(List<UserApiEntry> response) { List<Hipster> hipsters = new ArrayList<Hipster>(); for (UserApiEntry userApiEntry : response) {
UserApi user = userApiEntry.getUser();
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/mapper/HipsterViewMapperManual.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/HipsterBoundary.java // public class HipsterBoundary { // private String name; // private String avatar; // private int rating; // private String userId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public int getRating() { // return rating; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // }
import com.flipper83.protohipster.feed.domain.boundaries.HipsterBoundary; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import javax.inject.Inject;
package com.flipper83.protohipster.feed.view.viewmodel.mapper; /** * */ public class HipsterViewMapperManual implements HipsterViewMapper { @Inject public HipsterViewMapperManual(){ } @Override
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/HipsterBoundary.java // public class HipsterBoundary { // private String name; // private String avatar; // private int rating; // private String userId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public int getRating() { // return rating; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/mapper/HipsterViewMapperManual.java import com.flipper83.protohipster.feed.domain.boundaries.HipsterBoundary; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import javax.inject.Inject; package com.flipper83.protohipster.feed.view.viewmodel.mapper; /** * */ public class HipsterViewMapperManual implements HipsterViewMapper { @Inject public HipsterViewMapperManual(){ } @Override
public HipsterViewModel mapper(HipsterBoundary hipsterBoundary) {
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/mapper/HipsterViewMapperManual.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/HipsterBoundary.java // public class HipsterBoundary { // private String name; // private String avatar; // private int rating; // private String userId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public int getRating() { // return rating; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // }
import com.flipper83.protohipster.feed.domain.boundaries.HipsterBoundary; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import javax.inject.Inject;
package com.flipper83.protohipster.feed.view.viewmodel.mapper; /** * */ public class HipsterViewMapperManual implements HipsterViewMapper { @Inject public HipsterViewMapperManual(){ } @Override
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/HipsterBoundary.java // public class HipsterBoundary { // private String name; // private String avatar; // private int rating; // private String userId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public int getRating() { // return rating; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/mapper/HipsterViewMapperManual.java import com.flipper83.protohipster.feed.domain.boundaries.HipsterBoundary; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import javax.inject.Inject; package com.flipper83.protohipster.feed.view.viewmodel.mapper; /** * */ public class HipsterViewMapperManual implements HipsterViewMapper { @Inject public HipsterViewMapperManual(){ } @Override
public HipsterViewModel mapper(HipsterBoundary hipsterBoundary) {
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/view/ui/FeedAdapter.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/uibase/transformation/TransformationBuilder.java // public interface TransformationBuilder { // Transformation createAvatarTransformation(); // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.beardedhen.androidbootstrap.FontAwesomeText; import com.flipper83.protohipster.R; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import com.flipper83.protohipster.uibase.transformation.TransformationBuilder; import com.squareup.picasso.Picasso; import java.util.List;
package com.flipper83.protohipster.feed.view.ui; /** * */ public class FeedAdapter extends BaseAdapter { private static final int NUM_STARS = 5; private static final String ICON_HEART_FILL = "fa-heart"; private static final String ICON_HEART_EMPTY = "fa-heart-o"; private final Context context; private final Picasso picasso;
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/uibase/transformation/TransformationBuilder.java // public interface TransformationBuilder { // Transformation createAvatarTransformation(); // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/ui/FeedAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.beardedhen.androidbootstrap.FontAwesomeText; import com.flipper83.protohipster.R; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import com.flipper83.protohipster.uibase.transformation.TransformationBuilder; import com.squareup.picasso.Picasso; import java.util.List; package com.flipper83.protohipster.feed.view.ui; /** * */ public class FeedAdapter extends BaseAdapter { private static final int NUM_STARS = 5; private static final String ICON_HEART_FILL = "fa-heart"; private static final String ICON_HEART_EMPTY = "fa-heart-o"; private final Context context; private final Picasso picasso;
private final TransformationBuilder transformationBuilder;
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/view/ui/FeedAdapter.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/uibase/transformation/TransformationBuilder.java // public interface TransformationBuilder { // Transformation createAvatarTransformation(); // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.beardedhen.androidbootstrap.FontAwesomeText; import com.flipper83.protohipster.R; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import com.flipper83.protohipster.uibase.transformation.TransformationBuilder; import com.squareup.picasso.Picasso; import java.util.List;
package com.flipper83.protohipster.feed.view.ui; /** * */ public class FeedAdapter extends BaseAdapter { private static final int NUM_STARS = 5; private static final String ICON_HEART_FILL = "fa-heart"; private static final String ICON_HEART_EMPTY = "fa-heart-o"; private final Context context; private final Picasso picasso; private final TransformationBuilder transformationBuilder;
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/viewmodel/HipsterViewModel.java // public class HipsterViewModel { // public static final HipsterViewModel EMPTY = new HipsterViewModel(); // // private String userId = ""; // private String name = ""; // private String urlAvatar = ""; // private int rating; // private boolean likedByMe; // // public HipsterViewModel() { // // } // // public String getName() { // return name; // } // // public String getUrlAvatar() { // return urlAvatar; // } // // public int getRating() { // return rating; // } // // public void setName(String name) { // this.name = name; // } // // public void setUrlAvatar(String urlAvatar) { // this.urlAvatar = urlAvatar; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // // public void setLikedByMe(boolean likedByMe) { // this.likedByMe = likedByMe; // } // // public boolean isLikedByMe() { // return likedByMe; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/uibase/transformation/TransformationBuilder.java // public interface TransformationBuilder { // Transformation createAvatarTransformation(); // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/view/ui/FeedAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.beardedhen.androidbootstrap.FontAwesomeText; import com.flipper83.protohipster.R; import com.flipper83.protohipster.feed.view.viewmodel.HipsterViewModel; import com.flipper83.protohipster.uibase.transformation.TransformationBuilder; import com.squareup.picasso.Picasso; import java.util.List; package com.flipper83.protohipster.feed.view.ui; /** * */ public class FeedAdapter extends BaseAdapter { private static final int NUM_STARS = 5; private static final String ICON_HEART_FILL = "fa-heart"; private static final String ICON_HEART_EMPTY = "fa-heart-o"; private final Context context; private final Picasso picasso; private final TransformationBuilder transformationBuilder;
private List<HipsterViewModel> feed;
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // }
import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response;
package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall";
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall";
private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>();
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // }
import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response;
package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall"; private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>();
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall"; private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>();
private GetFeedRequest request;
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // }
import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response;
package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall"; private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); private GetFeedRequest request; private int page;
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall"; private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); private GetFeedRequest request; private int page;
public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) {
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // }
import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response;
package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall"; private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); private GetFeedRequest request; private int page; public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { super(apiResponseCallback); } @Override public void call(RestAdapter restAdapter) { page = 0; responseBuffer.clear(); request = restAdapter.create(GetFeedRequest.class); request.getRandomUsers(MAX_USERS, page, this); } @Override public void success(GetFeedResponse apiUsers, Response response) { responseBuffer.addAll(apiUsers.getResults()); if (responseBuffer.size() >= MAX_USERS) { super.responseCallback.complete(responseBuffer); } else { page++; request.getRandomUsers(MAX_USERS, page, this); } } @Override public void failure(RetrofitError retrofitError) { //TODO notify api error.
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/request/GetFeedRequest.java // public interface GetFeedRequest { // public final static String SEED_HIPSTER = "hipster"; // // /** // * randomUser.me don't have page suppont, and the limit in one all is 5 users. I'm going to // * simulate the page system with the seed param. // */ // @GET("/") // void getRandomUsers(@Query("results") int maxUsers,@Query("seed") int page, // Callback<GetFeedResponse> callback); // // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/response/GetFeedResponse.java // public class GetFeedResponse { // private List<UserApiEntry> results; // // public List<UserApiEntry> getResults() { // return results; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/callback/ApiResponseCallback.java // public interface ApiResponseCallback<T> { // void complete(T response); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/model/UserApiEntry.java // public class UserApiEntry { // private UserApi user; // // public UserApi getUser() { // return user; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/LoggerProvider.java // public class LoggerProvider { // // @Inject // static Logger logger; // // public LoggerProvider() { // // } // // public static Logger getLogger() { // return logger; // } // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/rest/GetFeedCall.java import com.flipper83.protohipster.feed.datasource.api.call.rest.request.GetFeedRequest; import com.flipper83.protohipster.feed.datasource.api.call.rest.response.GetFeedResponse; import com.flipper83.protohipster.feed.datasource.api.callback.ApiResponseCallback; import com.flipper83.protohipster.feed.datasource.api.model.UserApiEntry; import com.flipper83.protohipster.globalutils.module.LoggerProvider; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; package com.flipper83.protohipster.feed.datasource.api.call.rest; /** * Api Call to request */ public class GetFeedCall extends ApiRestCall implements Callback<GetFeedResponse> { private static final int MAX_USERS = 5; private static final String LOGTAG = "GetFeedCall"; private List<UserApiEntry> responseBuffer = new ArrayList<UserApiEntry>(); private GetFeedRequest request; private int page; public GetFeedCall(ApiResponseCallback<List<UserApiEntry>> apiResponseCallback) { super(apiResponseCallback); } @Override public void call(RestAdapter restAdapter) { page = 0; responseBuffer.clear(); request = restAdapter.create(GetFeedRequest.class); request.getRandomUsers(MAX_USERS, page, this); } @Override public void success(GetFeedResponse apiUsers, Response response) { responseBuffer.addAll(apiUsers.getResults()); if (responseBuffer.size() >= MAX_USERS) { super.responseCallback.complete(responseBuffer); } else { page++; request.getRandomUsers(MAX_USERS, page, this); } } @Override public void failure(RetrofitError retrofitError) { //TODO notify api error.
LoggerProvider.getLogger().d(LOGTAG, "an error happens " + retrofitError.getBody());
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/domain/module/GetFeedImpl.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/LikeDataSource.java // public interface LikeDataSource { // void getCountLikesForUser(List<String> userIds, GetCountLikesCallback getCountLikesCallback); // void getMyLikers(GetMyLikersCallback getLikersForUserCallback); // void likeUser(String userId, LikeUserCallback likeUserCallback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetCountLikesCallback.java // public interface GetCountLikesCallback { // void countUsers(Map<String, Integer> countLikers); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/FeedBoundary.java // public class FeedBoundary { // private boolean success = false; // List<HipsterBoundary> hipsters = new ArrayList<HipsterBoundary>(); // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // public List<HipsterBoundary> getHipsters() { // return hipsters; // } // // // public void add(HipsterBoundary hipster) { // hipsters.add(hipster); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/HipsterBoundary.java // public class HipsterBoundary { // private String name; // private String avatar; // private int rating; // private String userId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public int getRating() { // return rating; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/mappers/HipsterMapper.java // public interface HipsterMapper { // public HipsterBoundary mapper(Hipster hipster); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/interactors/GetFeed.java // public interface GetFeed { // Observable<FeedBoundary> getFeed(); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/rating/RatingCalculator.java // public interface RatingCalculator{ // int calculate(int totalLikers); // // int defaultValue(); // }
import com.flipper83.protohipster.feed.datasource.interfaces.LikeDataSource; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetCountLikesCallback; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.domain.boundaries.FeedBoundary; import com.flipper83.protohipster.feed.domain.boundaries.HipsterBoundary; import com.flipper83.protohipster.feed.domain.mappers.HipsterMapper; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import com.flipper83.protohipster.feed.domain.interactors.GetFeed; import com.flipper83.protohipster.globalutils.rating.RatingCalculator; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.subscriptions.Subscriptions; import rx.util.functions.Func1; import rx.util.functions.Func2;
package com.flipper83.protohipster.feed.domain.module; /** * this is an implementation for feed */ class GetFeedImpl implements GetFeed { private final HipsterMapper hipsterMapper;
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/LikeDataSource.java // public interface LikeDataSource { // void getCountLikesForUser(List<String> userIds, GetCountLikesCallback getCountLikesCallback); // void getMyLikers(GetMyLikersCallback getLikersForUserCallback); // void likeUser(String userId, LikeUserCallback likeUserCallback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/UserDataSource.java // public interface UserDataSource { // void getUsers(GetUserCallback callback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetCountLikesCallback.java // public interface GetCountLikesCallback { // void countUsers(Map<String, Integer> countLikers); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetUserCallback.java // public interface GetUserCallback { // public void usersReady(List<Hipster> users); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/FeedBoundary.java // public class FeedBoundary { // private boolean success = false; // List<HipsterBoundary> hipsters = new ArrayList<HipsterBoundary>(); // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // public List<HipsterBoundary> getHipsters() { // return hipsters; // } // // // public void add(HipsterBoundary hipster) { // hipsters.add(hipster); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/boundaries/HipsterBoundary.java // public class HipsterBoundary { // private String name; // private String avatar; // private int rating; // private String userId; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public int getRating() { // return rating; // } // // public void setRating(int rating) { // this.rating = rating; // } // // public String getUserId() { // return userId; // } // // public void setUserId(String userId) { // this.userId = userId; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/mappers/HipsterMapper.java // public interface HipsterMapper { // public HipsterBoundary mapper(Hipster hipster); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/gateway/Hipster.java // public class Hipster { // // private String userId; // private String name; // private String surname; // private String avatar; // private long time; // private int numLikes; // // public Hipster(String userId) { // this.userId = userId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getUserId() { // return userId; // } // // public int getNumLikes() { // return numLikes; // } // // public void setNumLikes(int numLikes) { // this.numLikes = numLikes; // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/interactors/GetFeed.java // public interface GetFeed { // Observable<FeedBoundary> getFeed(); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/rating/RatingCalculator.java // public interface RatingCalculator{ // int calculate(int totalLikers); // // int defaultValue(); // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/module/GetFeedImpl.java import com.flipper83.protohipster.feed.datasource.interfaces.LikeDataSource; import com.flipper83.protohipster.feed.datasource.interfaces.UserDataSource; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetCountLikesCallback; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetUserCallback; import com.flipper83.protohipster.feed.domain.boundaries.FeedBoundary; import com.flipper83.protohipster.feed.domain.boundaries.HipsterBoundary; import com.flipper83.protohipster.feed.domain.mappers.HipsterMapper; import com.flipper83.protohipster.feed.domain.gateway.Hipster; import com.flipper83.protohipster.feed.domain.interactors.GetFeed; import com.flipper83.protohipster.globalutils.rating.RatingCalculator; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.subscriptions.Subscriptions; import rx.util.functions.Func1; import rx.util.functions.Func2; package com.flipper83.protohipster.feed.domain.module; /** * this is an implementation for feed */ class GetFeedImpl implements GetFeed { private final HipsterMapper hipsterMapper;
UserDataSource userDataSource;
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/feed/domain/module/GetMyLikersImpl.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/parse/response/GetLikesResponse.java // public class GetLikesResponse { // private static final int NO_EXIST = 0; // // Map<String, Integer> likes = new HashMap<String, Integer>(); // // public void add(String userId, int numLikes) { // likes.put(userId, numLikes); // } // // public int getNumLikes(String userId) { // if (likes.containsKey(userId)) { // return likes.get(userId); // } else { // return NO_EXIST; // } // } // // public Map<String, Integer> getAllLikers() { // return Collections.unmodifiableMap(likes); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/LikeDataSource.java // public interface LikeDataSource { // void getCountLikesForUser(List<String> userIds, GetCountLikesCallback getCountLikesCallback); // void getMyLikers(GetMyLikersCallback getLikersForUserCallback); // void likeUser(String userId, LikeUserCallback likeUserCallback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetMyLikersCallback.java // public interface GetMyLikersCallback { // void myLikers(List<String> userIds); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/interactors/GetMyLikers.java // public interface GetMyLikers { // Observable<List<String>> getMyLikers(); // }
import com.flipper83.protohipster.feed.datasource.api.call.parse.response.GetLikesResponse; import com.flipper83.protohipster.feed.datasource.interfaces.LikeDataSource; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetMyLikersCallback; import com.flipper83.protohipster.feed.domain.interactors.GetMyLikers; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.subscriptions.Subscriptions;
package com.flipper83.protohipster.feed.domain.module; /** * this is an implementation for feed */ class GetMyLikersImpl extends GetLikesResponse implements GetMyLikers { LikeDataSource likeDataSource; @Inject GetMyLikersImpl(LikeDataSource likeDataSource) { this.likeDataSource = likeDataSource; } @Override public Observable<List<String>> getMyLikers() { return Observable.create(new Observable.OnSubscribeFunc<List<String>>() { @Override public Subscription onSubscribe(final Observer<? super List<String>> observer) {
// Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/api/call/parse/response/GetLikesResponse.java // public class GetLikesResponse { // private static final int NO_EXIST = 0; // // Map<String, Integer> likes = new HashMap<String, Integer>(); // // public void add(String userId, int numLikes) { // likes.put(userId, numLikes); // } // // public int getNumLikes(String userId) { // if (likes.containsKey(userId)) { // return likes.get(userId); // } else { // return NO_EXIST; // } // } // // public Map<String, Integer> getAllLikers() { // return Collections.unmodifiableMap(likes); // } // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/LikeDataSource.java // public interface LikeDataSource { // void getCountLikesForUser(List<String> userIds, GetCountLikesCallback getCountLikesCallback); // void getMyLikers(GetMyLikersCallback getLikersForUserCallback); // void likeUser(String userId, LikeUserCallback likeUserCallback); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/datasource/interfaces/callbacks/GetMyLikersCallback.java // public interface GetMyLikersCallback { // void myLikers(List<String> userIds); // } // // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/interactors/GetMyLikers.java // public interface GetMyLikers { // Observable<List<String>> getMyLikers(); // } // Path: protohipster/src/main/java/com/flipper83/protohipster/feed/domain/module/GetMyLikersImpl.java import com.flipper83.protohipster.feed.datasource.api.call.parse.response.GetLikesResponse; import com.flipper83.protohipster.feed.datasource.interfaces.LikeDataSource; import com.flipper83.protohipster.feed.datasource.interfaces.callbacks.GetMyLikersCallback; import com.flipper83.protohipster.feed.domain.interactors.GetMyLikers; import java.util.List; import javax.inject.Inject; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.subscriptions.Subscriptions; package com.flipper83.protohipster.feed.domain.module; /** * this is an implementation for feed */ class GetMyLikersImpl extends GetLikesResponse implements GetMyLikers { LikeDataSource likeDataSource; @Inject GetMyLikersImpl(LikeDataSource likeDataSource) { this.likeDataSource = likeDataSource; } @Override public Observable<List<String>> getMyLikers() { return Observable.create(new Observable.OnSubscribeFunc<List<String>>() { @Override public Subscription onSubscribe(final Observer<? super List<String>> observer) {
likeDataSource.getMyLikers(new GetMyLikersCallback() {
flipper83/protohipster
protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/AndroidModule.java
// Path: protohipster/src/main/java/com/flipper83/protohipster/uibase/app/ProtoApplication.java // public class ProtoApplication extends Application{ // private ObjectGraph graph; // // @Override // public void onCreate() { // super.onCreate(); // // graph = ObjectGraph.create(getModules().toArray()); // graph.injectStatics(); // } // // protected List<Object> getModules() { // return Arrays.asList(new AndroidModule(this),new GlobalModule(), new DomainModule(),new FeedViewModule(),new DataSourceModule()); // } // // // // public void inject(Object object) { // graph.inject(object); // } // // }
import android.content.Context; import android.location.LocationManager; import com.flipper83.protohipster.daggerUtils.ForApplication; import com.flipper83.protohipster.uibase.app.ProtoApplication; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static android.content.Context.LOCATION_SERVICE;
package com.flipper83.protohipster.globalutils.module; /* * Copyright (C) 2013 Square, Inc. * * 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. */ /** * A module for Android-specific dependencies which require a {@link Context} or * {@link android.app.Application} to create. */ @Module(library = true) public class AndroidModule {
// Path: protohipster/src/main/java/com/flipper83/protohipster/uibase/app/ProtoApplication.java // public class ProtoApplication extends Application{ // private ObjectGraph graph; // // @Override // public void onCreate() { // super.onCreate(); // // graph = ObjectGraph.create(getModules().toArray()); // graph.injectStatics(); // } // // protected List<Object> getModules() { // return Arrays.asList(new AndroidModule(this),new GlobalModule(), new DomainModule(),new FeedViewModule(),new DataSourceModule()); // } // // // // public void inject(Object object) { // graph.inject(object); // } // // } // Path: protohipster/src/main/java/com/flipper83/protohipster/globalutils/module/AndroidModule.java import android.content.Context; import android.location.LocationManager; import com.flipper83.protohipster.daggerUtils.ForApplication; import com.flipper83.protohipster.uibase.app.ProtoApplication; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import static android.content.Context.LOCATION_SERVICE; package com.flipper83.protohipster.globalutils.module; /* * Copyright (C) 2013 Square, Inc. * * 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. */ /** * A module for Android-specific dependencies which require a {@link Context} or * {@link android.app.Application} to create. */ @Module(library = true) public class AndroidModule {
private final ProtoApplication application;
jjkester/transportlanguage
Code/src/test/java/otld/otld/intermediate/VariableAssignmentTest.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // }
import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.*;
package otld.otld.intermediate; public class VariableAssignmentTest { @Test public void testGetDestination() throws Exception { Variable v = Variable.create(Type.INT, "v", null); Variable w = Variable.create(Type.INT, "w", "42"); VariableAssignment vw = new VariableAssignment(v, w); assertEquals(v, vw.getTarget()); } @Test public void testGetSource() throws Exception { Variable v = Variable.create(Type.INT, "v", null); Variable w = Variable.create(Type.INT, "w", "42"); VariableAssignment vw = new VariableAssignment(v, w); assertEquals(w, vw.getSource()); }
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // Path: Code/src/test/java/otld/otld/intermediate/VariableAssignmentTest.java import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.*; package otld.otld.intermediate; public class VariableAssignmentTest { @Test public void testGetDestination() throws Exception { Variable v = Variable.create(Type.INT, "v", null); Variable w = Variable.create(Type.INT, "w", "42"); VariableAssignment vw = new VariableAssignment(v, w); assertEquals(v, vw.getTarget()); } @Test public void testGetSource() throws Exception { Variable v = Variable.create(Type.INT, "v", null); Variable w = Variable.create(Type.INT, "w", "42"); VariableAssignment vw = new VariableAssignment(v, w); assertEquals(w, vw.getSource()); }
@Test(expected = TypeMismatch.class)
jjkester/transportlanguage
Code/src/test/java/otld/otld/intermediate/ProgramTest.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // }
import org.junit.Test; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import static org.junit.Assert.*;
package otld.otld.intermediate; public class ProgramTest { @Test public void testGetId() throws Exception { Program program = new Program("test"); assertEquals("test", program.getId()); } @Test public void testGetVariable() throws Exception { Program program = new Program("test"); Variable v = Variable.create(Type.INT, "v", "10"); program.addVariable(v); assertEquals(v, program.getVariable("v")); }
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // } // Path: Code/src/test/java/otld/otld/intermediate/ProgramTest.java import org.junit.Test; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import static org.junit.Assert.*; package otld.otld.intermediate; public class ProgramTest { @Test public void testGetId() throws Exception { Program program = new Program("test"); assertEquals("test", program.getId()); } @Test public void testGetVariable() throws Exception { Program program = new Program("test"); Variable v = Variable.create(Type.INT, "v", "10"); program.addVariable(v); assertEquals(v, program.getVariable("v")); }
@Test(expected = VariableAlreadyDeclared.class)
jjkester/transportlanguage
Code/src/test/java/otld/otld/intermediate/ProgramTest.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // }
import org.junit.Test; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import static org.junit.Assert.*;
package otld.otld.intermediate; public class ProgramTest { @Test public void testGetId() throws Exception { Program program = new Program("test"); assertEquals("test", program.getId()); } @Test public void testGetVariable() throws Exception { Program program = new Program("test"); Variable v = Variable.create(Type.INT, "v", "10"); program.addVariable(v); assertEquals(v, program.getVariable("v")); } @Test(expected = VariableAlreadyDeclared.class) public void testAddVariable() throws Exception { Program program = new Program("test"); Variable v = Variable.create(Type.INT, "v", "10"); program.addVariable(v); program.addVariable(Variable.create(Type.INT, "v", "10")); } @Test public void testGetFunction() throws Exception { Program program = new Program("test"); Function f = new Function("f", Type.INT, Type.INT); program.addFunction(f); assertEquals(f, program.getFunction("f")); }
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // } // Path: Code/src/test/java/otld/otld/intermediate/ProgramTest.java import org.junit.Test; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import static org.junit.Assert.*; package otld.otld.intermediate; public class ProgramTest { @Test public void testGetId() throws Exception { Program program = new Program("test"); assertEquals("test", program.getId()); } @Test public void testGetVariable() throws Exception { Program program = new Program("test"); Variable v = Variable.create(Type.INT, "v", "10"); program.addVariable(v); assertEquals(v, program.getVariable("v")); } @Test(expected = VariableAlreadyDeclared.class) public void testAddVariable() throws Exception { Program program = new Program("test"); Variable v = Variable.create(Type.INT, "v", "10"); program.addVariable(v); program.addVariable(Variable.create(Type.INT, "v", "10")); } @Test public void testGetFunction() throws Exception { Program program = new Program("test"); Function f = new Function("f", Type.INT, Type.INT); program.addFunction(f); assertEquals(f, program.getFunction("f")); }
@Test(expected = FunctionAlreadyDeclared.class)
jjkester/transportlanguage
Code/src/test/java/otld/otld/intermediate/OperationSequenceTest.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // }
import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.*;
package otld.otld.intermediate; public class OperationSequenceTest { Function add = new Function("add", Type.INT, Type.INT, Type.INT); Function eq = new Function("eq", Type.INT, Type.INT, Type.BOOL); Variable x = Variable.create(Type.INT, "x", null); Variable y = Variable.create(Type.INT, "y", null); Variable z = Variable.create(Type.BOOL, "z", null); @Test
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // Path: Code/src/test/java/otld/otld/intermediate/OperationSequenceTest.java import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.*; package otld.otld.intermediate; public class OperationSequenceTest { Function add = new Function("add", Type.INT, Type.INT, Type.INT); Function eq = new Function("eq", Type.INT, Type.INT, Type.BOOL); Variable x = Variable.create(Type.INT, "x", null); Variable y = Variable.create(Type.INT, "y", null); Variable z = Variable.create(Type.BOOL, "z", null); @Test
public void testBehaviour() throws TypeMismatch {
jjkester/transportlanguage
Code/src/main/java/otld/otld/intermediate/Variable.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // }
import com.google.common.base.Optional; import otld.otld.intermediate.exceptions.TypeMismatch; import sun.reflect.generics.reflectiveObjects.NotImplementedException;
package otld.otld.intermediate; /** * A variable. * * A variable has a signature which indicates the Java class to use for values. * * A variable has a required identifier and type. A variable might have an initial value, which is saved here. * Computation and storage of the actual value is (obviously) left to the target language. * * It is recommended to create new variables using the factory method. * * @param <T> The Java type of the values for this variable. */ public class Variable<T> extends Element implements TypedElement { /** The unique identifier of this variable. */ private String id; /** The type of this variable. */ private Type type; /** The optional initial value of this variable. */ private Optional<T> initialValue; /** * @param type The type of this variable. * @param id The unique identifier of this variable. * @param initialValue The initial value of this variable. */ protected Variable(final Type type, final String id, final T initialValue) { this.type = type; this.id = id; this.initialValue = Optional.fromNullable(initialValue); } /** * @param type The type of this variable. * @param id The unique identifier of this variable. */ public Variable(final Type type, final String id) { this(type, id, null); } /** * @return The unique identifier of this variable. */ public final String getId() { return this.id; } /** * @return The type of this variable. */ public final Type getType() { return this.type; } /** * @return The initial value of this variable. Can be {@code null}. */ public final T getInitialValue() { return this.initialValue.orNull(); } /** * Creates a new VariableAssignment with this variable as destination. * * @param source The source variable. * @return The assignment. * @throws TypeMismatch The types of this and the source variable do not match. */
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // Path: Code/src/main/java/otld/otld/intermediate/Variable.java import com.google.common.base.Optional; import otld.otld.intermediate.exceptions.TypeMismatch; import sun.reflect.generics.reflectiveObjects.NotImplementedException; package otld.otld.intermediate; /** * A variable. * * A variable has a signature which indicates the Java class to use for values. * * A variable has a required identifier and type. A variable might have an initial value, which is saved here. * Computation and storage of the actual value is (obviously) left to the target language. * * It is recommended to create new variables using the factory method. * * @param <T> The Java type of the values for this variable. */ public class Variable<T> extends Element implements TypedElement { /** The unique identifier of this variable. */ private String id; /** The type of this variable. */ private Type type; /** The optional initial value of this variable. */ private Optional<T> initialValue; /** * @param type The type of this variable. * @param id The unique identifier of this variable. * @param initialValue The initial value of this variable. */ protected Variable(final Type type, final String id, final T initialValue) { this.type = type; this.id = id; this.initialValue = Optional.fromNullable(initialValue); } /** * @param type The type of this variable. * @param id The unique identifier of this variable. */ public Variable(final Type type, final String id) { this(type, id, null); } /** * @return The unique identifier of this variable. */ public final String getId() { return this.id; } /** * @return The type of this variable. */ public final Type getType() { return this.type; } /** * @return The initial value of this variable. Can be {@code null}. */ public final T getInitialValue() { return this.initialValue.orNull(); } /** * Creates a new VariableAssignment with this variable as destination. * * @param source The source variable. * @return The assignment. * @throws TypeMismatch The types of this and the source variable do not match. */
public final VariableAssignment createVariableAssignment(final Variable<T> source) throws TypeMismatch {
jjkester/transportlanguage
Code/src/test/java/otld/otld/intermediate/ApplicationTest.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // }
import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
package otld.otld.intermediate; public class ApplicationTest { @Test public void testGetOperator() throws Exception { Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", "5"); Application a = new Application(Operator.ADDITION, v, w, v); assertEquals(Operator.ADDITION, a.getOperator()); } @Test public void testGetArgs() throws Exception { Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", "5"); Application a = new Application(Operator.ADDITION, v, w, v); Variable[] args = {v, w}; assertArrayEquals(args, a.getArgs()); } @Test public void testGetVariable() throws Exception { Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", "5"); Application a = new Application(Operator.ADDITION, v, w, v); assertEquals(v, a.getTarget()); }
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // Path: Code/src/test/java/otld/otld/intermediate/ApplicationTest.java import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; package otld.otld.intermediate; public class ApplicationTest { @Test public void testGetOperator() throws Exception { Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", "5"); Application a = new Application(Operator.ADDITION, v, w, v); assertEquals(Operator.ADDITION, a.getOperator()); } @Test public void testGetArgs() throws Exception { Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", "5"); Application a = new Application(Operator.ADDITION, v, w, v); Variable[] args = {v, w}; assertArrayEquals(args, a.getArgs()); } @Test public void testGetVariable() throws Exception { Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", "5"); Application a = new Application(Operator.ADDITION, v, w, v); assertEquals(v, a.getTarget()); }
@Test(expected = TypeMismatch.class)
jjkester/transportlanguage
Code/src/main/java/otld/otld/parsing/OTLDListener.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // }
import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import otld.otld.grammar.otldBaseListener; import otld.otld.grammar.otldLexer; import otld.otld.grammar.otldParser; import otld.otld.intermediate.*; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.TypeMismatch; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.io.IOException; import java.io.InputStream; import java.util.*;
} } } else { returnVar = city.getVariable(id); } return returnVar; } @Override public void enterCity(otldParser.CityContext ctx) { city = new Program(ctx.ID().getText()); } @Override public void enterCompany(otldParser.CompanyContext ctx) { stack.push(city.getBody()); } @Override public void exitCompany(otldParser.CompanyContext ctx) { stack.pop(); } @Override public void enterDeftrain(otldParser.DeftrainContext ctx) { /*Train represents an array, arrays are as of yet still unsupported in our intermediate representation so this code isn't used.*/ if (!ctx.ID().getText().startsWith("platform")) { try { city.addVariable(Variable.create(getArrType(ctx.CARGO().getText()), ctx.ID().getText(), null));
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // } // Path: Code/src/main/java/otld/otld/parsing/OTLDListener.java import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import otld.otld.grammar.otldBaseListener; import otld.otld.grammar.otldLexer; import otld.otld.grammar.otldParser; import otld.otld.intermediate.*; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.TypeMismatch; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.io.IOException; import java.io.InputStream; import java.util.*; } } } else { returnVar = city.getVariable(id); } return returnVar; } @Override public void enterCity(otldParser.CityContext ctx) { city = new Program(ctx.ID().getText()); } @Override public void enterCompany(otldParser.CompanyContext ctx) { stack.push(city.getBody()); } @Override public void exitCompany(otldParser.CompanyContext ctx) { stack.pop(); } @Override public void enterDeftrain(otldParser.DeftrainContext ctx) { /*Train represents an array, arrays are as of yet still unsupported in our intermediate representation so this code isn't used.*/ if (!ctx.ID().getText().startsWith("platform")) { try { city.addVariable(Variable.create(getArrType(ctx.CARGO().getText()), ctx.ID().getText(), null));
} catch (VariableAlreadyDeclared variableAlreadyDeclared) {
jjkester/transportlanguage
Code/src/main/java/otld/otld/parsing/OTLDListener.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // }
import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import otld.otld.grammar.otldBaseListener; import otld.otld.grammar.otldLexer; import otld.otld.grammar.otldParser; import otld.otld.intermediate.*; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.TypeMismatch; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.io.IOException; import java.io.InputStream; import java.util.*;
} } else { errors.add(new Error(ctx.ID().getSymbol().getLine(), ctx.ID().getSymbol().getCharPositionInLine(), ErrorMsg.RESERVEDNAME.getMessage())); } } @Override public void enterFactory(otldParser.FactoryContext ctx) { ArrayList<Type> types = new ArrayList<>(ctx.CARGO().size()); for (TerminalNode n : ctx.CARGO()) { Type type = getType(n.getText()); if (type != null) { types.add(type); } else { errors.add(new Error(ctx.CARGO().get(ctx.CARGO().indexOf(n)).getSymbol().getLine(), ctx.CARGO().get(ctx.CARGO().indexOf(n)).getSymbol().getCharPositionInLine(), ErrorMsg.TYPENOTDEFINED.getMessage())); } } try { Type[] typeArr = new Type[types.size()]; Function function = new Function(ctx.ID().getText(), types.toArray(typeArr)); city.addFunction(function); functions.put(ctx.deffactory(), function); //Set the lastFunction to this so code that is part of the factory body can access it's platforms lastFunction = function;
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // } // Path: Code/src/main/java/otld/otld/parsing/OTLDListener.java import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import otld.otld.grammar.otldBaseListener; import otld.otld.grammar.otldLexer; import otld.otld.grammar.otldParser; import otld.otld.intermediate.*; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.TypeMismatch; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.io.IOException; import java.io.InputStream; import java.util.*; } } else { errors.add(new Error(ctx.ID().getSymbol().getLine(), ctx.ID().getSymbol().getCharPositionInLine(), ErrorMsg.RESERVEDNAME.getMessage())); } } @Override public void enterFactory(otldParser.FactoryContext ctx) { ArrayList<Type> types = new ArrayList<>(ctx.CARGO().size()); for (TerminalNode n : ctx.CARGO()) { Type type = getType(n.getText()); if (type != null) { types.add(type); } else { errors.add(new Error(ctx.CARGO().get(ctx.CARGO().indexOf(n)).getSymbol().getLine(), ctx.CARGO().get(ctx.CARGO().indexOf(n)).getSymbol().getCharPositionInLine(), ErrorMsg.TYPENOTDEFINED.getMessage())); } } try { Type[] typeArr = new Type[types.size()]; Function function = new Function(ctx.ID().getText(), types.toArray(typeArr)); city.addFunction(function); functions.put(ctx.deffactory(), function); //Set the lastFunction to this so code that is part of the factory body can access it's platforms lastFunction = function;
} catch (FunctionAlreadyDeclared functionAlreadyDeclared) {
jjkester/transportlanguage
Code/src/main/java/otld/otld/parsing/OTLDListener.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // }
import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import otld.otld.grammar.otldBaseListener; import otld.otld.grammar.otldLexer; import otld.otld.grammar.otldParser; import otld.otld.intermediate.*; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.TypeMismatch; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.io.IOException; import java.io.InputStream; import java.util.*;
//Translate our green/red to true/false Boolean boolval = true; if (ctx.BOOLEAN().getText().equals("red")) { boolval = false; } stack.peek().add(var.createValueAssignment(boolval)); } } else if (ctx.CHARACTER() != null) { if (var.getType().equals(Type.CHAR)) { stack.peek().add(var.createValueAssignment(ctx.CHARACTER().getText().charAt(1))); } } } else { errors.add(new Error(ctx.ID().getSymbol().getLine(), ctx.ID().getSymbol().getCharPositionInLine(), ErrorMsg.VARNOTDEFINED.getMessage())); } } @Override public void enterTransfer(otldParser.TransferContext ctx) { //TODO implement for arrays Variable var0 = getVariable(ctx.ID().get(0).getText()); Variable var1 = getVariable(ctx.ID().get(1).getText()); if (var0 != null) { if (var1 != null) { try { stack.peek().add(var1.createVariableAssignment(var0));
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // } // Path: Code/src/main/java/otld/otld/parsing/OTLDListener.java import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.ParseTreeProperty; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import otld.otld.grammar.otldBaseListener; import otld.otld.grammar.otldLexer; import otld.otld.grammar.otldParser; import otld.otld.intermediate.*; import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.TypeMismatch; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.io.IOException; import java.io.InputStream; import java.util.*; //Translate our green/red to true/false Boolean boolval = true; if (ctx.BOOLEAN().getText().equals("red")) { boolval = false; } stack.peek().add(var.createValueAssignment(boolval)); } } else if (ctx.CHARACTER() != null) { if (var.getType().equals(Type.CHAR)) { stack.peek().add(var.createValueAssignment(ctx.CHARACTER().getText().charAt(1))); } } } else { errors.add(new Error(ctx.ID().getSymbol().getLine(), ctx.ID().getSymbol().getCharPositionInLine(), ErrorMsg.VARNOTDEFINED.getMessage())); } } @Override public void enterTransfer(otldParser.TransferContext ctx) { //TODO implement for arrays Variable var0 = getVariable(ctx.ID().get(0).getText()); Variable var1 = getVariable(ctx.ID().get(1).getText()); if (var0 != null) { if (var1 != null) { try { stack.peek().add(var1.createVariableAssignment(var0));
} catch (TypeMismatch typeMismatch) {
jjkester/transportlanguage
Code/src/test/java/otld/otld/intermediate/CallTest.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // }
import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.*;
package otld.otld.intermediate; public class CallTest { @Test public void testGetFunction() throws Exception { Function f = new Function("f", Type.INT, Type.INT); Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", null); Call c = new Call(f, v, w); assertEquals(f, c.getFunction()); } @Test public void testGetArgs() throws Exception { Function f = new Function("f", Type.INT, Type.INT); Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", null); Call c = new Call(f, v, w); Variable[] args = {v}; assertArrayEquals(args, c.getArgs()); } @Test public void testGetVariable() throws Exception { Function f = new Function("f", Type.INT, Type.INT); Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", null); Call c = new Call(f, v, w); assertEquals(w, c.getTarget()); }
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/TypeMismatch.java // public class TypeMismatch extends ElementException { // } // Path: Code/src/test/java/otld/otld/intermediate/CallTest.java import org.junit.Test; import otld.otld.intermediate.exceptions.TypeMismatch; import static org.junit.Assert.*; package otld.otld.intermediate; public class CallTest { @Test public void testGetFunction() throws Exception { Function f = new Function("f", Type.INT, Type.INT); Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", null); Call c = new Call(f, v, w); assertEquals(f, c.getFunction()); } @Test public void testGetArgs() throws Exception { Function f = new Function("f", Type.INT, Type.INT); Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", null); Call c = new Call(f, v, w); Variable[] args = {v}; assertArrayEquals(args, c.getArgs()); } @Test public void testGetVariable() throws Exception { Function f = new Function("f", Type.INT, Type.INT); Variable v = Variable.create(Type.INT, "v", "10"); Variable w = Variable.create(Type.INT, "w", null); Call c = new Call(f, v, w); assertEquals(w, c.getTarget()); }
@Test(expected = TypeMismatch.class)
jjkester/transportlanguage
Code/src/main/java/otld/otld/intermediate/Program.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // }
import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.util.*;
package otld.otld.intermediate; /** * Represents a program. * * A program is responsible for keeping administration on all variables, functions, etc. which are globally defined. * (Currently, all variables and functions are global except for function arguments.) The program body will be executed * at the start of the program. In Java terms, this is the static main method of the program. */ public class Program { /** The identifier of the program. */ private String id; /** The variables in this program indexed by identifier. */ private Map<String, Variable> variables; /** The functions in this program indexed by identifier. */ private Map<String, Function> functions; /** The operations that form the program. */ private OperationSequence body; /** * @param id The unique identifier of the program. */ public Program(final String id) { this.id = id; this.variables = new HashMap<String, Variable>(); this.functions = new HashMap<String, Function>(); this.body = new OperationSequence(); } /** * @return The unique identifier of the program. */ public final String getId() { return this.id; } /** * @param id The identifier of the variable. * @return The variable or {@code null} if there is no variable with the given identifier. */ public final Variable getVariable(final String id) { return this.variables.get(id); } /** * @param var The variable to add. * @throws VariableAlreadyDeclared There already exists a variable with the given name. */
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // } // Path: Code/src/main/java/otld/otld/intermediate/Program.java import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.util.*; package otld.otld.intermediate; /** * Represents a program. * * A program is responsible for keeping administration on all variables, functions, etc. which are globally defined. * (Currently, all variables and functions are global except for function arguments.) The program body will be executed * at the start of the program. In Java terms, this is the static main method of the program. */ public class Program { /** The identifier of the program. */ private String id; /** The variables in this program indexed by identifier. */ private Map<String, Variable> variables; /** The functions in this program indexed by identifier. */ private Map<String, Function> functions; /** The operations that form the program. */ private OperationSequence body; /** * @param id The unique identifier of the program. */ public Program(final String id) { this.id = id; this.variables = new HashMap<String, Variable>(); this.functions = new HashMap<String, Function>(); this.body = new OperationSequence(); } /** * @return The unique identifier of the program. */ public final String getId() { return this.id; } /** * @param id The identifier of the variable. * @return The variable or {@code null} if there is no variable with the given identifier. */ public final Variable getVariable(final String id) { return this.variables.get(id); } /** * @param var The variable to add. * @throws VariableAlreadyDeclared There already exists a variable with the given name. */
public final void addVariable(final Variable var) throws VariableAlreadyDeclared {
jjkester/transportlanguage
Code/src/main/java/otld/otld/intermediate/Program.java
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // }
import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.util.*;
package otld.otld.intermediate; /** * Represents a program. * * A program is responsible for keeping administration on all variables, functions, etc. which are globally defined. * (Currently, all variables and functions are global except for function arguments.) The program body will be executed * at the start of the program. In Java terms, this is the static main method of the program. */ public class Program { /** The identifier of the program. */ private String id; /** The variables in this program indexed by identifier. */ private Map<String, Variable> variables; /** The functions in this program indexed by identifier. */ private Map<String, Function> functions; /** The operations that form the program. */ private OperationSequence body; /** * @param id The unique identifier of the program. */ public Program(final String id) { this.id = id; this.variables = new HashMap<String, Variable>(); this.functions = new HashMap<String, Function>(); this.body = new OperationSequence(); } /** * @return The unique identifier of the program. */ public final String getId() { return this.id; } /** * @param id The identifier of the variable. * @return The variable or {@code null} if there is no variable with the given identifier. */ public final Variable getVariable(final String id) { return this.variables.get(id); } /** * @param var The variable to add. * @throws VariableAlreadyDeclared There already exists a variable with the given name. */ public final void addVariable(final Variable var) throws VariableAlreadyDeclared { if (this.variables.containsKey(var.getId())) { throw new VariableAlreadyDeclared(); } this.variables.put(var.getId(), var); } /** * @param id The identifier of the function. * @return The function or {@code null} if there is no function with the given identifier. */ public final Function getFunction(final String id) { return this.functions.get(id); } /** * @param function The function to add. * @throws FunctionAlreadyDeclared There already exists a function with the given name. */
// Path: Code/src/main/java/otld/otld/intermediate/exceptions/FunctionAlreadyDeclared.java // public class FunctionAlreadyDeclared extends ElementException { // } // // Path: Code/src/main/java/otld/otld/intermediate/exceptions/VariableAlreadyDeclared.java // public class VariableAlreadyDeclared extends ElementException { // } // Path: Code/src/main/java/otld/otld/intermediate/Program.java import otld.otld.intermediate.exceptions.FunctionAlreadyDeclared; import otld.otld.intermediate.exceptions.VariableAlreadyDeclared; import java.util.*; package otld.otld.intermediate; /** * Represents a program. * * A program is responsible for keeping administration on all variables, functions, etc. which are globally defined. * (Currently, all variables and functions are global except for function arguments.) The program body will be executed * at the start of the program. In Java terms, this is the static main method of the program. */ public class Program { /** The identifier of the program. */ private String id; /** The variables in this program indexed by identifier. */ private Map<String, Variable> variables; /** The functions in this program indexed by identifier. */ private Map<String, Function> functions; /** The operations that form the program. */ private OperationSequence body; /** * @param id The unique identifier of the program. */ public Program(final String id) { this.id = id; this.variables = new HashMap<String, Variable>(); this.functions = new HashMap<String, Function>(); this.body = new OperationSequence(); } /** * @return The unique identifier of the program. */ public final String getId() { return this.id; } /** * @param id The identifier of the variable. * @return The variable or {@code null} if there is no variable with the given identifier. */ public final Variable getVariable(final String id) { return this.variables.get(id); } /** * @param var The variable to add. * @throws VariableAlreadyDeclared There already exists a variable with the given name. */ public final void addVariable(final Variable var) throws VariableAlreadyDeclared { if (this.variables.containsKey(var.getId())) { throw new VariableAlreadyDeclared(); } this.variables.put(var.getId(), var); } /** * @param id The identifier of the function. * @return The function or {@code null} if there is no function with the given identifier. */ public final Function getFunction(final String id) { return this.functions.get(id); } /** * @param function The function to add. * @throws FunctionAlreadyDeclared There already exists a function with the given name. */
public final void addFunction(final Function function) throws FunctionAlreadyDeclared {
svarzee/gpsoauth-java
src/main/java/xxx/sun/security/ssl/HandshakeMessage.java
// Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum KeyExchange { // // // key exchange algorithms // K_NULL ("NULL", false, false), // K_RSA ("RSA", true, false), // K_RSA_EXPORT ("RSA_EXPORT", true, false), // K_DH_RSA ("DH_RSA", false, false), // K_DH_DSS ("DH_DSS", false, false), // K_DHE_DSS ("DHE_DSS", true, false), // K_DHE_RSA ("DHE_RSA", true, false), // K_DH_ANON ("DH_anon", true, false), // // K_ECDH_ECDSA ("ECDH_ECDSA", ALLOW_ECC, true), // K_ECDH_RSA ("ECDH_RSA", ALLOW_ECC, true), // K_ECDHE_ECDSA("ECDHE_ECDSA", ALLOW_ECC, true), // K_ECDHE_RSA ("ECDHE_RSA", ALLOW_ECC, true), // K_ECDH_ANON ("ECDH_anon", ALLOW_ECC, true), // // // Kerberos cipher suites // K_KRB5 ("KRB5", true, false), // K_KRB5_EXPORT("KRB5_EXPORT", true, false), // // // renegotiation protection request signaling cipher suite // K_SCSV ("SCSV", true, false); // // // name of the key exchange algorithm, e.g. DHE_DSS // final String name; // final boolean allowed; // final boolean isEC; // private final boolean alwaysAvailable; // // KeyExchange(String name, boolean allowed, boolean isEC) { // this.name = name; // this.allowed = allowed; // this.isEC = isEC; // this.alwaysAvailable = allowed && // (!name.startsWith("EC")) && (!name.startsWith("KRB")); // } // // boolean isAvailable() { // if (alwaysAvailable) { // return true; // } // // if (isEC) { // return (allowed && JsseJce.isEcAvailable()); // } else if (name.startsWith("KRB")) { // return (allowed && JsseJce.isKerberosAvailable()); // } else { // return allowed; // } // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum PRF { // // // PRF algorithms // P_NONE( "NONE", 0, 0), // P_SHA256("SHA-256", 32, 64), // P_SHA384("SHA-384", 48, 128), // P_SHA512("SHA-512", 64, 128); // not currently used. // // // PRF characteristics // private final String prfHashAlg; // private final int prfHashLength; // private final int prfBlockSize; // // PRF(String prfHashAlg, int prfHashLength, int prfBlockSize) { // this.prfHashAlg = prfHashAlg; // this.prfHashLength = prfHashLength; // this.prfBlockSize = prfBlockSize; // } // // String getPRFHashAlg() { // return prfHashAlg; // } // // int getPRFHashLength() { // return prfHashLength; // } // // int getPRFBlockSize() { // return prfBlockSize; // } // }
import sun.security.internal.spec.TlsPrfParameterSpec; import xxx.sun.security.ssl.CipherSuite.KeyExchange; import xxx.sun.security.ssl.CipherSuite.PRF; import sun.security.util.KeyUtil; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.DHPublicKeySpec; import javax.net.ssl.*; import javax.security.auth.x500.X500Principal; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigInteger; import java.security.*; import java.security.cert.Certificate; import java.security.cert.*; import java.security.interfaces.ECPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static xxx.sun.security.ssl.CipherSuite.PRF.P_NONE;
static final int cct_rsa_fixed_dh = 3; static final int cct_dss_fixed_dh = 4; // The existance of these two values is a bug in the SSL specification. // They are never used in the protocol. static final int cct_rsa_ephemeral_dh = 5; static final int cct_dss_ephemeral_dh = 6; // From RFC 4492 (ECC) static final int cct_ecdsa_sign = 64; static final int cct_rsa_fixed_ecdh = 65; static final int cct_ecdsa_fixed_ecdh = 66; private final static byte[] TYPES_NO_ECC = { cct_rsa_sign, cct_dss_sign }; private final static byte[] TYPES_ECC = { cct_rsa_sign, cct_dss_sign, cct_ecdsa_sign }; byte types []; // 1 to 255 types HandshakeMessage.DistinguishedName authorities []; // 3 to 2^16 - 1 // ... "3" because that's the smallest DER-encoded X500 DN // protocol version being established using this CertificateRequest message ProtocolVersion protocolVersion; // supported_signature_algorithms for TLS 1.2 or later private Collection<xxx.sun.security.ssl.SignatureAndHashAlgorithm> algorithms; // length of supported_signature_algorithms private int algorithmsLen;
// Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum KeyExchange { // // // key exchange algorithms // K_NULL ("NULL", false, false), // K_RSA ("RSA", true, false), // K_RSA_EXPORT ("RSA_EXPORT", true, false), // K_DH_RSA ("DH_RSA", false, false), // K_DH_DSS ("DH_DSS", false, false), // K_DHE_DSS ("DHE_DSS", true, false), // K_DHE_RSA ("DHE_RSA", true, false), // K_DH_ANON ("DH_anon", true, false), // // K_ECDH_ECDSA ("ECDH_ECDSA", ALLOW_ECC, true), // K_ECDH_RSA ("ECDH_RSA", ALLOW_ECC, true), // K_ECDHE_ECDSA("ECDHE_ECDSA", ALLOW_ECC, true), // K_ECDHE_RSA ("ECDHE_RSA", ALLOW_ECC, true), // K_ECDH_ANON ("ECDH_anon", ALLOW_ECC, true), // // // Kerberos cipher suites // K_KRB5 ("KRB5", true, false), // K_KRB5_EXPORT("KRB5_EXPORT", true, false), // // // renegotiation protection request signaling cipher suite // K_SCSV ("SCSV", true, false); // // // name of the key exchange algorithm, e.g. DHE_DSS // final String name; // final boolean allowed; // final boolean isEC; // private final boolean alwaysAvailable; // // KeyExchange(String name, boolean allowed, boolean isEC) { // this.name = name; // this.allowed = allowed; // this.isEC = isEC; // this.alwaysAvailable = allowed && // (!name.startsWith("EC")) && (!name.startsWith("KRB")); // } // // boolean isAvailable() { // if (alwaysAvailable) { // return true; // } // // if (isEC) { // return (allowed && JsseJce.isEcAvailable()); // } else if (name.startsWith("KRB")) { // return (allowed && JsseJce.isKerberosAvailable()); // } else { // return allowed; // } // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum PRF { // // // PRF algorithms // P_NONE( "NONE", 0, 0), // P_SHA256("SHA-256", 32, 64), // P_SHA384("SHA-384", 48, 128), // P_SHA512("SHA-512", 64, 128); // not currently used. // // // PRF characteristics // private final String prfHashAlg; // private final int prfHashLength; // private final int prfBlockSize; // // PRF(String prfHashAlg, int prfHashLength, int prfBlockSize) { // this.prfHashAlg = prfHashAlg; // this.prfHashLength = prfHashLength; // this.prfBlockSize = prfBlockSize; // } // // String getPRFHashAlg() { // return prfHashAlg; // } // // int getPRFHashLength() { // return prfHashLength; // } // // int getPRFBlockSize() { // return prfBlockSize; // } // } // Path: src/main/java/xxx/sun/security/ssl/HandshakeMessage.java import sun.security.internal.spec.TlsPrfParameterSpec; import xxx.sun.security.ssl.CipherSuite.KeyExchange; import xxx.sun.security.ssl.CipherSuite.PRF; import sun.security.util.KeyUtil; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.DHPublicKeySpec; import javax.net.ssl.*; import javax.security.auth.x500.X500Principal; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigInteger; import java.security.*; import java.security.cert.Certificate; import java.security.cert.*; import java.security.interfaces.ECPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static xxx.sun.security.ssl.CipherSuite.PRF.P_NONE; static final int cct_rsa_fixed_dh = 3; static final int cct_dss_fixed_dh = 4; // The existance of these two values is a bug in the SSL specification. // They are never used in the protocol. static final int cct_rsa_ephemeral_dh = 5; static final int cct_dss_ephemeral_dh = 6; // From RFC 4492 (ECC) static final int cct_ecdsa_sign = 64; static final int cct_rsa_fixed_ecdh = 65; static final int cct_ecdsa_fixed_ecdh = 66; private final static byte[] TYPES_NO_ECC = { cct_rsa_sign, cct_dss_sign }; private final static byte[] TYPES_ECC = { cct_rsa_sign, cct_dss_sign, cct_ecdsa_sign }; byte types []; // 1 to 255 types HandshakeMessage.DistinguishedName authorities []; // 3 to 2^16 - 1 // ... "3" because that's the smallest DER-encoded X500 DN // protocol version being established using this CertificateRequest message ProtocolVersion protocolVersion; // supported_signature_algorithms for TLS 1.2 or later private Collection<xxx.sun.security.ssl.SignatureAndHashAlgorithm> algorithms; // length of supported_signature_algorithms private int algorithmsLen;
CertificateRequest(X509Certificate ca[], KeyExchange keyExchange,
svarzee/gpsoauth-java
src/main/java/xxx/sun/security/ssl/HandshakeMessage.java
// Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum KeyExchange { // // // key exchange algorithms // K_NULL ("NULL", false, false), // K_RSA ("RSA", true, false), // K_RSA_EXPORT ("RSA_EXPORT", true, false), // K_DH_RSA ("DH_RSA", false, false), // K_DH_DSS ("DH_DSS", false, false), // K_DHE_DSS ("DHE_DSS", true, false), // K_DHE_RSA ("DHE_RSA", true, false), // K_DH_ANON ("DH_anon", true, false), // // K_ECDH_ECDSA ("ECDH_ECDSA", ALLOW_ECC, true), // K_ECDH_RSA ("ECDH_RSA", ALLOW_ECC, true), // K_ECDHE_ECDSA("ECDHE_ECDSA", ALLOW_ECC, true), // K_ECDHE_RSA ("ECDHE_RSA", ALLOW_ECC, true), // K_ECDH_ANON ("ECDH_anon", ALLOW_ECC, true), // // // Kerberos cipher suites // K_KRB5 ("KRB5", true, false), // K_KRB5_EXPORT("KRB5_EXPORT", true, false), // // // renegotiation protection request signaling cipher suite // K_SCSV ("SCSV", true, false); // // // name of the key exchange algorithm, e.g. DHE_DSS // final String name; // final boolean allowed; // final boolean isEC; // private final boolean alwaysAvailable; // // KeyExchange(String name, boolean allowed, boolean isEC) { // this.name = name; // this.allowed = allowed; // this.isEC = isEC; // this.alwaysAvailable = allowed && // (!name.startsWith("EC")) && (!name.startsWith("KRB")); // } // // boolean isAvailable() { // if (alwaysAvailable) { // return true; // } // // if (isEC) { // return (allowed && JsseJce.isEcAvailable()); // } else if (name.startsWith("KRB")) { // return (allowed && JsseJce.isKerberosAvailable()); // } else { // return allowed; // } // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum PRF { // // // PRF algorithms // P_NONE( "NONE", 0, 0), // P_SHA256("SHA-256", 32, 64), // P_SHA384("SHA-384", 48, 128), // P_SHA512("SHA-512", 64, 128); // not currently used. // // // PRF characteristics // private final String prfHashAlg; // private final int prfHashLength; // private final int prfBlockSize; // // PRF(String prfHashAlg, int prfHashLength, int prfBlockSize) { // this.prfHashAlg = prfHashAlg; // this.prfHashLength = prfHashLength; // this.prfBlockSize = prfBlockSize; // } // // String getPRFHashAlg() { // return prfHashAlg; // } // // int getPRFHashLength() { // return prfHashLength; // } // // int getPRFBlockSize() { // return prfBlockSize; // } // }
import sun.security.internal.spec.TlsPrfParameterSpec; import xxx.sun.security.ssl.CipherSuite.KeyExchange; import xxx.sun.security.ssl.CipherSuite.PRF; import sun.security.util.KeyUtil; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.DHPublicKeySpec; import javax.net.ssl.*; import javax.security.auth.x500.X500Principal; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigInteger; import java.security.*; import java.security.cert.Certificate; import java.security.cert.*; import java.security.interfaces.ECPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static xxx.sun.security.ssl.CipherSuite.PRF.P_NONE;
* both client and server are fully in sync, and that the handshake * computations have been successful. */ boolean verify(HandshakeHash handshakeHash, int sender, SecretKey master) { byte[] myFinished = getFinished(handshakeHash, sender, master); return MessageDigest.isEqual(myFinished, verifyData); } /* * Perform the actual finished message calculation. */ private byte[] getFinished(HandshakeHash handshakeHash, int sender, SecretKey masterKey) { byte[] sslLabel; String tlsLabel; if (sender == CLIENT) { sslLabel = SSL_CLIENT; tlsLabel = "client finished"; } else if (sender == SERVER) { sslLabel = SSL_SERVER; tlsLabel = "server finished"; } else { throw new RuntimeException("Invalid sender: " + sender); } if (protocolVersion.v >= ProtocolVersion.TLS10.v) { // TLS 1.0+ try { byte [] seed; String prfAlg;
// Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum KeyExchange { // // // key exchange algorithms // K_NULL ("NULL", false, false), // K_RSA ("RSA", true, false), // K_RSA_EXPORT ("RSA_EXPORT", true, false), // K_DH_RSA ("DH_RSA", false, false), // K_DH_DSS ("DH_DSS", false, false), // K_DHE_DSS ("DHE_DSS", true, false), // K_DHE_RSA ("DHE_RSA", true, false), // K_DH_ANON ("DH_anon", true, false), // // K_ECDH_ECDSA ("ECDH_ECDSA", ALLOW_ECC, true), // K_ECDH_RSA ("ECDH_RSA", ALLOW_ECC, true), // K_ECDHE_ECDSA("ECDHE_ECDSA", ALLOW_ECC, true), // K_ECDHE_RSA ("ECDHE_RSA", ALLOW_ECC, true), // K_ECDH_ANON ("ECDH_anon", ALLOW_ECC, true), // // // Kerberos cipher suites // K_KRB5 ("KRB5", true, false), // K_KRB5_EXPORT("KRB5_EXPORT", true, false), // // // renegotiation protection request signaling cipher suite // K_SCSV ("SCSV", true, false); // // // name of the key exchange algorithm, e.g. DHE_DSS // final String name; // final boolean allowed; // final boolean isEC; // private final boolean alwaysAvailable; // // KeyExchange(String name, boolean allowed, boolean isEC) { // this.name = name; // this.allowed = allowed; // this.isEC = isEC; // this.alwaysAvailable = allowed && // (!name.startsWith("EC")) && (!name.startsWith("KRB")); // } // // boolean isAvailable() { // if (alwaysAvailable) { // return true; // } // // if (isEC) { // return (allowed && JsseJce.isEcAvailable()); // } else if (name.startsWith("KRB")) { // return (allowed && JsseJce.isKerberosAvailable()); // } else { // return allowed; // } // } // // @Override // public String toString() { // return name; // } // } // // Path: src/main/java/xxx/sun/security/ssl/CipherSuite.java // static enum PRF { // // // PRF algorithms // P_NONE( "NONE", 0, 0), // P_SHA256("SHA-256", 32, 64), // P_SHA384("SHA-384", 48, 128), // P_SHA512("SHA-512", 64, 128); // not currently used. // // // PRF characteristics // private final String prfHashAlg; // private final int prfHashLength; // private final int prfBlockSize; // // PRF(String prfHashAlg, int prfHashLength, int prfBlockSize) { // this.prfHashAlg = prfHashAlg; // this.prfHashLength = prfHashLength; // this.prfBlockSize = prfBlockSize; // } // // String getPRFHashAlg() { // return prfHashAlg; // } // // int getPRFHashLength() { // return prfHashLength; // } // // int getPRFBlockSize() { // return prfBlockSize; // } // } // Path: src/main/java/xxx/sun/security/ssl/HandshakeMessage.java import sun.security.internal.spec.TlsPrfParameterSpec; import xxx.sun.security.ssl.CipherSuite.KeyExchange; import xxx.sun.security.ssl.CipherSuite.PRF; import sun.security.util.KeyUtil; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.DHPublicKeySpec; import javax.net.ssl.*; import javax.security.auth.x500.X500Principal; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigInteger; import java.security.*; import java.security.cert.Certificate; import java.security.cert.*; import java.security.interfaces.ECPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static xxx.sun.security.ssl.CipherSuite.PRF.P_NONE; * both client and server are fully in sync, and that the handshake * computations have been successful. */ boolean verify(HandshakeHash handshakeHash, int sender, SecretKey master) { byte[] myFinished = getFinished(handshakeHash, sender, master); return MessageDigest.isEqual(myFinished, verifyData); } /* * Perform the actual finished message calculation. */ private byte[] getFinished(HandshakeHash handshakeHash, int sender, SecretKey masterKey) { byte[] sslLabel; String tlsLabel; if (sender == CLIENT) { sslLabel = SSL_CLIENT; tlsLabel = "client finished"; } else if (sender == SERVER) { sslLabel = SSL_SERVER; tlsLabel = "server finished"; } else { throw new RuntimeException("Invalid sender: " + sender); } if (protocolVersion.v >= ProtocolVersion.TLS10.v) { // TLS 1.0+ try { byte [] seed; String prfAlg;
PRF prf;
svarzee/gpsoauth-java
src/main/java/xxx/sun/security/ssl/JsseJce.java
// Path: src/main/java/xxx/sun/security/ssl/SunJSSE.java // static Provider cryptoProvider;
import java.math.BigInteger; import java.security.*; import java.security.interfaces.RSAPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.EllipticCurve; import java.security.spec.RSAPublicKeySpec; import java.util.Map; import static xxx.sun.security.ssl.SunJSSE.cryptoProvider; import sun.security.jca.ProviderList; import sun.security.jca.Providers; import sun.security.util.ECUtil; import javax.crypto.*;
null); return null; } }); temp = true; } catch (Exception e) { temp = false; } kerberosAvailable = temp; } static { // force FIPS flag initialization // Because isFIPS() is synchronized and cryptoProvider is not modified // after it completes, this also eliminates the need for any further // synchronization when accessing cryptoProvider if (SunJSSE.isFIPS() == false) { fipsProviderList = null; } else { // Setup a ProviderList that can be used by the trust manager // during certificate chain validation. All the crypto must be // from the FIPS provider, but we also allow the required // certificate related services from the SUN provider. Provider sun = Security.getProvider("SUN"); if (sun == null) { throw new RuntimeException ("FIPS mode: SUN provider must be installed"); } Provider sunCerts = new SunCertificates(sun);
// Path: src/main/java/xxx/sun/security/ssl/SunJSSE.java // static Provider cryptoProvider; // Path: src/main/java/xxx/sun/security/ssl/JsseJce.java import java.math.BigInteger; import java.security.*; import java.security.interfaces.RSAPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.EllipticCurve; import java.security.spec.RSAPublicKeySpec; import java.util.Map; import static xxx.sun.security.ssl.SunJSSE.cryptoProvider; import sun.security.jca.ProviderList; import sun.security.jca.Providers; import sun.security.util.ECUtil; import javax.crypto.*; null); return null; } }); temp = true; } catch (Exception e) { temp = false; } kerberosAvailable = temp; } static { // force FIPS flag initialization // Because isFIPS() is synchronized and cryptoProvider is not modified // after it completes, this also eliminates the need for any further // synchronization when accessing cryptoProvider if (SunJSSE.isFIPS() == false) { fipsProviderList = null; } else { // Setup a ProviderList that can be used by the trust manager // during certificate chain validation. All the crypto must be // from the FIPS provider, but we also allow the required // certificate related services from the SUN provider. Provider sun = Security.getProvider("SUN"); if (sun == null) { throw new RuntimeException ("FIPS mode: SUN provider must be installed"); } Provider sunCerts = new SunCertificates(sun);
fipsProviderList = ProviderList.newList(cryptoProvider, sunCerts);
svarzee/gpsoauth-java
src/main/java/svarzee/gps/gpsoauth/Util.java
// Path: src/main/java/svarzee/gps/gpsoauth/Try.java // public static <T> Try<T> failure() { // @SuppressWarnings("unchecked") // Try<T> failure = (Try<T>) FAILURE; // return failure; // }
import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static svarzee.gps.gpsoauth.Try.failure;
package svarzee.gps.gpsoauth; class Util { public Try<String> extractValue(String responseBody, String key) { Matcher matcher = Pattern.compile(format("(\n|^)%s=(.*)?(\n|$)", key)).matcher(responseBody); if (matcher.find()) return Try.of(matcher.group(2));
// Path: src/main/java/svarzee/gps/gpsoauth/Try.java // public static <T> Try<T> failure() { // @SuppressWarnings("unchecked") // Try<T> failure = (Try<T>) FAILURE; // return failure; // } // Path: src/main/java/svarzee/gps/gpsoauth/Util.java import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static svarzee.gps.gpsoauth.Try.failure; package svarzee.gps.gpsoauth; class Util { public Try<String> extractValue(String responseBody, String key) { Matcher matcher = Pattern.compile(format("(\n|^)%s=(.*)?(\n|$)", key)).matcher(responseBody); if (matcher.find()) return Try.of(matcher.group(2));
else return failure();
krishnaraj/oneclipboard
oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/ApplicationPropertyChangeSupport.java
// Path: oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/ApplicationConstants.java // public enum Property { // LOGIN, // LOGOUT, // STOP, // START, // ; // }
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import com.cb.oneclipboard.desktop.ApplicationConstants.Property;
package com.cb.oneclipboard.desktop; public class ApplicationPropertyChangeSupport { private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); }
// Path: oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/ApplicationConstants.java // public enum Property { // LOGIN, // LOGOUT, // STOP, // START, // ; // } // Path: oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/ApplicationPropertyChangeSupport.java import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import com.cb.oneclipboard.desktop.ApplicationConstants.Property; package com.cb.oneclipboard.desktop; public class ApplicationPropertyChangeSupport { private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(listener); }
public void firePropertyChange(Property property, Object oldValue, Object newValue){
krishnaraj/oneclipboard
oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // }
import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger;
package com.cb.oneclipboard.lib.socket; public class ClipboardConnector { private final static Logger LOGGER = Logger.getLogger(ClipboardConnector.class.getName()); private static final int MAX_RECONNECT_ATTEMPTS = 3; private int reconnectCounter = 0; private static SecureRandom secureRandom; private volatile boolean connected = false; static { // TODO this might slow down the app startup secureRandom = new SecureRandom(); secureRandom.nextInt(); } private String server; private int port; private Socket clientSocket; private ObjectInputStream objInputStream; private ObjectOutputStream objOutputStream;
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // } // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger; package com.cb.oneclipboard.lib.socket; public class ClipboardConnector { private final static Logger LOGGER = Logger.getLogger(ClipboardConnector.class.getName()); private static final int MAX_RECONNECT_ATTEMPTS = 3; private int reconnectCounter = 0; private static SecureRandom secureRandom; private volatile boolean connected = false; static { // TODO this might slow down the app startup secureRandom = new SecureRandom(); secureRandom.nextInt(); } private String server; private int port; private Socket clientSocket; private ObjectInputStream objInputStream; private ObjectOutputStream objOutputStream;
private SocketListener socketListener;
krishnaraj/oneclipboard
oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // }
import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger;
package com.cb.oneclipboard.lib.socket; public class ClipboardConnector { private final static Logger LOGGER = Logger.getLogger(ClipboardConnector.class.getName()); private static final int MAX_RECONNECT_ATTEMPTS = 3; private int reconnectCounter = 0; private static SecureRandom secureRandom; private volatile boolean connected = false; static { // TODO this might slow down the app startup secureRandom = new SecureRandom(); secureRandom.nextInt(); } private String server; private int port; private Socket clientSocket; private ObjectInputStream objInputStream; private ObjectOutputStream objOutputStream; private SocketListener socketListener;
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // } // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger; package com.cb.oneclipboard.lib.socket; public class ClipboardConnector { private final static Logger LOGGER = Logger.getLogger(ClipboardConnector.class.getName()); private static final int MAX_RECONNECT_ATTEMPTS = 3; private int reconnectCounter = 0; private static SecureRandom secureRandom; private volatile boolean connected = false; static { // TODO this might slow down the app startup secureRandom = new SecureRandom(); secureRandom.nextInt(); } private String server; private int port; private Socket clientSocket; private ObjectInputStream objInputStream; private ObjectOutputStream objOutputStream; private SocketListener socketListener;
private KeyStoreManager keyStoreManager;
krishnaraj/oneclipboard
oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // }
import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger;
/* * The objOutputStream needs to be created and flushed * before the objInputStream can be created */ objOutputStream = new ObjectOutputStream(clientSocket.getOutputStream()); objOutputStream.flush(); objInputStream = new ObjectInputStream(clientSocket.getInputStream()); } catch (Exception e) { // try reconnecting reconnectCounter++; if (reconnectCounter <= MAX_RECONNECT_ATTEMPTS) { LOGGER.info("Reconnect attempt " + reconnectCounter); connect(); return; } LOGGER.log(Level.SEVERE, "Unable to connect", e); connected = false; return; } LOGGER.info("connected to " + server + ":" + port); connected = true; // resert counter reconnectCounter = 0; socketListener.onConnect(); try { while (listening) { if (objInputStream != null) {
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // } // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger; /* * The objOutputStream needs to be created and flushed * before the objInputStream can be created */ objOutputStream = new ObjectOutputStream(clientSocket.getOutputStream()); objOutputStream.flush(); objInputStream = new ObjectInputStream(clientSocket.getInputStream()); } catch (Exception e) { // try reconnecting reconnectCounter++; if (reconnectCounter <= MAX_RECONNECT_ATTEMPTS) { LOGGER.info("Reconnect attempt " + reconnectCounter); connect(); return; } LOGGER.log(Level.SEVERE, "Unable to connect", e); connected = false; return; } LOGGER.info("connected to " + server + ":" + port); connected = true; // resert counter reconnectCounter = 0; socketListener.onConnect(); try { while (listening) { if (objInputStream != null) {
Message message = (Message) objInputStream.readObject();
krishnaraj/oneclipboard
oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // }
import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger;
} catch (SocketException e) { LOGGER.severe(e.getMessage()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception when listening for message", e); } finally { close(); connected = false; socketListener.onDisconnect(); } } }, "Incoming message listener thread"); listenerThread.start(); return this; } private Socket createSocket() throws Exception { return new Socket(server, port); } @SuppressWarnings("incomplete-switch") private void processMessage(Message message, SocketListener listener) { switch (message.getMessageType()) { case CLIPBOARD_TEXT: listener.onMessageReceived(message); break; case PING: // Server is checking if connection is alive, ping back to say yes.
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/SocketListener.java // public interface SocketListener { // public void onMessageReceived(Message message); // public void onConnect(); // public void onDisconnect(); // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/security/KeyStoreManager.java // public class KeyStoreManager { // KeyStore publicKeyStore; // KeyStore privateKeyStore; // // private TrustManagerFactory tmf; // private KeyManagerFactory kmf; // // protected KeyStoreManager() { // // } // // protected void setPublicKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // publicKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // tmf.init(publicKeyStore); // } // // protected void setPrivateKeyStore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // privateKeyStore = setupKeystore(keyStoreInputStream, passphrase); // // kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // kmf.init(privateKeyStore, passphrase.toCharArray()); // } // // private KeyStore setupKeystore(InputStream keyStoreInputStream, String passphrase) // throws GeneralSecurityException, IOException { // KeyStore keyStore = KeyStore.getInstance("BKS"); // keyStore.load(keyStoreInputStream, passphrase.toCharArray()); // // return keyStore; // } // // public TrustManagerFactory getTrustManagerFactory() { // return tmf; // } // // public KeyManagerFactory getKeyManagerFactory() { // return kmf; // } // // } // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/socket/ClipboardConnector.java import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.SocketListener; import com.cb.oneclipboard.lib.security.KeyStoreManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import java.security.SecureRandom; import java.util.logging.Level; import java.util.logging.Logger; } catch (SocketException e) { LOGGER.severe(e.getMessage()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception when listening for message", e); } finally { close(); connected = false; socketListener.onDisconnect(); } } }, "Incoming message listener thread"); listenerThread.start(); return this; } private Socket createSocket() throws Exception { return new Socket(server, port); } @SuppressWarnings("incomplete-switch") private void processMessage(Message message, SocketListener listener) { switch (message.getMessageType()) { case CLIPBOARD_TEXT: listener.onMessageReceived(message); break; case PING: // Server is checking if connection is alive, ping back to say yes.
send(new Message("ping", MessageType.PING, message.getUser()));
krishnaraj/oneclipboard
oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil;
package com.cb.oneclipboard; public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ClipboardApplication app = ((ClipboardApplication) getApplicationContext()); if (!OneClipboardService.isRunning) { if (app.pref.getUsername() != null && app.pref.getPassword() != null) { initAndStart(); } else { setContentView(R.layout.login); Button loginButton = (Button) findViewById(R.id.btnLogin); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else {
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // } // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil; package com.cb.oneclipboard; public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ClipboardApplication app = ((ClipboardApplication) getApplicationContext()); if (!OneClipboardService.isRunning) { if (app.pref.getUsername() != null && app.pref.getPassword() != null) { initAndStart(); } else { setContentView(R.layout.login); Button loginButton = (Button) findViewById(R.id.btnLogin); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else {
startActivity(IntentUtil.getHomePageIntent(this));
krishnaraj/oneclipboard
oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil;
Button loginButton = (Button) findViewById(R.id.btnLogin); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else { startActivity(IntentUtil.getHomePageIntent(this)); finish(); } } public void initAndStart() { try { ClipboardApplication app = ((ClipboardApplication) getApplicationContext());
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // } // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil; Button loginButton = (Button) findViewById(R.id.btnLogin); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else { startActivity(IntentUtil.getHomePageIntent(this)); finish(); } } public void initAndStart() { try { ClipboardApplication app = ((ClipboardApplication) getApplicationContext());
CipherManager cipherManager = new CipherManager(app.pref.getUsername(), app.pref.getPassword());
krishnaraj/oneclipboard
oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil;
loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else { startActivity(IntentUtil.getHomePageIntent(this)); finish(); } } public void initAndStart() { try { ClipboardApplication app = ((ClipboardApplication) getApplicationContext()); CipherManager cipherManager = new CipherManager(app.pref.getUsername(), app.pref.getPassword());
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // } // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil; loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else { startActivity(IntentUtil.getHomePageIntent(this)); finish(); } } public void initAndStart() { try { ClipboardApplication app = ((ClipboardApplication) getApplicationContext()); CipherManager cipherManager = new CipherManager(app.pref.getUsername(), app.pref.getPassword());
String sha256Hash = Util.getSha256Hash(cipherManager.getEncryptionPassword());
krishnaraj/oneclipboard
oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil;
@Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else { startActivity(IntentUtil.getHomePageIntent(this)); finish(); } } public void initAndStart() { try { ClipboardApplication app = ((ClipboardApplication) getApplicationContext()); CipherManager cipherManager = new CipherManager(app.pref.getUsername(), app.pref.getPassword()); String sha256Hash = Util.getSha256Hash(cipherManager.getEncryptionPassword());
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/CipherManager.java // public class CipherManager { // private BasicTextEncryptor encryptor = new BasicTextEncryptor(); // private String encryptionPassword; // // public CipherManager(String userName, String password) { // encryptionPassword = userName + password; // encryptor.setPassword(encryptionPassword); // } // // public String encrypt(String text) { // return encryptor.encrypt(text); // } // // public String decrypt(String text) { // return encryptor.decrypt(text); // } // // public String getEncryptionPassword() { // return encryptionPassword; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Util.java // public class Util { // // public static String getSha256Hash(String text) throws Exception { // MessageDigest md = MessageDigest.getInstance("SHA-256"); // // md.update(text.getBytes("UTF-8")); // Change this to "UTF-16" if needed // byte[] digest = md.digest(); // // return new String(digest); // } // } // // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java // public class IntentUtil { // // public static Intent getHomePageIntent( Context context ) { // Intent homePageIntent = new Intent( context, HomePageActivity.class ); // homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); // // return homePageIntent; // } // } // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/MainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.cb.oneclipboard.lib.CipherManager; import com.cb.oneclipboard.lib.User; import com.cb.oneclipboard.lib.Util; import com.cb.oneclipboard.util.IntentUtil; @Override public void onClick(View arg0) { TextView usernameField = (TextView) findViewById(R.id.usernameField); TextView passwordField = (TextView) findViewById(R.id.passwordField); String username = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (username.length() > 0 && password.length() > 0) { app.pref.setUsername(username); app.pref.setPassword(password); initAndStart(); } } }); } app.loadProperties(); } else { startActivity(IntentUtil.getHomePageIntent(this)); finish(); } } public void initAndStart() { try { ClipboardApplication app = ((ClipboardApplication) getApplicationContext()); CipherManager cipherManager = new CipherManager(app.pref.getUsername(), app.pref.getPassword()); String sha256Hash = Util.getSha256Hash(cipherManager.getEncryptionPassword());
User user = new User(app.pref.getUsername(), sha256Hash);
krishnaraj/oneclipboard
oneclipboardandroid/src/main/java/com/cb/oneclipboard/ClipboardListener.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Callback.java // public interface Callback { // public void execute(Object object); // }
import android.content.ClipboardManager; import android.content.ClipboardManager.OnPrimaryClipChangedListener; import android.util.Log; import com.cb.oneclipboard.lib.Callback;
package com.cb.oneclipboard; public class ClipboardListener implements OnPrimaryClipChangedListener { private static final String TAG = "ClipboardListener"; ClipboardManager clipBoard = null;
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Callback.java // public interface Callback { // public void execute(Object object); // } // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/ClipboardListener.java import android.content.ClipboardManager; import android.content.ClipboardManager.OnPrimaryClipChangedListener; import android.util.Log; import com.cb.oneclipboard.lib.Callback; package com.cb.oneclipboard; public class ClipboardListener implements OnPrimaryClipChangedListener { private static final String TAG = "ClipboardListener"; ClipboardManager clipBoard = null;
Callback callback = null;
krishnaraj/oneclipboard
oneclipboardserver/src/main/java/com/cb/oneclipboard/server/ServerThread.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // }
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.User; import org.apache.commons.lang3.StringUtils;
package com.cb.oneclipboard.server; public class ServerThread extends Thread { private final static Logger LOGGER = Logger.getLogger(ServerThread.class.getName()); Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null;
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // Path: oneclipboardserver/src/main/java/com/cb/oneclipboard/server/ServerThread.java import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.User; import org.apache.commons.lang3.StringUtils; package com.cb.oneclipboard.server; public class ServerThread extends Thread { private final static Logger LOGGER = Logger.getLogger(ServerThread.class.getName()); Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null;
User user = null;
krishnaraj/oneclipboard
oneclipboardserver/src/main/java/com/cb/oneclipboard/server/ServerThread.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // }
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.User; import org.apache.commons.lang3.StringUtils;
package com.cb.oneclipboard.server; public class ServerThread extends Thread { private final static Logger LOGGER = Logger.getLogger(ServerThread.class.getName()); Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null; User user = null; public ServerThread(Socket socket) throws Exception { super("ServerThread"); this.socket = socket; LOGGER.info("Accepting connection from " + getHostAddress()); start(); } @Override public void run() { try { objInputStream = new ObjectInputStream(socket.getInputStream()); objOutputStream = new ObjectOutputStream(socket.getOutputStream()); objOutputStream.flush(); Registery.register(this);
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // Path: oneclipboardserver/src/main/java/com/cb/oneclipboard/server/ServerThread.java import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.User; import org.apache.commons.lang3.StringUtils; package com.cb.oneclipboard.server; public class ServerThread extends Thread { private final static Logger LOGGER = Logger.getLogger(ServerThread.class.getName()); Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null; User user = null; public ServerThread(Socket socket) throws Exception { super("ServerThread"); this.socket = socket; LOGGER.info("Accepting connection from " + getHostAddress()); start(); } @Override public void run() { try { objInputStream = new ObjectInputStream(socket.getInputStream()); objOutputStream = new ObjectOutputStream(socket.getOutputStream()); objOutputStream.flush(); Registery.register(this);
Message message;
krishnaraj/oneclipboard
oneclipboardserver/src/main/java/com/cb/oneclipboard/server/ServerThread.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // }
import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.User; import org.apache.commons.lang3.StringUtils;
package com.cb.oneclipboard.server; public class ServerThread extends Thread { private final static Logger LOGGER = Logger.getLogger(ServerThread.class.getName()); Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null; User user = null; public ServerThread(Socket socket) throws Exception { super("ServerThread"); this.socket = socket; LOGGER.info("Accepting connection from " + getHostAddress()); start(); } @Override public void run() { try { objInputStream = new ObjectInputStream(socket.getInputStream()); objOutputStream = new ObjectOutputStream(socket.getOutputStream()); objOutputStream.flush(); Registery.register(this); Message message; while ((message = (Message) objInputStream.readObject()) != null) { String abbMessageText = StringUtils.abbreviate(message.getText(), 10); LOGGER.info(String.format("Received '%s' from %s@%s", abbMessageText, message.getUser().getUserName(), getHostAddress()));
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Message.java // public class Message implements Serializable { // /** // * // */ // private static final long serialVersionUID = 7626096672509386693L; // private String text; // private MessageType messageType; // private User user; // // public Message(String text, User user) { // this(text, MessageType.CLIPBOARD_TEXT, user); // } // // public Message(String text, MessageType messageType, User user) { // super(); // this.text = text; // this.messageType = messageType; // this.user = user; // } // // public MessageType getMessageType() { // return messageType; // } // // public void setMessageType(MessageType messageType) { // this.messageType = messageType; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/MessageType.java // public enum MessageType { // REGISTER, // CLIPBOARD_TEXT, // PING, // ; // } // // Path: oneclipboardlib/src/com/cb/oneclipboard/lib/User.java // public class User implements Serializable { // /** // * // */ // private static final long serialVersionUID = -6709827468159234065L; // private String userName; // private String sha256Hash; // // public User(String userName, String sha256Hash) { // super(); // this.userName = userName; // this.sha256Hash = sha256Hash; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // User user = (User) o; // // return sha256Hash != null ? sha256Hash.equals(user.sha256Hash) : user.sha256Hash == null; // // } // // @Override // public int hashCode() { // return sha256Hash != null ? sha256Hash.hashCode() : 0; // } // // public String getSha256Hash() { // return sha256Hash; // } // // public void setSha256Hash(String sha256Hash) { // this.sha256Hash = sha256Hash; // } // // public String getUserName() { // return userName; // } // } // Path: oneclipboardserver/src/main/java/com/cb/oneclipboard/server/ServerThread.java import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; import com.cb.oneclipboard.lib.Message; import com.cb.oneclipboard.lib.MessageType; import com.cb.oneclipboard.lib.User; import org.apache.commons.lang3.StringUtils; package com.cb.oneclipboard.server; public class ServerThread extends Thread { private final static Logger LOGGER = Logger.getLogger(ServerThread.class.getName()); Socket socket = null; ObjectInputStream objInputStream = null; ObjectOutputStream objOutputStream = null; User user = null; public ServerThread(Socket socket) throws Exception { super("ServerThread"); this.socket = socket; LOGGER.info("Accepting connection from " + getHostAddress()); start(); } @Override public void run() { try { objInputStream = new ObjectInputStream(socket.getInputStream()); objOutputStream = new ObjectOutputStream(socket.getOutputStream()); objOutputStream.flush(); Registery.register(this); Message message; while ((message = (Message) objInputStream.readObject()) != null) { String abbMessageText = StringUtils.abbreviate(message.getText(), 10); LOGGER.info(String.format("Received '%s' from %s@%s", abbMessageText, message.getUser().getUserName(), getHostAddress()));
if (message.getMessageType() == MessageType.REGISTER) {
krishnaraj/oneclipboard
oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java
// Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/HomePageActivity.java // public class HomePageActivity extends Activity { // // private static final String TAG = "HomePageActivity"; // // private BroadcastReceiver receiver = null; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.home_page); // // receiver = new BroadcastReceiver() { // // @Override // public void onReceive(Context context, Intent intent) { // String clipboardText = intent.getStringExtra("message"); // TextView clipboardTextView = (TextView) findViewById(R.id.homePageText); // clipboardTextView.setText(clipboardText); // // // Explicitly setting height as otherwise the textView doesn't fill screen height for long text. // LayoutParams params = clipboardTextView.getLayoutParams(); // params.height = getResources().getDimensionPixelSize(R.dimen.text_view_height); // clipboardTextView.setLayoutParams(params); // } // }; // } // // @Override // protected void onStart() { // super.onStart(); // LocalBroadcastManager.getInstance(this).registerReceiver((receiver), new IntentFilter(ClipboardApplication.CLIPBOARD_UPDATED)); // // // This is necessary as the textView won't be updated when the activity wasn't visible. // final ClipboardManager clipBoard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); // TextView clipboardTextView = (TextView) findViewById(R.id.homePageText); // clipboardTextView.setText(clipBoard.getText()); // } // // @Override // protected void onStop() { // LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); // super.onStop(); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.activity_home_page, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // ClipboardApplication app = (ClipboardApplication) getApplication(); // // switch (item.getItemId()) { // case R.id.menu_quit: // stopService(); // finish(); // return true; // case R.id.menu_logout: // stopService(); // app.pref.clear(); // Intent login = new Intent(this, MainActivity.class); // startActivity(login); // finish(); // default: // return super.onOptionsItemSelected(item); // } // } // // public void stopService() { // Intent oneclipboardServiceIntent = new Intent(this, OneClipboardService.class); // stopService(oneclipboardServiceIntent); // } // }
import com.cb.oneclipboard.HomePageActivity; import android.content.Context; import android.content.Intent;
package com.cb.oneclipboard.util; public class IntentUtil { public static Intent getHomePageIntent( Context context ) {
// Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/HomePageActivity.java // public class HomePageActivity extends Activity { // // private static final String TAG = "HomePageActivity"; // // private BroadcastReceiver receiver = null; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.home_page); // // receiver = new BroadcastReceiver() { // // @Override // public void onReceive(Context context, Intent intent) { // String clipboardText = intent.getStringExtra("message"); // TextView clipboardTextView = (TextView) findViewById(R.id.homePageText); // clipboardTextView.setText(clipboardText); // // // Explicitly setting height as otherwise the textView doesn't fill screen height for long text. // LayoutParams params = clipboardTextView.getLayoutParams(); // params.height = getResources().getDimensionPixelSize(R.dimen.text_view_height); // clipboardTextView.setLayoutParams(params); // } // }; // } // // @Override // protected void onStart() { // super.onStart(); // LocalBroadcastManager.getInstance(this).registerReceiver((receiver), new IntentFilter(ClipboardApplication.CLIPBOARD_UPDATED)); // // // This is necessary as the textView won't be updated when the activity wasn't visible. // final ClipboardManager clipBoard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); // TextView clipboardTextView = (TextView) findViewById(R.id.homePageText); // clipboardTextView.setText(clipBoard.getText()); // } // // @Override // protected void onStop() { // LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); // super.onStop(); // } // // @Override // public boolean onCreateOptionsMenu(Menu menu) { // // Inflate the menu; this adds items to the action bar if it is present. // getMenuInflater().inflate(R.menu.activity_home_page, menu); // return true; // } // // @Override // public boolean onOptionsItemSelected(MenuItem item) { // ClipboardApplication app = (ClipboardApplication) getApplication(); // // switch (item.getItemId()) { // case R.id.menu_quit: // stopService(); // finish(); // return true; // case R.id.menu_logout: // stopService(); // app.pref.clear(); // Intent login = new Intent(this, MainActivity.class); // startActivity(login); // finish(); // default: // return super.onOptionsItemSelected(item); // } // } // // public void stopService() { // Intent oneclipboardServiceIntent = new Intent(this, OneClipboardService.class); // stopService(oneclipboardServiceIntent); // } // } // Path: oneclipboardandroid/src/main/java/com/cb/oneclipboard/util/IntentUtil.java import com.cb.oneclipboard.HomePageActivity; import android.content.Context; import android.content.Intent; package com.cb.oneclipboard.util; public class IntentUtil { public static Intent getHomePageIntent( Context context ) {
Intent homePageIntent = new Intent( context, HomePageActivity.class );
krishnaraj/oneclipboard
oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/Utilities.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/ApplicationProperties.java // public class ApplicationProperties { // // static Properties properties = new Properties(); // // public static void loadProperties(String[] fileList, PropertyLoader loader){ // for (int i = fileList.length - 1; i >= 0; i--) { // loader.load(properties, fileList[i]); // } // } // // public static String getStringProperty(String key){ // return properties.getProperty(key); // } // // public static Integer getIntProperty(String key) { // return Integer.parseInt(getStringProperty(key)); // } // // // }
import com.cb.oneclipboard.lib.ApplicationProperties;
package com.cb.oneclipboard.desktop; public class Utilities { public static String getFullApplicationName() {
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/ApplicationProperties.java // public class ApplicationProperties { // // static Properties properties = new Properties(); // // public static void loadProperties(String[] fileList, PropertyLoader loader){ // for (int i = fileList.length - 1; i >= 0; i--) { // loader.load(properties, fileList[i]); // } // } // // public static String getStringProperty(String key){ // return properties.getProperty(key); // } // // public static Integer getIntProperty(String key) { // return Integer.parseInt(getStringProperty(key)); // } // // // } // Path: oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/Utilities.java import com.cb.oneclipboard.lib.ApplicationProperties; package com.cb.oneclipboard.desktop; public class Utilities { public static String getFullApplicationName() {
return ApplicationProperties.getStringProperty("app_name") + " " + ApplicationProperties.getStringProperty("version");
krishnaraj/oneclipboard
oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/ClipboardPollTask.java
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Callback.java // public interface Callback { // public void execute(Object object); // }
import com.cb.oneclipboard.lib.Callback;
package com.cb.oneclipboard.desktop; public class ClipboardPollTask implements Runnable{ private String clipboardContent = null; TextTransfer textTransfer;
// Path: oneclipboardlib/src/com/cb/oneclipboard/lib/Callback.java // public interface Callback { // public void execute(Object object); // } // Path: oneclipboarddesktop/src/main/java/com/cb/oneclipboard/desktop/ClipboardPollTask.java import com.cb.oneclipboard.lib.Callback; package com.cb.oneclipboard.desktop; public class ClipboardPollTask implements Runnable{ private String clipboardContent = null; TextTransfer textTransfer;
Callback callback;
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemProcessor.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named;
package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemProcessor.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named; package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named
public class AuctionDataItemProcessor extends AbstractAuctionFileProcess implements ItemProcessor {
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemProcessor.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named;
package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named public class AuctionDataItemProcessor extends AbstractAuctionFileProcess implements ItemProcessor { @Override public Object processItem(Object item) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemProcessor.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named; package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named public class AuctionDataItemProcessor extends AbstractAuctionFileProcess implements ItemProcessor { @Override public Object processItem(Object item) {
Auction auction = (Auction) item;
radcortez/wow-auctions
batch/src/test/java/com/radcortez/wow/auctions/batch/process/data/ReadSampleAuctionDataTest.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // }
import com.radcortez.wow.auctions.entity.Auction; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.json.Json; import java.io.Serializable; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;
package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ public class ReadSampleAuctionDataTest { private TestableAuctionDataItemReader itemReader; @BeforeEach public void setUp() { itemReader = new TestableAuctionDataItemReader(); itemReader.open(null); } @Test public void testReadSampleAuctionDataTest() { int count = 0;
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // Path: batch/src/test/java/com/radcortez/wow/auctions/batch/process/data/ReadSampleAuctionDataTest.java import com.radcortez.wow.auctions.entity.Auction; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import javax.json.Json; import java.io.Serializable; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ public class ReadSampleAuctionDataTest { private TestableAuctionDataItemReader itemReader; @BeforeEach public void setUp() { itemReader = new TestableAuctionDataItemReader(); itemReader.open(null); } @Test public void testReadSampleAuctionDataTest() { int count = 0;
Auction auction;
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Realm; import org.mapstruct.Builder; import org.mapstruct.CollectionMappingStrategy; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; import org.mapstruct.factory.Mappers;
package com.radcortez.wow.auctions.mapper; @Mapper( collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not ) public interface ConnectedRealmMapper { ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class);
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // Path: batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Realm; import org.mapstruct.Builder; import org.mapstruct.CollectionMappingStrategy; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; import org.mapstruct.factory.Mappers; package com.radcortez.wow.auctions.mapper; @Mapper( collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not ) public interface ConnectedRealmMapper { ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class);
ConnectedRealm toEntity(com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm, String region);
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Realm; import org.mapstruct.Builder; import org.mapstruct.CollectionMappingStrategy; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; import org.mapstruct.factory.Mappers;
package com.radcortez.wow.auctions.mapper; @Mapper( collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not ) public interface ConnectedRealmMapper { ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class); ConnectedRealm toEntity(com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm, String region); @Mapping(target = "id", ignore = true) @Mapping(target = "folders", ignore = true) ConnectedRealm toEntity(ConnectedRealm source, @MappingTarget ConnectedRealm target); // TODO - This is only here due to https://github.com/mapstruct/mapstruct/issues/1477
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // Path: batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Realm; import org.mapstruct.Builder; import org.mapstruct.CollectionMappingStrategy; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; import org.mapstruct.factory.Mappers; package com.radcortez.wow.auctions.mapper; @Mapper( collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not ) public interface ConnectedRealmMapper { ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class); ConnectedRealm toEntity(com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm, String region); @Mapping(target = "id", ignore = true) @Mapping(target = "folders", ignore = true) ConnectedRealm toEntity(ConnectedRealm source, @MappingTarget ConnectedRealm target); // TODO - This is only here due to https://github.com/mapstruct/mapstruct/issues/1477
Realm realm(com.radcortez.wow.auctions.api.Realm realm);
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemReader.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.FileStatus; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.json.Json; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.stream.JsonParser; import javax.transaction.Transactional; import java.io.FileInputStream; import java.io.Serializable; import java.util.Optional; import static org.apache.commons.io.FileUtils.openInputStream;
package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named @Log @Transactional
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemReader.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.FileStatus; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.json.Json; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.stream.JsonParser; import javax.transaction.Transactional; import java.io.FileInputStream; import java.io.Serializable; import java.util.Optional; import static org.apache.commons.io.FileUtils.openInputStream; package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named @Log @Transactional
public class AuctionDataItemReader extends AbstractAuctionFileProcess implements ItemReader {
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemReader.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.FileStatus; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.json.Json; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.stream.JsonParser; import javax.transaction.Transactional; import java.io.FileInputStream; import java.io.Serializable; import java.util.Optional; import static org.apache.commons.io.FileUtils.openInputStream;
package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named @Log @Transactional public class AuctionDataItemReader extends AbstractAuctionFileProcess implements ItemReader { private JsonParser parser; private FileInputStream in; @Override public void open(Serializable checkpoint) throws Exception { log.info("Processing file " + getContext().getAuctionFile().getFileName() + " for Realm " + getContext().getConnectedRealm().getId()); // todo - Configure folderType in = openInputStream(getContext().getAuctionFile(FolderType.FI_TMP)); setParser(Json.createParser(in));
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemReader.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.FileStatus; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.json.Json; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.stream.JsonParser; import javax.transaction.Transactional; import java.io.FileInputStream; import java.io.Serializable; import java.util.Optional; import static org.apache.commons.io.FileUtils.openInputStream; package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named @Log @Transactional public class AuctionDataItemReader extends AbstractAuctionFileProcess implements ItemReader { private JsonParser parser; private FileInputStream in; @Override public void open(Serializable checkpoint) throws Exception { log.info("Processing file " + getContext().getAuctionFile().getFileName() + " for Realm " + getContext().getConnectedRealm().getId()); // todo - Configure folderType in = openInputStream(getContext().getAuctionFile(FolderType.FI_TMP)); setParser(Json.createParser(in));
AuctionFile fileToProcess = getContext().getAuctionFile();
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemReader.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.FileStatus; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.json.Json; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.stream.JsonParser; import javax.transaction.Transactional; import java.io.FileInputStream; import java.io.Serializable; import java.util.Optional; import static org.apache.commons.io.FileUtils.openInputStream;
package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named @Log @Transactional public class AuctionDataItemReader extends AbstractAuctionFileProcess implements ItemReader { private JsonParser parser; private FileInputStream in; @Override public void open(Serializable checkpoint) throws Exception { log.info("Processing file " + getContext().getAuctionFile().getFileName() + " for Realm " + getContext().getConnectedRealm().getId()); // todo - Configure folderType in = openInputStream(getContext().getAuctionFile(FolderType.FI_TMP)); setParser(Json.createParser(in)); AuctionFile fileToProcess = getContext().getAuctionFile(); fileToProcess.setFileStatus(FileStatus.PROCESSING); } @Override public void close() throws Exception { AuctionFile fileToProcess = getContext().getAuctionFile(); fileToProcess.setFileStatus(FileStatus.PROCESSED); if (in != null) { in.close(); } log.info("Finished file " + getContext().getAuctionFile().getFileName() + " for Realm " + getContext().getConnectedRealm().getId()); } @Override public Object readItem() { while (parser.hasNext()) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemReader.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.Auction; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.FileStatus; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.json.Json; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.stream.JsonParser; import javax.transaction.Transactional; import java.io.FileInputStream; import java.io.Serializable; import java.util.Optional; import static org.apache.commons.io.FileUtils.openInputStream; package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named @Log @Transactional public class AuctionDataItemReader extends AbstractAuctionFileProcess implements ItemReader { private JsonParser parser; private FileInputStream in; @Override public void open(Serializable checkpoint) throws Exception { log.info("Processing file " + getContext().getAuctionFile().getFileName() + " for Realm " + getContext().getConnectedRealm().getId()); // todo - Configure folderType in = openInputStream(getContext().getAuctionFile(FolderType.FI_TMP)); setParser(Json.createParser(in)); AuctionFile fileToProcess = getContext().getAuctionFile(); fileToProcess.setFileStatus(FileStatus.PROCESSING); } @Override public void close() throws Exception { AuctionFile fileToProcess = getContext().getAuctionFile(); fileToProcess.setFileStatus(FileStatus.PROCESSED); if (in != null) { in.close(); } log.info("Finished file " + getContext().getAuctionFile().getFileName() + " for Realm " + getContext().getConnectedRealm().getId()); } @Override public Object readItem() { while (parser.hasNext()) {
Auction auction = new Auction();
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java // @Mapper( // collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, // builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not // ) // public interface ConnectedRealmMapper { // ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class); // // ConnectedRealm toEntity(com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm, String region); // // @Mapping(target = "id", ignore = true) // @Mapping(target = "folders", ignore = true) // ConnectedRealm toEntity(ConnectedRealm source, @MappingTarget ConnectedRealm target); // // // TODO - This is only here due to https://github.com/mapstruct/mapstruct/issues/1477 // Realm realm(com.radcortez.wow.auctions.api.Realm realm); // }
import com.radcortez.wow.auctions.mapper.ConnectedRealmMapper; import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.Singular; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.MapKey; import javax.persistence.OneToMany; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import static javax.persistence.CascadeType.ALL; import static javax.persistence.FetchType.EAGER;
public ConnectedRealm( final String id, final Region region, @Singular final Set<Realm> realms, final Map<FolderType, Folder> folders, final Set<AuctionFile> files) { this.id = id; this.region = region; this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); } public void addRealm(final Realm realm) { realm.setConnectedRealm(this); realms.add(realm); } public ConnectedRealm create() { realms.stream() .filter(realm -> realm.getConnectedRealm() == null) .forEach(realm -> realm.setConnectedRealm(this)); persist(); return this; } public ConnectedRealm update(final ConnectedRealm connectedRealm) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java // @Mapper( // collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, // builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not // ) // public interface ConnectedRealmMapper { // ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class); // // ConnectedRealm toEntity(com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm, String region); // // @Mapping(target = "id", ignore = true) // @Mapping(target = "folders", ignore = true) // ConnectedRealm toEntity(ConnectedRealm source, @MappingTarget ConnectedRealm target); // // // TODO - This is only here due to https://github.com/mapstruct/mapstruct/issues/1477 // Realm realm(com.radcortez.wow.auctions.api.Realm realm); // } // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java import com.radcortez.wow.auctions.mapper.ConnectedRealmMapper; import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.Singular; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.MapKey; import javax.persistence.OneToMany; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import static javax.persistence.CascadeType.ALL; import static javax.persistence.FetchType.EAGER; public ConnectedRealm( final String id, final Region region, @Singular final Set<Realm> realms, final Map<FolderType, Folder> folders, final Set<AuctionFile> files) { this.id = id; this.region = region; this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); } public void addRealm(final Realm realm) { realm.setConnectedRealm(this); realms.add(realm); } public ConnectedRealm create() { realms.stream() .filter(realm -> realm.getConnectedRealm() == null) .forEach(realm -> realm.setConnectedRealm(this)); persist(); return this; } public ConnectedRealm update(final ConnectedRealm connectedRealm) {
return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm);
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsReader.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import lombok.extern.java.Log; import org.apache.commons.dbutils.DbUtils; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import java.io.Serializable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Optional;
package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named @Log
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsReader.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import lombok.extern.java.Log; import org.apache.commons.dbutils.DbUtils; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.batch.api.chunk.ItemReader; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import java.io.Serializable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Optional; package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named @Log
public class ProcessedAuctionsReader extends AbstractAuctionFileProcess implements ItemReader {
radcortez/wow-auctions
itest/src/test/java/com/radcortez/wow/auctions/batch/itest/PrepareJobTest.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; import javax.inject.Inject; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertFalse;
package com.radcortez.wow.auctions.batch.itest; @QuarkusTest public class PrepareJobTest { @Inject JobOperator jobOperator; @Test void prepareJob() { long executionId = jobOperator.start("prepare-job", new Properties()); await().atMost(60, TimeUnit.SECONDS).until(() -> { final JobExecution jobExecution = jobOperator.getJobExecution(executionId); return BatchStatus.COMPLETED.equals(jobExecution.getBatchStatus()); });
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // Path: itest/src/test/java/com/radcortez/wow/auctions/batch/itest/PrepareJobTest.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchStatus; import javax.batch.runtime.JobExecution; import javax.inject.Inject; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertFalse; package com.radcortez.wow.auctions.batch.itest; @QuarkusTest public class PrepareJobTest { @Inject JobOperator jobOperator; @Test void prepareJob() { long executionId = jobOperator.start("prepare-job", new Properties()); await().atMost(60, TimeUnit.SECONDS).until(() -> { final JobExecution jobExecution = jobOperator.getJobExecution(executionId); return BatchStatus.COMPLETED.equals(jobExecution.getBatchStatus()); });
assertFalse(ConnectedRealm.listAll().isEmpty());
radcortez/wow-auctions
batch/src/test/java/com/radcortez/wow/auctions/batch/process/statistics/AuctionsProcessorTest.java
// Path: batch/src/test/java/com/radcortez/wow/auctions/QuarkusDataSourceProvider.java // public class QuarkusDataSourceProvider implements DataSourceProvider { // @Override // @SneakyThrows // public DataSourceInfo getDatasourceInfo(final ExtensionContext extensionContext) { // // We don't have access to the Quarkus CL here, so we cannot use ConfigProvider.getConfig() to retrieve the same configuration. // // URL properties = Thread.currentThread().getContextClassLoader().getResource("application.properties"); // assert properties != null; // // SmallRyeConfig config = new SmallRyeConfigBuilder() // .withSources(new PropertiesConfigSource(properties)) // .withProfile("test") // .build(); // // return DataSourceInfo.config(config.getRawValue("quarkus.datasource.jdbc.url")); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // }
import com.radcortez.flyway.test.annotation.DataSource; import com.radcortez.flyway.test.annotation.FlywayTest; import com.radcortez.wow.auctions.QuarkusDataSourceProvider; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.AuctionStatistics; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull;
package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @QuarkusTest @FlywayTest(@DataSource(QuarkusDataSourceProvider.class)) @Transactional public class AuctionsProcessorTest { @Inject ProcessedAuctionsReader processedAuctionsReader; @Inject ProcessedAuctionsProcessor processor; @Test public void testProcessedAuctionsReader() throws Exception {
// Path: batch/src/test/java/com/radcortez/wow/auctions/QuarkusDataSourceProvider.java // public class QuarkusDataSourceProvider implements DataSourceProvider { // @Override // @SneakyThrows // public DataSourceInfo getDatasourceInfo(final ExtensionContext extensionContext) { // // We don't have access to the Quarkus CL here, so we cannot use ConfigProvider.getConfig() to retrieve the same configuration. // // URL properties = Thread.currentThread().getContextClassLoader().getResource("application.properties"); // assert properties != null; // // SmallRyeConfig config = new SmallRyeConfigBuilder() // .withSources(new PropertiesConfigSource(properties)) // .withProfile("test") // .build(); // // return DataSourceInfo.config(config.getRawValue("quarkus.datasource.jdbc.url")); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // } // Path: batch/src/test/java/com/radcortez/wow/auctions/batch/process/statistics/AuctionsProcessorTest.java import com.radcortez.flyway.test.annotation.DataSource; import com.radcortez.flyway.test.annotation.FlywayTest; import com.radcortez.wow.auctions.QuarkusDataSourceProvider; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.AuctionStatistics; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @QuarkusTest @FlywayTest(@DataSource(QuarkusDataSourceProvider.class)) @Transactional public class AuctionsProcessorTest { @Inject ProcessedAuctionsReader processedAuctionsReader; @Inject ProcessedAuctionsProcessor processor; @Test public void testProcessedAuctionsReader() throws Exception {
processedAuctionsReader.getContext().setAuctionFile(AuctionFile.findById(1L));
radcortez/wow-auctions
batch/src/test/java/com/radcortez/wow/auctions/batch/process/statistics/AuctionsProcessorTest.java
// Path: batch/src/test/java/com/radcortez/wow/auctions/QuarkusDataSourceProvider.java // public class QuarkusDataSourceProvider implements DataSourceProvider { // @Override // @SneakyThrows // public DataSourceInfo getDatasourceInfo(final ExtensionContext extensionContext) { // // We don't have access to the Quarkus CL here, so we cannot use ConfigProvider.getConfig() to retrieve the same configuration. // // URL properties = Thread.currentThread().getContextClassLoader().getResource("application.properties"); // assert properties != null; // // SmallRyeConfig config = new SmallRyeConfigBuilder() // .withSources(new PropertiesConfigSource(properties)) // .withProfile("test") // .build(); // // return DataSourceInfo.config(config.getRawValue("quarkus.datasource.jdbc.url")); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // }
import com.radcortez.flyway.test.annotation.DataSource; import com.radcortez.flyway.test.annotation.FlywayTest; import com.radcortez.wow.auctions.QuarkusDataSourceProvider; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.AuctionStatistics; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull;
package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @QuarkusTest @FlywayTest(@DataSource(QuarkusDataSourceProvider.class)) @Transactional public class AuctionsProcessorTest { @Inject ProcessedAuctionsReader processedAuctionsReader; @Inject ProcessedAuctionsProcessor processor; @Test public void testProcessedAuctionsReader() throws Exception { processedAuctionsReader.getContext().setAuctionFile(AuctionFile.findById(1L)); processedAuctionsReader.open(null); assertNotNull(processedAuctionsReader.readItem()); assertNotNull(processedAuctionsReader.readItem()); assertNotNull(processedAuctionsReader.readItem()); assertNull(processedAuctionsReader.readItem()); } @Test public void testProcessedAuctionsProcessor() throws Exception { processedAuctionsReader.getContext().setAuctionFile(AuctionFile.findById(1L)); processedAuctionsReader.open(null); Object auction; while ((auction = processedAuctionsReader.readItem()) != null) {
// Path: batch/src/test/java/com/radcortez/wow/auctions/QuarkusDataSourceProvider.java // public class QuarkusDataSourceProvider implements DataSourceProvider { // @Override // @SneakyThrows // public DataSourceInfo getDatasourceInfo(final ExtensionContext extensionContext) { // // We don't have access to the Quarkus CL here, so we cannot use ConfigProvider.getConfig() to retrieve the same configuration. // // URL properties = Thread.currentThread().getContextClassLoader().getResource("application.properties"); // assert properties != null; // // SmallRyeConfig config = new SmallRyeConfigBuilder() // .withSources(new PropertiesConfigSource(properties)) // .withProfile("test") // .build(); // // return DataSourceInfo.config(config.getRawValue("quarkus.datasource.jdbc.url")); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // } // Path: batch/src/test/java/com/radcortez/wow/auctions/batch/process/statistics/AuctionsProcessorTest.java import com.radcortez.flyway.test.annotation.DataSource; import com.radcortez.flyway.test.annotation.FlywayTest; import com.radcortez.wow.auctions.QuarkusDataSourceProvider; import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.AuctionStatistics; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @QuarkusTest @FlywayTest(@DataSource(QuarkusDataSourceProvider.class)) @Transactional public class AuctionsProcessorTest { @Inject ProcessedAuctionsReader processedAuctionsReader; @Inject ProcessedAuctionsProcessor processor; @Test public void testProcessedAuctionsReader() throws Exception { processedAuctionsReader.getContext().setAuctionFile(AuctionFile.findById(1L)); processedAuctionsReader.open(null); assertNotNull(processedAuctionsReader.readItem()); assertNotNull(processedAuctionsReader.readItem()); assertNotNull(processedAuctionsReader.readItem()); assertNull(processedAuctionsReader.readItem()); } @Test public void testProcessedAuctionsProcessor() throws Exception { processedAuctionsReader.getContext().setAuctionFile(AuctionFile.findById(1L)); processedAuctionsReader.open(null); Object auction; while ((auction = processedAuctionsReader.readItem()) != null) {
AuctionStatistics auctionStatistics = (AuctionStatistics) processor.processItem(auction);
radcortez/wow-auctions
batch/src/test/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapperTest.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Region.java // public enum Region { // US, // EU // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import com.radcortez.wow.auctions.entity.Realm; import com.radcortez.wow.auctions.entity.Region; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull;
package com.radcortez.wow.auctions.mapper; class ConnectedRealmMapperTest { @Test void toConnectedRealm() {
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Region.java // public enum Region { // US, // EU // } // Path: batch/src/test/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapperTest.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import com.radcortez.wow.auctions.entity.Realm; import com.radcortez.wow.auctions.entity.Region; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; package com.radcortez.wow.auctions.mapper; class ConnectedRealmMapperTest { @Test void toConnectedRealm() {
com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm = new com.radcortez.wow.auctions.api.ConnectedRealm();
radcortez/wow-auctions
batch/src/test/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapperTest.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Region.java // public enum Region { // US, // EU // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import com.radcortez.wow.auctions.entity.Realm; import com.radcortez.wow.auctions.entity.Region; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull;
package com.radcortez.wow.auctions.mapper; class ConnectedRealmMapperTest { @Test void toConnectedRealm() { com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm = new com.radcortez.wow.auctions.api.ConnectedRealm(); connectedRealm.setId("1"); connectedRealm.setRealms(new HashSet<>());
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Region.java // public enum Region { // US, // EU // } // Path: batch/src/test/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapperTest.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import com.radcortez.wow.auctions.entity.Realm; import com.radcortez.wow.auctions.entity.Region; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; package com.radcortez.wow.auctions.mapper; class ConnectedRealmMapperTest { @Test void toConnectedRealm() { com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm = new com.radcortez.wow.auctions.api.ConnectedRealm(); connectedRealm.setId("1"); connectedRealm.setRealms(new HashSet<>());
com.radcortez.wow.auctions.api.Realm realm = new com.radcortez.wow.auctions.api.Realm();
radcortez/wow-auctions
batch/src/test/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapperTest.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Region.java // public enum Region { // US, // EU // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import com.radcortez.wow.auctions.entity.Realm; import com.radcortez.wow.auctions.entity.Region; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull;
package com.radcortez.wow.auctions.mapper; class ConnectedRealmMapperTest { @Test void toConnectedRealm() { com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm = new com.radcortez.wow.auctions.api.ConnectedRealm(); connectedRealm.setId("1"); connectedRealm.setRealms(new HashSet<>()); com.radcortez.wow.auctions.api.Realm realm = new com.radcortez.wow.auctions.api.Realm(); realm.setId("1"); realm.setName("Grim Batol"); realm.setSlug("grim-batol"); connectedRealm.getRealms().add(realm); ConnectedRealm toConnectedRealm = ConnectedRealmMapper.INSTANCE.toEntity(connectedRealm, "EU"); assertEquals(connectedRealm.getId(), toConnectedRealm.getId());
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Realm.java // @NoArgsConstructor // @AllArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // @Builder // // @Entity // public class Realm extends PanacheEntityBase { // @Id // private String id; // private String name; // private String slug; // // @ManyToOne(cascade = CascadeType.ALL, optional = false) // private ConnectedRealm connectedRealm; // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Region.java // public enum Region { // US, // EU // } // Path: batch/src/test/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapperTest.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import com.radcortez.wow.auctions.entity.Realm; import com.radcortez.wow.auctions.entity.Region; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; package com.radcortez.wow.auctions.mapper; class ConnectedRealmMapperTest { @Test void toConnectedRealm() { com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm = new com.radcortez.wow.auctions.api.ConnectedRealm(); connectedRealm.setId("1"); connectedRealm.setRealms(new HashSet<>()); com.radcortez.wow.auctions.api.Realm realm = new com.radcortez.wow.auctions.api.Realm(); realm.setId("1"); realm.setName("Grim Batol"); realm.setSlug("grim-batol"); connectedRealm.getRealms().add(realm); ConnectedRealm toConnectedRealm = ConnectedRealmMapper.INSTANCE.toEntity(connectedRealm, "EU"); assertEquals(connectedRealm.getId(), toConnectedRealm.getId());
assertEquals(Region.EU, toConnectedRealm.getRegion());
radcortez/wow-auctions
batch/src/test/java/com/radcortez/wow/auctions/batch/process/purge/PurgeRawAuctionDataBatchletTest.java
// Path: batch/src/test/java/com/radcortez/wow/auctions/QuarkusDataSourceProvider.java // public class QuarkusDataSourceProvider implements DataSourceProvider { // @Override // @SneakyThrows // public DataSourceInfo getDatasourceInfo(final ExtensionContext extensionContext) { // // We don't have access to the Quarkus CL here, so we cannot use ConfigProvider.getConfig() to retrieve the same configuration. // // URL properties = Thread.currentThread().getContextClassLoader().getResource("application.properties"); // assert properties != null; // // SmallRyeConfig config = new SmallRyeConfigBuilder() // .withSources(new PropertiesConfigSource(properties)) // .withProfile("test") // .build(); // // return DataSourceInfo.config(config.getRawValue("quarkus.datasource.jdbc.url")); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // }
import com.radcortez.flyway.test.annotation.DataSource; import com.radcortez.flyway.test.annotation.FlywayTest; import com.radcortez.wow.auctions.QuarkusDataSourceProvider; import com.radcortez.wow.auctions.entity.AuctionFile; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import javax.batch.runtime.context.JobContext; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.assertEquals;
package com.radcortez.wow.auctions.batch.process.purge; /** * @author Ivan St. Ivanov */ @QuarkusTest @FlywayTest(@DataSource(QuarkusDataSourceProvider.class)) @Transactional @Disabled public class PurgeRawAuctionDataBatchletTest { @Inject PurgeRawAuctionDataBatchlet batchlet; @Inject JobContext jobContext; @BeforeEach public void setUp() { jobContext.getProperties().setProperty("auctionFileId", "1"); } @Test public void testPurgeRawAuctionData() { batchlet.process();
// Path: batch/src/test/java/com/radcortez/wow/auctions/QuarkusDataSourceProvider.java // public class QuarkusDataSourceProvider implements DataSourceProvider { // @Override // @SneakyThrows // public DataSourceInfo getDatasourceInfo(final ExtensionContext extensionContext) { // // We don't have access to the Quarkus CL here, so we cannot use ConfigProvider.getConfig() to retrieve the same configuration. // // URL properties = Thread.currentThread().getContextClassLoader().getResource("application.properties"); // assert properties != null; // // SmallRyeConfig config = new SmallRyeConfigBuilder() // .withSources(new PropertiesConfigSource(properties)) // .withProfile("test") // .build(); // // return DataSourceInfo.config(config.getRawValue("quarkus.datasource.jdbc.url")); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // Path: batch/src/test/java/com/radcortez/wow/auctions/batch/process/purge/PurgeRawAuctionDataBatchletTest.java import com.radcortez.flyway.test.annotation.DataSource; import com.radcortez.flyway.test.annotation.FlywayTest; import com.radcortez.wow.auctions.QuarkusDataSourceProvider; import com.radcortez.wow.auctions.entity.AuctionFile; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import javax.batch.runtime.context.JobContext; import javax.inject.Inject; import javax.transaction.Transactional; import static org.junit.jupiter.api.Assertions.assertEquals; package com.radcortez.wow.auctions.batch.process.purge; /** * @author Ivan St. Ivanov */ @QuarkusTest @FlywayTest(@DataSource(QuarkusDataSourceProvider.class)) @Transactional @Disabled public class PurgeRawAuctionDataBatchletTest { @Inject PurgeRawAuctionDataBatchlet batchlet; @Inject JobContext jobContext; @BeforeEach public void setUp() { jobContext.getProperties().setProperty("auctionFileId", "1"); } @Test public void testPurgeRawAuctionData() { batchlet.process();
assertEquals(1, AuctionFile.listAll().size());
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/purge/PurgeRawAuctionDataBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import javax.batch.api.Batchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.transaction.Transactional;
package com.radcortez.wow.auctions.batch.process.purge; /** * @author Ivan St. Ivanov */ @Dependent @Named
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/purge/PurgeRawAuctionDataBatchlet.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import javax.batch.api.Batchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Named; import javax.transaction.Transactional; package com.radcortez.wow.auctions.batch.process.purge; /** * @author Ivan St. Ivanov */ @Dependent @Named
public class PurgeRawAuctionDataBatchlet extends AbstractAuctionFileProcess implements Batchlet {
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // }
import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.FolderType; import lombok.RequiredArgsConstructor; import javax.annotation.PostConstruct; import javax.batch.runtime.context.JobContext; import javax.inject.Inject; import java.io.File; import static org.apache.commons.io.FileUtils.getFile;
package com.radcortez.wow.auctions.batch.process; /** * @author Roberto Cortez */ public abstract class AbstractAuctionFileProcess { @Inject JobContext jobContext; @PostConstruct void init() { final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); if (jobContext.getTransientUserData() == null) { jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); } } public AuctionFileProcessContext getContext() { return (AuctionFileProcessContext) jobContext.getTransientUserData(); } @RequiredArgsConstructor public static class AuctionFileProcessContext { private final String connectedRealmId;
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.FolderType; import lombok.RequiredArgsConstructor; import javax.annotation.PostConstruct; import javax.batch.runtime.context.JobContext; import javax.inject.Inject; import java.io.File; import static org.apache.commons.io.FileUtils.getFile; package com.radcortez.wow.auctions.batch.process; /** * @author Roberto Cortez */ public abstract class AbstractAuctionFileProcess { @Inject JobContext jobContext; @PostConstruct void init() { final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); if (jobContext.getTransientUserData() == null) { jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); } } public AuctionFileProcessContext getContext() { return (AuctionFileProcessContext) jobContext.getTransientUserData(); } @RequiredArgsConstructor public static class AuctionFileProcessContext { private final String connectedRealmId;
private ConnectedRealm connectedRealm;
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // }
import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.FolderType; import lombok.RequiredArgsConstructor; import javax.annotation.PostConstruct; import javax.batch.runtime.context.JobContext; import javax.inject.Inject; import java.io.File; import static org.apache.commons.io.FileUtils.getFile;
package com.radcortez.wow.auctions.batch.process; /** * @author Roberto Cortez */ public abstract class AbstractAuctionFileProcess { @Inject JobContext jobContext; @PostConstruct void init() { final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); if (jobContext.getTransientUserData() == null) { jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); } } public AuctionFileProcessContext getContext() { return (AuctionFileProcessContext) jobContext.getTransientUserData(); } @RequiredArgsConstructor public static class AuctionFileProcessContext { private final String connectedRealmId; private ConnectedRealm connectedRealm;
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionFile.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class AuctionFile extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private String fileName; // @Enumerated(EnumType.STRING) // private FileStatus fileStatus; // private Long timestamp; // // @OneToMany(mappedBy = "auctionFile", cascade = CascadeType.ALL, orphanRemoval = true) // private Set<Auction> auctions = new HashSet<>(); // @ManyToOne(optional = false) // private ConnectedRealm connectedRealm; // // @Builder // public AuctionFile( // final String fileName, // final FileStatus fileStatus, // final Long timestamp, // final Set<Auction> auctions, // final ConnectedRealm connectedRealm) { // // this.fileName = fileName; // this.fileStatus = fileStatus; // this.timestamp = timestamp; // this.auctions = Optional.ofNullable(auctions).map(HashSet::new).orElse(new HashSet<>()); // this.connectedRealm = connectedRealm; // } // // public AuctionFile create() { // persist(); // return this; // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java import com.radcortez.wow.auctions.entity.AuctionFile; import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.FolderType; import lombok.RequiredArgsConstructor; import javax.annotation.PostConstruct; import javax.batch.runtime.context.JobContext; import javax.inject.Inject; import java.io.File; import static org.apache.commons.io.FileUtils.getFile; package com.radcortez.wow.auctions.batch.process; /** * @author Roberto Cortez */ public abstract class AbstractAuctionFileProcess { @Inject JobContext jobContext; @PostConstruct void init() { final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); if (jobContext.getTransientUserData() == null) { jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); } } public AuctionFileProcessContext getContext() { return (AuctionFileProcessContext) jobContext.getTransientUserData(); } @RequiredArgsConstructor public static class AuctionFileProcessContext { private final String connectedRealmId; private ConnectedRealm connectedRealm;
private AuctionFile auctionFile;
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // }
import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI;
package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI; package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject
ApiConfig apiConfig;
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // }
import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI;
package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject ApiConfig apiConfig; @Inject
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI; package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject ApiConfig apiConfig; @Inject
ConnectedRealmsApi connectedRealmsApi;
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // }
import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI;
package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject ApiConfig apiConfig; @Inject ConnectedRealmsApi connectedRealmsApi; @Inject
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI; package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject ApiConfig apiConfig; @Inject ConnectedRealmsApi connectedRealmsApi; @Inject
LocationApi locationApi;
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // }
import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI;
package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject ApiConfig apiConfig; @Inject ConnectedRealmsApi connectedRealmsApi; @Inject LocationApi locationApi; @Override @Transactional public String process() { log.info(ConnectRealmsBatchlet.class.getSimpleName() + " running"); connectedRealmsApi.index() .getConnectedRealms() .forEach(location -> createConnectedRealmFromUri(location.getHref())); log.info(ConnectRealmsBatchlet.class.getSimpleName() + " completed"); return BatchStatus.COMPLETED.toString(); } private void createConnectedRealmFromUri(final URI connectedRealmUri) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/api/ApiConfig.java // @ConfigMapping(prefix = "api.blizzard") // public interface ApiConfig { // String host(); // String locale(); // // default String region() { // return ConfigProvider.getConfig().getConfigValue("api.blizzard.region").getRawValue(); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealmsApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // @Path("/data/wow/connected-realm") // public interface ConnectedRealmsApi extends AutoCloseable { // @GET // @Path("/index") // ConnectedRealms index(); // // @GET // @Path("/{connectedRealmId}/auctions") // InputStream auctions(@PathParam("connectedRealmId") String connectedRealmId); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/api/LocationApi.java // @Produces(MediaType.APPLICATION_JSON) // @Consumes(MediaType.APPLICATION_JSON) // public interface LocationApi extends AutoCloseable { // @GET // @Path("/{location}") // ConnectedRealm getConnectedRealm(@PathParam ("location") String location); // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/ConnectRealmsBatchlet.java import com.radcortez.wow.auctions.api.ApiConfig; import com.radcortez.wow.auctions.api.ConnectedRealmsApi; import com.radcortez.wow.auctions.api.LocationApi; import com.radcortez.wow.auctions.entity.ConnectedRealm; import lombok.extern.java.Log; import org.eclipse.microprofile.config.Config; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.net.URI; package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class ConnectRealmsBatchlet extends AbstractBatchlet { @Inject ApiConfig apiConfig; @Inject ConnectedRealmsApi connectedRealmsApi; @Inject LocationApi locationApi; @Override @Transactional public String process() { log.info(ConnectRealmsBatchlet.class.getSimpleName() + " running"); connectedRealmsApi.index() .getConnectedRealms() .forEach(location -> createConnectedRealmFromUri(location.getHref())); log.info(ConnectRealmsBatchlet.class.getSimpleName() + " completed"); return BatchStatus.COMPLETED.toString(); } private void createConnectedRealmFromUri(final URI connectedRealmUri) {
com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm =
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealm.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java // @Mapper( // collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, // builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not // ) // public interface ConnectedRealmMapper { // ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class); // // ConnectedRealm toEntity(com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm, String region); // // @Mapping(target = "id", ignore = true) // @Mapping(target = "folders", ignore = true) // ConnectedRealm toEntity(ConnectedRealm source, @MappingTarget ConnectedRealm target); // // // TODO - This is only here due to https://github.com/mapstruct/mapstruct/issues/1477 // Realm realm(com.radcortez.wow.auctions.api.Realm realm); // }
import com.radcortez.wow.auctions.mapper.ConnectedRealmMapper; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Set;
package com.radcortez.wow.auctions.api; @NoArgsConstructor @Data public class ConnectedRealm { private String id; private Status status; private Set<Realm> realms; public boolean isDown() { return Status.Type.DOWN.equals(status.getType()); } public com.radcortez.wow.auctions.entity.ConnectedRealm toEntity(final String region) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/mapper/ConnectedRealmMapper.java // @Mapper( // collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED, // builder = @Builder(disableBuilder = true) // TODO - Figure out if we should use builder or not // ) // public interface ConnectedRealmMapper { // ConnectedRealmMapper INSTANCE = Mappers.getMapper(ConnectedRealmMapper.class); // // ConnectedRealm toEntity(com.radcortez.wow.auctions.api.ConnectedRealm connectedRealm, String region); // // @Mapping(target = "id", ignore = true) // @Mapping(target = "folders", ignore = true) // ConnectedRealm toEntity(ConnectedRealm source, @MappingTarget ConnectedRealm target); // // // TODO - This is only here due to https://github.com/mapstruct/mapstruct/issues/1477 // Realm realm(com.radcortez.wow.auctions.api.Realm realm); // } // Path: batch/src/main/java/com/radcortez/wow/auctions/api/ConnectedRealm.java import com.radcortez.wow.auctions.mapper.ConnectedRealmMapper; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Set; package com.radcortez.wow.auctions.api; @NoArgsConstructor @Data public class ConnectedRealm { private String id; private Status status; private Set<Realm> realms; public boolean isDown() { return Status.Type.DOWN.equals(status.getType()); } public com.radcortez.wow.auctions.entity.ConnectedRealm toEntity(final String region) {
return ConnectedRealmMapper.INSTANCE.toEntity(this, region.toUpperCase());
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsWriter.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // }
import com.radcortez.wow.auctions.entity.AuctionStatistics; import javax.batch.api.chunk.AbstractItemWriter; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.util.List;
package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named public class ProcessedAuctionsWriter extends AbstractItemWriter { @Override @SuppressWarnings("unchecked") public void writeItems(List<Object> items) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsWriter.java import com.radcortez.wow.auctions.entity.AuctionStatistics; import javax.batch.api.chunk.AbstractItemWriter; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.util.List; package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named public class ProcessedAuctionsWriter extends AbstractItemWriter { @Override @SuppressWarnings("unchecked") public void writeItems(List<Object> items) {
items.stream().map(AuctionStatistics.class::cast).forEach(AuctionStatistics::create);
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsProcessor.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.AuctionStatistics; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.sql.ResultSet;
package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsProcessor.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.AuctionStatistics; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.sql.ResultSet; package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named
public class ProcessedAuctionsProcessor extends AbstractAuctionFileProcess implements ItemProcessor {
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsProcessor.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.AuctionStatistics; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.sql.ResultSet;
package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named public class ProcessedAuctionsProcessor extends AbstractAuctionFileProcess implements ItemProcessor { @Override public Object processItem(Object item) throws Exception { ResultSet resultSet = (ResultSet) item;
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/AuctionStatistics.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // @NamedQueries({ // @NamedQuery(name = "AuctionItemStatistics.findByRealmsAndItem", // query = "SELECT ais FROM AuctionStatistics ais " + // "WHERE ais.connectedRealm.id IN :realmIds AND ais.itemId = :itemId " + // "ORDER BY ais.timestamp ASC") // }) // public class AuctionStatistics extends PanacheEntityBase { // @Id // @GeneratedValue // private Long id; // private Integer itemId; // private Long quantity; // // private Long bid; // private Long minBid; // private Long maxBid; // // private Long buyout; // private Long minBuyout; // private Long maxBuyout; // // private Double avgBid; // private Double avgBuyout; // private Long timestamp; // // @ManyToOne // private ConnectedRealm connectedRealm; // // public AuctionStatistics create() { // persist(); // return this; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/statistics/ProcessedAuctionsProcessor.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.AuctionStatistics; import javax.batch.api.chunk.ItemProcessor; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.sql.ResultSet; package com.radcortez.wow.auctions.batch.process.statistics; /** * @author Ivan St. Ivanov */ @Dependent @Named public class ProcessedAuctionsProcessor extends AbstractAuctionFileProcess implements ItemProcessor { @Override public Object processItem(Object item) throws Exception { ResultSet resultSet = (ResultSet) item;
AuctionStatistics auctionStatistics = new AuctionStatistics();
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/FolderCreationBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import org.apache.commons.io.FileUtils; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.io.File; import java.io.IOException;
package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class FolderCreationBatchlet extends AbstractBatchlet { @Inject @ConfigProperty(name = "wow.batch.home") String batchHome; @Override @Transactional public String process() { log.info(FolderCreationBatchlet.class.getSimpleName() + " running");
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/FolderCreationBatchlet.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import org.apache.commons.io.FileUtils; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.io.File; import java.io.IOException; package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class FolderCreationBatchlet extends AbstractBatchlet { @Inject @ConfigProperty(name = "wow.batch.home") String batchHome; @Override @Transactional public String process() { log.info(FolderCreationBatchlet.class.getSimpleName() + " running");
ConnectedRealm.<ConnectedRealm>listAll().forEach(this::verifyAndCreateFolder);
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/FolderCreationBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // }
import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import org.apache.commons.io.FileUtils; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.io.File; import java.io.IOException;
package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class FolderCreationBatchlet extends AbstractBatchlet { @Inject @ConfigProperty(name = "wow.batch.home") String batchHome; @Override @Transactional public String process() { log.info(FolderCreationBatchlet.class.getSimpleName() + " running"); ConnectedRealm.<ConnectedRealm>listAll().forEach(this::verifyAndCreateFolder); log.info(FolderCreationBatchlet.class.getSimpleName() + " completed"); return BatchStatus.COMPLETED.toString(); } private void verifyAndCreateFolder(final ConnectedRealm connectedRealm) { for (FolderType folderType : FolderType.values()) { File folder = FileUtils.getFile(batchHome, connectedRealm.getRegion().toString(), connectedRealm.getId(), folderType.toString()); if (!folder.exists()) { try { log.info("Creating folder " + folder); FileUtils.forceMkdir(folder); } catch (IOException e) { // Ignore continue; } } if (!connectedRealm.getFolders().containsKey(folderType)) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/ConnectedRealm.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // // @Entity // public class ConnectedRealm extends PanacheEntityBase { // @Id // private String id; // @Enumerated(EnumType.STRING) // private Region region; // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<Realm> realms = new HashSet<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true, fetch = EAGER) // @MapKey(name = "id.folderType") // private Map<FolderType, Folder> folders = new HashMap<>(); // @OneToMany(mappedBy = "connectedRealm", cascade = ALL, orphanRemoval = true) // private Set<AuctionFile> files = new HashSet<>(); // // @Builder(toBuilder = true) // public ConnectedRealm( // final String id, // final Region region, // @Singular // final Set<Realm> realms, // final Map<FolderType, Folder> folders, // final Set<AuctionFile> files) { // // this.id = id; // this.region = region; // this.realms = Optional.ofNullable(realms).map(HashSet::new).orElse(new HashSet<>()); // this.folders = Optional.ofNullable(folders).map(HashMap::new).orElse(new HashMap<>()); // this.files = Optional.ofNullable(files).map(HashSet::new).orElse(new HashSet<>()); // } // // public void addRealm(final Realm realm) { // realm.setConnectedRealm(this); // realms.add(realm); // } // // public ConnectedRealm create() { // realms.stream() // .filter(realm -> realm.getConnectedRealm() == null) // .forEach(realm -> realm.setConnectedRealm(this)); // // persist(); // return this; // } // // public ConnectedRealm update(final ConnectedRealm connectedRealm) { // return ConnectedRealmMapper.INSTANCE.toEntity(this, connectedRealm); // } // } // // Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Folder.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "connectedRealm") // // @Entity // public class Folder implements Serializable { // @EmbeddedId // private FolderPK id; // private String path; // // @ManyToOne // @MapsId("connectedRealmId") // private ConnectedRealm connectedRealm; // // @Deprecated // public Folder(final String id, final FolderType folderType, final String path) { // this.id = new FolderPK(id, folderType); // this.path = path; // } // // @Builder // public Folder(final ConnectedRealm connectedRealm, final FolderType folderType, final String path) { // this.id = new FolderPK(connectedRealm.getId(), folderType); // this.connectedRealm = connectedRealm; // this.path = path; // } // // @Data // @NoArgsConstructor // @AllArgsConstructor // @Embeddable // public static class FolderPK implements Serializable { // @Basic // private String connectedRealmId; // @Enumerated(EnumType.STRING) // private FolderType folderType; // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/prepare/FolderCreationBatchlet.java import com.radcortez.wow.auctions.entity.ConnectedRealm; import com.radcortez.wow.auctions.entity.Folder; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import org.apache.commons.io.FileUtils; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.batch.api.AbstractBatchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.io.File; import java.io.IOException; package com.radcortez.wow.auctions.batch.prepare; /** * @author Roberto Cortez */ @Dependent @Named @Log public class FolderCreationBatchlet extends AbstractBatchlet { @Inject @ConfigProperty(name = "wow.batch.home") String batchHome; @Override @Transactional public String process() { log.info(FolderCreationBatchlet.class.getSimpleName() + " running"); ConnectedRealm.<ConnectedRealm>listAll().forEach(this::verifyAndCreateFolder); log.info(FolderCreationBatchlet.class.getSimpleName() + " completed"); return BatchStatus.COMPLETED.toString(); } private void verifyAndCreateFolder(final ConnectedRealm connectedRealm) { for (FolderType folderType : FolderType.values()) { File folder = FileUtils.getFile(batchHome, connectedRealm.getRegion().toString(), connectedRealm.getId(), folderType.toString()); if (!folder.exists()) { try { log.info("Creating folder " + folder); FileUtils.forceMkdir(folder); } catch (IOException e) { // Ignore continue; } } if (!connectedRealm.getFolders().containsKey(folderType)) {
connectedRealm.getFolders().put(folderType, new Folder(connectedRealm, folderType, folder.getPath()));
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/move/MoveFileBatchlet.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // }
import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import org.apache.commons.io.FileExistsException; import org.eclipse.microprofile.config.Config; import javax.batch.api.Batchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import java.io.File; import static org.apache.commons.io.FileUtils.moveFileToDirectory;
package com.radcortez.wow.auctions.batch.process.move; /** * @author Roberto Cortez */ @Dependent @Named @Log
// Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/AbstractAuctionFileProcess.java // public abstract class AbstractAuctionFileProcess { // @Inject // JobContext jobContext; // // @PostConstruct // void init() { // final String connectedRealmId = jobContext.getProperties().getProperty("connectedRealmId"); // // if (jobContext.getTransientUserData() == null) { // jobContext.setTransientUserData(new AuctionFileProcessContext(connectedRealmId)); // } // } // // public AuctionFileProcessContext getContext() { // return (AuctionFileProcessContext) jobContext.getTransientUserData(); // } // // @RequiredArgsConstructor // public static class AuctionFileProcessContext { // private final String connectedRealmId; // // private ConnectedRealm connectedRealm; // private AuctionFile auctionFile; // // public ConnectedRealm getConnectedRealm() { // if (connectedRealm == null) { // connectedRealm = ConnectedRealm.findById(connectedRealmId); // } // return connectedRealm; // } // // public AuctionFile getAuctionFile() { // if (auctionFile == null) { // throw new IllegalStateException(); // } // return auctionFile; // } // // public void setAuctionFile(AuctionFile auctionFile) { // this.auctionFile = auctionFile; // } // // public File getAuctionFile(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath() + "/" + getAuctionFile().getFileName()); // } // // public File getFolder(FolderType folderType) { // return getFile(connectedRealm.getFolders().get(folderType).getPath()); // } // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/move/MoveFileBatchlet.java import com.radcortez.wow.auctions.batch.process.AbstractAuctionFileProcess; import com.radcortez.wow.auctions.entity.FolderType; import lombok.extern.java.Log; import org.apache.commons.io.FileExistsException; import org.eclipse.microprofile.config.Config; import javax.batch.api.Batchlet; import javax.batch.runtime.BatchStatus; import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import java.io.File; import static org.apache.commons.io.FileUtils.moveFileToDirectory; package com.radcortez.wow.auctions.batch.process.move; /** * @author Roberto Cortez */ @Dependent @Named @Log
public class MoveFileBatchlet extends AbstractAuctionFileProcess implements Batchlet {
radcortez/wow-auctions
batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemWriter.java
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // }
import com.radcortez.wow.auctions.entity.Auction; import javax.batch.api.chunk.AbstractItemWriter; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.util.List;
package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named public class AuctionDataItemWriter extends AbstractItemWriter { @Override public void writeItems(List<Object> items) {
// Path: batch/src/main/java/com/radcortez/wow/auctions/entity/Auction.java // @NoArgsConstructor // @Data // @EqualsAndHashCode(of = "id", callSuper = false) // @ToString(exclude = "auctionFile") // // @Entity // public class Auction extends PanacheEntityBase implements Serializable { // @Id // private Long id; // @Id // @ManyToOne(optional = false) // private AuctionFile auctionFile; // // private Integer itemId; // private Long bid; // private Long buyout; // private Integer quantity; // // public Auction create() { // persist(); // return this; // } // // public static List<Auction> findByConnectedRealm(final ConnectedRealm connectedRealm) { // return list("auctionFile.connectedRealm.id", connectedRealm.getId()); // } // } // Path: batch/src/main/java/com/radcortez/wow/auctions/batch/process/data/AuctionDataItemWriter.java import com.radcortez.wow.auctions.entity.Auction; import javax.batch.api.chunk.AbstractItemWriter; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.util.List; package com.radcortez.wow.auctions.batch.process.data; /** * @author Roberto Cortez */ @Dependent @Named public class AuctionDataItemWriter extends AbstractItemWriter { @Override public void writeItems(List<Object> items) {
items.stream().map(Auction.class::cast).forEach(Auction::create);
tminglei/form-binder-java
src/main/java/com/github/tminglei/bind/spi/ExtraConstraint.java
// Path: src/main/java/com/github/tminglei/bind/Messages.java // @FunctionalInterface // public interface Messages { // String get(String key); // }
import java.util.List; import com.github.tminglei.bind.Messages;
package com.github.tminglei.bind.spi; @FunctionalInterface public interface ExtraConstraint<T> extends Metable<ExtensionMeta> {
// Path: src/main/java/com/github/tminglei/bind/Messages.java // @FunctionalInterface // public interface Messages { // String get(String key); // } // Path: src/main/java/com/github/tminglei/bind/spi/ExtraConstraint.java import java.util.List; import com.github.tminglei.bind.Messages; package com.github.tminglei.bind.spi; @FunctionalInterface public interface ExtraConstraint<T> extends Metable<ExtensionMeta> {
List<String> apply(String label, T vObj, Messages messages);
tminglei/form-binder-java
src/main/java/com/github/tminglei/bind/spi/PreProcessor.java
// Path: src/main/java/com/github/tminglei/bind/Options.java // public class Options { // public static final Options EMPTY = new Options(); // // private Boolean eagerCheck; // private Boolean skipUntouched; // private TouchedChecker touchedChecker; // // internal state, only applied to current mapping // private InputMode inputMode; // private String label = null; // private boolean ignoreConstraints = false; // private List<Constraint> constraints = Collections.emptyList(); // private List<ExtraConstraint<?>> extraConstraints = Collections.emptyList(); // private List<PreProcessor> processors = Collections.emptyList(); // // used to associate/hold application specific object // private Object attachment; // // public Options() {} // public Options(Boolean eagerCheck, Boolean skipUntouched, TouchedChecker touchedChecker) { // this.eagerCheck = eagerCheck; // this.skipUntouched = skipUntouched; // this.touchedChecker = touchedChecker; // } // // public Options merge(Options other) { // Options clone = this.clone(); // clone.eagerCheck = eagerCheck != null ? eagerCheck : other.eagerCheck; // clone.skipUntouched = skipUntouched != null ? skipUntouched : other.skipUntouched; // clone.touchedChecker = touchedChecker != null ? touchedChecker : other.touchedChecker; // return clone; // } // // /// // // /** // * whether check errors as more as possible // * @return the value optional // */ // public Optional<Boolean> eagerCheck() { // return Optional.ofNullable(this.eagerCheck); // } // public Options eagerCheck(Boolean eagerCheck) { // Options clone = this.clone(); // clone.eagerCheck = eagerCheck; // return clone; // } // // /** // * whether to skip checking untouched empty field/values // * @return the value optional // */ // public Optional<Boolean> skipUntouched() { // return Optional.ofNullable(this.skipUntouched); // } // public Options skipUntouched(Boolean ignoreEmpty) { // Options clone = this.clone(); // clone.skipUntouched = ignoreEmpty; // return clone; // } // // /** // * used to check whether a field was touched by user // * @return the touched checker // */ // public TouchedChecker touchedChecker() { // return this.touchedChecker; // } // public Options touchedChecker(TouchedChecker touched) { // Options clone = this.clone(); // clone.touchedChecker = touched; // return clone; // } // // //-- internal options // InputMode _inputMode() { // return this.inputMode; // } // Options _inputMode(InputMode inputMode) { // Options clone = this.clone(); // clone.inputMode = inputMode; // return clone; // } // // Optional<String> _label() { // return Optional.ofNullable(this.label); // } // Options _label(String label) { // Options clone = this.clone(); // clone.label = label; // return clone; // } // // boolean _ignoreConstraints() { // return this.ignoreConstraints; // } // Options _ignoreConstraints(boolean ignore) { // Options clone = this.clone(); // clone.ignoreConstraints = ignore; // return clone; // } // // List<Constraint> _constraints() { // return this.constraints; // } // Options _constraints(List<Constraint> constraints) { // Options clone = this.clone(); // clone.constraints = unmodifiableList(constraints); // return clone; // } // Options append_constraints(List<Constraint> constraints) { // Options clone = this.clone(); // clone.constraints = unmodifiableList(mergeList(clone.constraints, constraints)); // return clone; // } // Options prepend_constraints(List<Constraint> constraints) { // Options clone = this.clone(); // clone.constraints = unmodifiableList(mergeList(constraints, clone.constraints)); // return clone; // } // // List<PreProcessor> _processors() { // return this.processors; // } // Options _processors(List<PreProcessor> processors) { // Options clone = this.clone(); // clone.processors = unmodifiableList(processors); // return clone; // } // Options append_processors(List<PreProcessor> processors) { // Options clone = this.clone(); // clone.processors = unmodifiableList(mergeList(clone.processors, processors)); // return clone; // } // Options prepend_processors(List<PreProcessor> processors) { // Options clone = this.clone(); // clone.processors = unmodifiableList(mergeList(processors, clone.processors)); // return clone; // } // // <T> List<ExtraConstraint<T>> _extraConstraints() { // return this.extraConstraints.stream().map(c -> (ExtraConstraint<T>) c).collect(Collectors.toList()); // } // Options _extraConstraints(List<ExtraConstraint<?>> extraConstraints) { // Options clone = this.clone(); // clone.extraConstraints = unmodifiableList(extraConstraints); // return clone; // } // Options append_extraConstraints(List<ExtraConstraint<?>> extraConstraints) { // Options clone = this.clone(); // clone.extraConstraints = unmodifiableList(mergeList(clone.extraConstraints, extraConstraints)); // return clone; // } // // /// // Object _attachment() { // return this.attachment; // } // Options _attachment(Object attachment) { // Options clone = this.clone(); // clone.attachment = attachment; // return clone; // } // // ///////////////////////////////////////////////////////////////////////////////////// // // protected Options clone() { // Options clone = new Options(this.eagerCheck, this.skipUntouched, this.touchedChecker); // clone.inputMode = this.inputMode; // clone.label = this.label; // clone.ignoreConstraints = this.ignoreConstraints; // clone.constraints = this.constraints; // clone.extraConstraints = this.extraConstraints; // clone.processors = this.processors; // clone.attachment = this.attachment; // return clone; // } // }
import java.util.Map; import com.github.tminglei.bind.Options;
package com.github.tminglei.bind.spi; @FunctionalInterface public interface PreProcessor extends Metable<ExtensionMeta> {
// Path: src/main/java/com/github/tminglei/bind/Options.java // public class Options { // public static final Options EMPTY = new Options(); // // private Boolean eagerCheck; // private Boolean skipUntouched; // private TouchedChecker touchedChecker; // // internal state, only applied to current mapping // private InputMode inputMode; // private String label = null; // private boolean ignoreConstraints = false; // private List<Constraint> constraints = Collections.emptyList(); // private List<ExtraConstraint<?>> extraConstraints = Collections.emptyList(); // private List<PreProcessor> processors = Collections.emptyList(); // // used to associate/hold application specific object // private Object attachment; // // public Options() {} // public Options(Boolean eagerCheck, Boolean skipUntouched, TouchedChecker touchedChecker) { // this.eagerCheck = eagerCheck; // this.skipUntouched = skipUntouched; // this.touchedChecker = touchedChecker; // } // // public Options merge(Options other) { // Options clone = this.clone(); // clone.eagerCheck = eagerCheck != null ? eagerCheck : other.eagerCheck; // clone.skipUntouched = skipUntouched != null ? skipUntouched : other.skipUntouched; // clone.touchedChecker = touchedChecker != null ? touchedChecker : other.touchedChecker; // return clone; // } // // /// // // /** // * whether check errors as more as possible // * @return the value optional // */ // public Optional<Boolean> eagerCheck() { // return Optional.ofNullable(this.eagerCheck); // } // public Options eagerCheck(Boolean eagerCheck) { // Options clone = this.clone(); // clone.eagerCheck = eagerCheck; // return clone; // } // // /** // * whether to skip checking untouched empty field/values // * @return the value optional // */ // public Optional<Boolean> skipUntouched() { // return Optional.ofNullable(this.skipUntouched); // } // public Options skipUntouched(Boolean ignoreEmpty) { // Options clone = this.clone(); // clone.skipUntouched = ignoreEmpty; // return clone; // } // // /** // * used to check whether a field was touched by user // * @return the touched checker // */ // public TouchedChecker touchedChecker() { // return this.touchedChecker; // } // public Options touchedChecker(TouchedChecker touched) { // Options clone = this.clone(); // clone.touchedChecker = touched; // return clone; // } // // //-- internal options // InputMode _inputMode() { // return this.inputMode; // } // Options _inputMode(InputMode inputMode) { // Options clone = this.clone(); // clone.inputMode = inputMode; // return clone; // } // // Optional<String> _label() { // return Optional.ofNullable(this.label); // } // Options _label(String label) { // Options clone = this.clone(); // clone.label = label; // return clone; // } // // boolean _ignoreConstraints() { // return this.ignoreConstraints; // } // Options _ignoreConstraints(boolean ignore) { // Options clone = this.clone(); // clone.ignoreConstraints = ignore; // return clone; // } // // List<Constraint> _constraints() { // return this.constraints; // } // Options _constraints(List<Constraint> constraints) { // Options clone = this.clone(); // clone.constraints = unmodifiableList(constraints); // return clone; // } // Options append_constraints(List<Constraint> constraints) { // Options clone = this.clone(); // clone.constraints = unmodifiableList(mergeList(clone.constraints, constraints)); // return clone; // } // Options prepend_constraints(List<Constraint> constraints) { // Options clone = this.clone(); // clone.constraints = unmodifiableList(mergeList(constraints, clone.constraints)); // return clone; // } // // List<PreProcessor> _processors() { // return this.processors; // } // Options _processors(List<PreProcessor> processors) { // Options clone = this.clone(); // clone.processors = unmodifiableList(processors); // return clone; // } // Options append_processors(List<PreProcessor> processors) { // Options clone = this.clone(); // clone.processors = unmodifiableList(mergeList(clone.processors, processors)); // return clone; // } // Options prepend_processors(List<PreProcessor> processors) { // Options clone = this.clone(); // clone.processors = unmodifiableList(mergeList(processors, clone.processors)); // return clone; // } // // <T> List<ExtraConstraint<T>> _extraConstraints() { // return this.extraConstraints.stream().map(c -> (ExtraConstraint<T>) c).collect(Collectors.toList()); // } // Options _extraConstraints(List<ExtraConstraint<?>> extraConstraints) { // Options clone = this.clone(); // clone.extraConstraints = unmodifiableList(extraConstraints); // return clone; // } // Options append_extraConstraints(List<ExtraConstraint<?>> extraConstraints) { // Options clone = this.clone(); // clone.extraConstraints = unmodifiableList(mergeList(clone.extraConstraints, extraConstraints)); // return clone; // } // // /// // Object _attachment() { // return this.attachment; // } // Options _attachment(Object attachment) { // Options clone = this.clone(); // clone.attachment = attachment; // return clone; // } // // ///////////////////////////////////////////////////////////////////////////////////// // // protected Options clone() { // Options clone = new Options(this.eagerCheck, this.skipUntouched, this.touchedChecker); // clone.inputMode = this.inputMode; // clone.label = this.label; // clone.ignoreConstraints = this.ignoreConstraints; // clone.constraints = this.constraints; // clone.extraConstraints = this.extraConstraints; // clone.processors = this.processors; // clone.attachment = this.attachment; // return clone; // } // } // Path: src/main/java/com/github/tminglei/bind/spi/PreProcessor.java import java.util.Map; import com.github.tminglei.bind.Options; package com.github.tminglei.bind.spi; @FunctionalInterface public interface PreProcessor extends Metable<ExtensionMeta> {
Map<String, String> apply(String prefix, Map<String, String> data, Options options);
tminglei/form-binder-java
src/main/java/com/github/tminglei/bind/spi/ExtensionMeta.java
// Path: src/main/java/com/github/tminglei/bind/FrameworkUtils.java // public static <T> List<T> unmodifiableList(List<T> list) { // return list == null ? Collections.emptyList() : Collections.unmodifiableList(list); // }
import java.util.List; import static com.github.tminglei.bind.FrameworkUtils.unmodifiableList;
package com.github.tminglei.bind.spi; /** * Created by tminglei on 2/23/16. */ public class ExtensionMeta { public final String name; public final String desc; public final List<?> params; public ExtensionMeta(String name, String desc, List<?> params) { this.name = name; this.desc = desc;
// Path: src/main/java/com/github/tminglei/bind/FrameworkUtils.java // public static <T> List<T> unmodifiableList(List<T> list) { // return list == null ? Collections.emptyList() : Collections.unmodifiableList(list); // } // Path: src/main/java/com/github/tminglei/bind/spi/ExtensionMeta.java import java.util.List; import static com.github.tminglei.bind.FrameworkUtils.unmodifiableList; package com.github.tminglei.bind.spi; /** * Created by tminglei on 2/23/16. */ public class ExtensionMeta { public final String name; public final String desc; public final List<?> params; public ExtensionMeta(String name, String desc, List<?> params) { this.name = name; this.desc = desc;
this.params = unmodifiableList(params);
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/bundle/TenacityBundleBuilder.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityContainerExceptionMapper.java // public class TenacityContainerExceptionMapper implements ExceptionMapper<ContainerException> { // private final int statusCode; // // public TenacityContainerExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityContainerExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // @Override // public Response toResponse(ContainerException exception) { // if (TenacityExceptionMapper.isTenacityException(exception.getCause())) { // return Response.status(statusCode).build(); // } else { // return Response.serverError().build(); // } // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityContainerExceptionMapper other = (TenacityContainerExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityExceptionMapper.java // public class TenacityExceptionMapper implements ExceptionMapper<HystrixRuntimeException> { // private static final Logger LOGGER = LoggerFactory.getLogger(TenacityExceptionMapper.class); // private final int statusCode; // // public TenacityExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // public static boolean isTenacityException(Throwable throwable) { // if (throwable != null && throwable instanceof HystrixRuntimeException) { // return isTenacityException((HystrixRuntimeException) throwable); // } // return false; // } // // public static boolean isTenacityException(HystrixRuntimeException exception) { // switch (exception.getFailureType()) { // case TIMEOUT: // case SHORTCIRCUIT: // case REJECTED_THREAD_EXECUTION: // case REJECTED_SEMAPHORE_EXECUTION: // case REJECTED_SEMAPHORE_FALLBACK: // return true; // case COMMAND_EXCEPTION: // //TODO: Remove this and set to false by default // //SocketTimeoutExceptions should be fixed by the application if they are being thrown within the context // //of a TenacityCommand // return exception.getCause() instanceof SocketTimeoutException; // default: // return false; // } // } // // @Override // public Response toResponse(HystrixRuntimeException exception) { // if (isTenacityException(exception)) { // LOGGER.debug("Unhandled HystrixRuntimeException", exception); // return Response.status(statusCode).build(); //TODO: Retry-After for 429 // } // // LOGGER.warn("HystrixRuntimeException is not mappable to a status code: {}", exception); // // return Response.serverError().build(); // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityExceptionMapper other = (TenacityExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // }
import com.codahale.metrics.health.HealthCheck; import com.google.common.collect.ImmutableList; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.yammer.tenacity.core.errors.TenacityContainerExceptionMapper; import com.yammer.tenacity.core.errors.TenacityExceptionMapper; import io.dropwizard.Configuration; import javax.ws.rs.ext.ExceptionMapper; import java.util.Optional;
package com.yammer.tenacity.core.bundle; public class TenacityBundleBuilder<T extends Configuration> { protected final ImmutableList.Builder<ExceptionMapper<? extends Throwable>> exceptionMapperBuilder = ImmutableList.builder(); protected Optional<HystrixCommandExecutionHook> executionHook = Optional.empty(); protected TenacityBundleConfigurationFactory<T> configurationFactory; protected final ImmutableList.Builder<HealthCheck> healthCheckBuilder = ImmutableList.builder(); protected boolean usingTenacityCircuitBreakerHealthCheck = false; protected boolean usingAdminPort = false; public static <T extends Configuration> TenacityBundleBuilder<T> newBuilder() { return new TenacityBundleBuilder<>(); } public <E extends Throwable> TenacityBundleBuilder<T> addExceptionMapper(ExceptionMapper<E> exceptionMapper) { exceptionMapperBuilder.add(exceptionMapper); return this; } public TenacityBundleBuilder<T> withCircuitBreakerHealthCheck() { usingTenacityCircuitBreakerHealthCheck = true; return this; } public TenacityBundleBuilder<T> usingAdminPort() { usingAdminPort = true; return this; } public TenacityBundleBuilder<T> mapAllHystrixRuntimeExceptionsTo(int statusCode) {
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityContainerExceptionMapper.java // public class TenacityContainerExceptionMapper implements ExceptionMapper<ContainerException> { // private final int statusCode; // // public TenacityContainerExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityContainerExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // @Override // public Response toResponse(ContainerException exception) { // if (TenacityExceptionMapper.isTenacityException(exception.getCause())) { // return Response.status(statusCode).build(); // } else { // return Response.serverError().build(); // } // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityContainerExceptionMapper other = (TenacityContainerExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityExceptionMapper.java // public class TenacityExceptionMapper implements ExceptionMapper<HystrixRuntimeException> { // private static final Logger LOGGER = LoggerFactory.getLogger(TenacityExceptionMapper.class); // private final int statusCode; // // public TenacityExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // public static boolean isTenacityException(Throwable throwable) { // if (throwable != null && throwable instanceof HystrixRuntimeException) { // return isTenacityException((HystrixRuntimeException) throwable); // } // return false; // } // // public static boolean isTenacityException(HystrixRuntimeException exception) { // switch (exception.getFailureType()) { // case TIMEOUT: // case SHORTCIRCUIT: // case REJECTED_THREAD_EXECUTION: // case REJECTED_SEMAPHORE_EXECUTION: // case REJECTED_SEMAPHORE_FALLBACK: // return true; // case COMMAND_EXCEPTION: // //TODO: Remove this and set to false by default // //SocketTimeoutExceptions should be fixed by the application if they are being thrown within the context // //of a TenacityCommand // return exception.getCause() instanceof SocketTimeoutException; // default: // return false; // } // } // // @Override // public Response toResponse(HystrixRuntimeException exception) { // if (isTenacityException(exception)) { // LOGGER.debug("Unhandled HystrixRuntimeException", exception); // return Response.status(statusCode).build(); //TODO: Retry-After for 429 // } // // LOGGER.warn("HystrixRuntimeException is not mappable to a status code: {}", exception); // // return Response.serverError().build(); // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityExceptionMapper other = (TenacityExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/bundle/TenacityBundleBuilder.java import com.codahale.metrics.health.HealthCheck; import com.google.common.collect.ImmutableList; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.yammer.tenacity.core.errors.TenacityContainerExceptionMapper; import com.yammer.tenacity.core.errors.TenacityExceptionMapper; import io.dropwizard.Configuration; import javax.ws.rs.ext.ExceptionMapper; import java.util.Optional; package com.yammer.tenacity.core.bundle; public class TenacityBundleBuilder<T extends Configuration> { protected final ImmutableList.Builder<ExceptionMapper<? extends Throwable>> exceptionMapperBuilder = ImmutableList.builder(); protected Optional<HystrixCommandExecutionHook> executionHook = Optional.empty(); protected TenacityBundleConfigurationFactory<T> configurationFactory; protected final ImmutableList.Builder<HealthCheck> healthCheckBuilder = ImmutableList.builder(); protected boolean usingTenacityCircuitBreakerHealthCheck = false; protected boolean usingAdminPort = false; public static <T extends Configuration> TenacityBundleBuilder<T> newBuilder() { return new TenacityBundleBuilder<>(); } public <E extends Throwable> TenacityBundleBuilder<T> addExceptionMapper(ExceptionMapper<E> exceptionMapper) { exceptionMapperBuilder.add(exceptionMapper); return this; } public TenacityBundleBuilder<T> withCircuitBreakerHealthCheck() { usingTenacityCircuitBreakerHealthCheck = true; return this; } public TenacityBundleBuilder<T> usingAdminPort() { usingAdminPort = true; return this; } public TenacityBundleBuilder<T> mapAllHystrixRuntimeExceptionsTo(int statusCode) {
exceptionMapperBuilder.add(new TenacityExceptionMapper(statusCode));
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/bundle/TenacityBundleBuilder.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityContainerExceptionMapper.java // public class TenacityContainerExceptionMapper implements ExceptionMapper<ContainerException> { // private final int statusCode; // // public TenacityContainerExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityContainerExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // @Override // public Response toResponse(ContainerException exception) { // if (TenacityExceptionMapper.isTenacityException(exception.getCause())) { // return Response.status(statusCode).build(); // } else { // return Response.serverError().build(); // } // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityContainerExceptionMapper other = (TenacityContainerExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityExceptionMapper.java // public class TenacityExceptionMapper implements ExceptionMapper<HystrixRuntimeException> { // private static final Logger LOGGER = LoggerFactory.getLogger(TenacityExceptionMapper.class); // private final int statusCode; // // public TenacityExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // public static boolean isTenacityException(Throwable throwable) { // if (throwable != null && throwable instanceof HystrixRuntimeException) { // return isTenacityException((HystrixRuntimeException) throwable); // } // return false; // } // // public static boolean isTenacityException(HystrixRuntimeException exception) { // switch (exception.getFailureType()) { // case TIMEOUT: // case SHORTCIRCUIT: // case REJECTED_THREAD_EXECUTION: // case REJECTED_SEMAPHORE_EXECUTION: // case REJECTED_SEMAPHORE_FALLBACK: // return true; // case COMMAND_EXCEPTION: // //TODO: Remove this and set to false by default // //SocketTimeoutExceptions should be fixed by the application if they are being thrown within the context // //of a TenacityCommand // return exception.getCause() instanceof SocketTimeoutException; // default: // return false; // } // } // // @Override // public Response toResponse(HystrixRuntimeException exception) { // if (isTenacityException(exception)) { // LOGGER.debug("Unhandled HystrixRuntimeException", exception); // return Response.status(statusCode).build(); //TODO: Retry-After for 429 // } // // LOGGER.warn("HystrixRuntimeException is not mappable to a status code: {}", exception); // // return Response.serverError().build(); // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityExceptionMapper other = (TenacityExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // }
import com.codahale.metrics.health.HealthCheck; import com.google.common.collect.ImmutableList; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.yammer.tenacity.core.errors.TenacityContainerExceptionMapper; import com.yammer.tenacity.core.errors.TenacityExceptionMapper; import io.dropwizard.Configuration; import javax.ws.rs.ext.ExceptionMapper; import java.util.Optional;
package com.yammer.tenacity.core.bundle; public class TenacityBundleBuilder<T extends Configuration> { protected final ImmutableList.Builder<ExceptionMapper<? extends Throwable>> exceptionMapperBuilder = ImmutableList.builder(); protected Optional<HystrixCommandExecutionHook> executionHook = Optional.empty(); protected TenacityBundleConfigurationFactory<T> configurationFactory; protected final ImmutableList.Builder<HealthCheck> healthCheckBuilder = ImmutableList.builder(); protected boolean usingTenacityCircuitBreakerHealthCheck = false; protected boolean usingAdminPort = false; public static <T extends Configuration> TenacityBundleBuilder<T> newBuilder() { return new TenacityBundleBuilder<>(); } public <E extends Throwable> TenacityBundleBuilder<T> addExceptionMapper(ExceptionMapper<E> exceptionMapper) { exceptionMapperBuilder.add(exceptionMapper); return this; } public TenacityBundleBuilder<T> withCircuitBreakerHealthCheck() { usingTenacityCircuitBreakerHealthCheck = true; return this; } public TenacityBundleBuilder<T> usingAdminPort() { usingAdminPort = true; return this; } public TenacityBundleBuilder<T> mapAllHystrixRuntimeExceptionsTo(int statusCode) { exceptionMapperBuilder.add(new TenacityExceptionMapper(statusCode));
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityContainerExceptionMapper.java // public class TenacityContainerExceptionMapper implements ExceptionMapper<ContainerException> { // private final int statusCode; // // public TenacityContainerExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityContainerExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // @Override // public Response toResponse(ContainerException exception) { // if (TenacityExceptionMapper.isTenacityException(exception.getCause())) { // return Response.status(statusCode).build(); // } else { // return Response.serverError().build(); // } // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityContainerExceptionMapper other = (TenacityContainerExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/errors/TenacityExceptionMapper.java // public class TenacityExceptionMapper implements ExceptionMapper<HystrixRuntimeException> { // private static final Logger LOGGER = LoggerFactory.getLogger(TenacityExceptionMapper.class); // private final int statusCode; // // public TenacityExceptionMapper() { // this(429); // Too Many Requests http://tools.ietf.org/html/rfc6585#section-4 // } // // public TenacityExceptionMapper(int statusCode) { // this.statusCode = statusCode; // } // // public int getStatusCode() { // return statusCode; // } // // public static boolean isTenacityException(Throwable throwable) { // if (throwable != null && throwable instanceof HystrixRuntimeException) { // return isTenacityException((HystrixRuntimeException) throwable); // } // return false; // } // // public static boolean isTenacityException(HystrixRuntimeException exception) { // switch (exception.getFailureType()) { // case TIMEOUT: // case SHORTCIRCUIT: // case REJECTED_THREAD_EXECUTION: // case REJECTED_SEMAPHORE_EXECUTION: // case REJECTED_SEMAPHORE_FALLBACK: // return true; // case COMMAND_EXCEPTION: // //TODO: Remove this and set to false by default // //SocketTimeoutExceptions should be fixed by the application if they are being thrown within the context // //of a TenacityCommand // return exception.getCause() instanceof SocketTimeoutException; // default: // return false; // } // } // // @Override // public Response toResponse(HystrixRuntimeException exception) { // if (isTenacityException(exception)) { // LOGGER.debug("Unhandled HystrixRuntimeException", exception); // return Response.status(statusCode).build(); //TODO: Retry-After for 429 // } // // LOGGER.warn("HystrixRuntimeException is not mappable to a status code: {}", exception); // // return Response.serverError().build(); // } // // @Override // public int hashCode() { // return Objects.hash(statusCode); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null || getClass() != obj.getClass()) { // return false; // } // final TenacityExceptionMapper other = (TenacityExceptionMapper) obj; // return Objects.equals(this.statusCode, other.statusCode); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/bundle/TenacityBundleBuilder.java import com.codahale.metrics.health.HealthCheck; import com.google.common.collect.ImmutableList; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.yammer.tenacity.core.errors.TenacityContainerExceptionMapper; import com.yammer.tenacity.core.errors.TenacityExceptionMapper; import io.dropwizard.Configuration; import javax.ws.rs.ext.ExceptionMapper; import java.util.Optional; package com.yammer.tenacity.core.bundle; public class TenacityBundleBuilder<T extends Configuration> { protected final ImmutableList.Builder<ExceptionMapper<? extends Throwable>> exceptionMapperBuilder = ImmutableList.builder(); protected Optional<HystrixCommandExecutionHook> executionHook = Optional.empty(); protected TenacityBundleConfigurationFactory<T> configurationFactory; protected final ImmutableList.Builder<HealthCheck> healthCheckBuilder = ImmutableList.builder(); protected boolean usingTenacityCircuitBreakerHealthCheck = false; protected boolean usingAdminPort = false; public static <T extends Configuration> TenacityBundleBuilder<T> newBuilder() { return new TenacityBundleBuilder<>(); } public <E extends Throwable> TenacityBundleBuilder<T> addExceptionMapper(ExceptionMapper<E> exceptionMapper) { exceptionMapperBuilder.add(exceptionMapper); return this; } public TenacityBundleBuilder<T> withCircuitBreakerHealthCheck() { usingTenacityCircuitBreakerHealthCheck = true; return this; } public TenacityBundleBuilder<T> usingAdminPort() { usingAdminPort = true; return this; } public TenacityBundleBuilder<T> mapAllHystrixRuntimeExceptionsTo(int statusCode) { exceptionMapperBuilder.add(new TenacityExceptionMapper(statusCode));
exceptionMapperBuilder.add(new TenacityContainerExceptionMapper(statusCode));
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/resources/TenacityConfigurationResource.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyStore.java // public class TenacityPropertyStore { // private TenacityPropertyStore() {} // // public static TenacityConfiguration getTenacityConfiguration(TenacityPropertyKey key) { // final HystrixCommandProperties commandProperties = TenacityCommand.getCommandProperties(key); // final HystrixThreadPoolProperties threadPoolProperties = TenacityCommand.getThreadpoolProperties(key); // return new TenacityConfiguration( // new ThreadPoolConfiguration( // threadPoolProperties.coreSize().get(), // threadPoolProperties.keepAliveTimeMinutes().get(), // threadPoolProperties.maxQueueSize().get(), // threadPoolProperties.queueSizeRejectionThreshold().get(), // threadPoolProperties.metricsRollingStatisticalWindowInMilliseconds().get(), // threadPoolProperties.metricsRollingStatisticalWindowBuckets().get()), // new CircuitBreakerConfiguration( // commandProperties.circuitBreakerRequestVolumeThreshold().get(), // commandProperties.circuitBreakerSleepWindowInMilliseconds().get(), // commandProperties.circuitBreakerErrorThresholdPercentage().get(), // commandProperties.metricsRollingStatisticalWindowInMilliseconds().get(), // commandProperties.metricsRollingStatisticalWindowBuckets().get()), // new SemaphoreConfiguration( // commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get(), // commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get()), // commandProperties.executionTimeoutInMilliseconds().get(), // commandProperties.executionIsolationStrategy().get()); // } // }
import com.codahale.metrics.annotation.Timed; import com.yammer.tenacity.core.properties.TenacityPropertyKeyFactory; import com.yammer.tenacity.core.properties.TenacityPropertyStore; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static com.google.common.base.Preconditions.checkNotNull;
package com.yammer.tenacity.core.resources; @Path(TenacityConfigurationResource.PATH) public class TenacityConfigurationResource { public static final String PATH = "/tenacity/configuration"; private final TenacityPropertyKeyFactory factory; public TenacityConfigurationResource(TenacityPropertyKeyFactory factory) { this.factory = checkNotNull(factory); } @GET @Timed @Produces(MediaType.APPLICATION_JSON) @Path("{key}") public Response get(@PathParam("key") String key) { try {
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyStore.java // public class TenacityPropertyStore { // private TenacityPropertyStore() {} // // public static TenacityConfiguration getTenacityConfiguration(TenacityPropertyKey key) { // final HystrixCommandProperties commandProperties = TenacityCommand.getCommandProperties(key); // final HystrixThreadPoolProperties threadPoolProperties = TenacityCommand.getThreadpoolProperties(key); // return new TenacityConfiguration( // new ThreadPoolConfiguration( // threadPoolProperties.coreSize().get(), // threadPoolProperties.keepAliveTimeMinutes().get(), // threadPoolProperties.maxQueueSize().get(), // threadPoolProperties.queueSizeRejectionThreshold().get(), // threadPoolProperties.metricsRollingStatisticalWindowInMilliseconds().get(), // threadPoolProperties.metricsRollingStatisticalWindowBuckets().get()), // new CircuitBreakerConfiguration( // commandProperties.circuitBreakerRequestVolumeThreshold().get(), // commandProperties.circuitBreakerSleepWindowInMilliseconds().get(), // commandProperties.circuitBreakerErrorThresholdPercentage().get(), // commandProperties.metricsRollingStatisticalWindowInMilliseconds().get(), // commandProperties.metricsRollingStatisticalWindowBuckets().get()), // new SemaphoreConfiguration( // commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get(), // commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get()), // commandProperties.executionTimeoutInMilliseconds().get(), // commandProperties.executionIsolationStrategy().get()); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/resources/TenacityConfigurationResource.java import com.codahale.metrics.annotation.Timed; import com.yammer.tenacity.core.properties.TenacityPropertyKeyFactory; import com.yammer.tenacity.core.properties.TenacityPropertyStore; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static com.google.common.base.Preconditions.checkNotNull; package com.yammer.tenacity.core.resources; @Path(TenacityConfigurationResource.PATH) public class TenacityConfigurationResource { public static final String PATH = "/tenacity/configuration"; private final TenacityPropertyKeyFactory factory; public TenacityConfigurationResource(TenacityPropertyKeyFactory factory) { this.factory = checkNotNull(factory); } @GET @Timed @Produces(MediaType.APPLICATION_JSON) @Path("{key}") public Response get(@PathParam("key") String key) { try {
return Response.ok(TenacityPropertyStore.getTenacityConfiguration(factory.from(key))).build();
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/servlets/TenacityCircuitBreakersServlet.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/resources/TenacityCircuitBreakersResource.java // @Path(TenacityCircuitBreakersResource.PATH) // public class TenacityCircuitBreakersResource { // private static final Logger LOGGER = LoggerFactory.getLogger(TenacityCircuitBreakersResource.class); // public static final String PATH = "/tenacity/circuitbreakers"; // private final Collection<TenacityPropertyKey> keys; // private final TenacityPropertyKeyFactory keyFactory; // // public TenacityCircuitBreakersResource(Collection<TenacityPropertyKey> keys, // TenacityPropertyKeyFactory keyFactory) { // this.keys = keys; // this.keyFactory = keyFactory; // } // // @GET // @Timed // @Produces(MediaType.APPLICATION_JSON) // public Collection<CircuitBreaker> circuitBreakers() { // return CircuitBreakers.all(keys); // } // // @GET // @Timed // @Path("{key}") // @Produces(MediaType.APPLICATION_JSON) // public Response getCircuitBreaker(@PathParam("key") String key ) { // try { // final Optional<CircuitBreaker> circuitBreaker = CircuitBreakers.find(keys, keyFactory.from(key)); // if (circuitBreaker.isPresent()) { // return Response.ok(circuitBreaker.get()).build(); // } // } catch (NoSuchElementException err) { // LOGGER.warn("Could not find TenacityPropertyKey {}", key, err); // } // return Response.status(Response.Status.NOT_FOUND).build(); // } // // @PUT // @Timed // @Path("{key}") // @Produces(MediaType.APPLICATION_JSON) // public Response modifyCircuitBreaker(@PathParam("key") String key, // String body) { // try { // final TenacityPropertyKey foundKey = keyFactory.from(key).validate(keys); // final CircuitBreaker.State state = CircuitBreaker.State.valueOf(body.toUpperCase()); // switch (state) { // case FORCED_CLOSED: // TenacityPropertyRegister.registerCircuitForceReset(foundKey); // TenacityPropertyRegister.registerCircuitForceClosed(foundKey); // break; // case FORCED_OPEN: // TenacityPropertyRegister.registerCircuitForceReset(foundKey); // TenacityPropertyRegister.registerCircuitForceOpen(foundKey); // break; // case FORCED_RESET: // TenacityPropertyRegister.registerCircuitForceReset(foundKey); // break; // default: // throw new IllegalArgumentException("You cannot modify a circuit breaker with the state: " + state); // } // final Optional<CircuitBreaker> circuitBreaker = CircuitBreaker.usingHystrix(foundKey); // if (circuitBreaker.isPresent()) { // return Response.ok(circuitBreaker.get()).build(); // } // } catch (NoSuchElementException err) { // LOGGER.warn("Could not find TenacityPropertyKey {}", key, err); // } // return Response.status(Response.Status.NOT_FOUND).build(); // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.CharStreams; import com.yammer.tenacity.core.resources.TenacityCircuitBreakersResource; import org.eclipse.jetty.server.handler.gzip.GzipHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream;
package com.yammer.tenacity.core.servlets; public class TenacityCircuitBreakersServlet extends TenacityServlet { private static final long serialVersionUID = 0;
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/resources/TenacityCircuitBreakersResource.java // @Path(TenacityCircuitBreakersResource.PATH) // public class TenacityCircuitBreakersResource { // private static final Logger LOGGER = LoggerFactory.getLogger(TenacityCircuitBreakersResource.class); // public static final String PATH = "/tenacity/circuitbreakers"; // private final Collection<TenacityPropertyKey> keys; // private final TenacityPropertyKeyFactory keyFactory; // // public TenacityCircuitBreakersResource(Collection<TenacityPropertyKey> keys, // TenacityPropertyKeyFactory keyFactory) { // this.keys = keys; // this.keyFactory = keyFactory; // } // // @GET // @Timed // @Produces(MediaType.APPLICATION_JSON) // public Collection<CircuitBreaker> circuitBreakers() { // return CircuitBreakers.all(keys); // } // // @GET // @Timed // @Path("{key}") // @Produces(MediaType.APPLICATION_JSON) // public Response getCircuitBreaker(@PathParam("key") String key ) { // try { // final Optional<CircuitBreaker> circuitBreaker = CircuitBreakers.find(keys, keyFactory.from(key)); // if (circuitBreaker.isPresent()) { // return Response.ok(circuitBreaker.get()).build(); // } // } catch (NoSuchElementException err) { // LOGGER.warn("Could not find TenacityPropertyKey {}", key, err); // } // return Response.status(Response.Status.NOT_FOUND).build(); // } // // @PUT // @Timed // @Path("{key}") // @Produces(MediaType.APPLICATION_JSON) // public Response modifyCircuitBreaker(@PathParam("key") String key, // String body) { // try { // final TenacityPropertyKey foundKey = keyFactory.from(key).validate(keys); // final CircuitBreaker.State state = CircuitBreaker.State.valueOf(body.toUpperCase()); // switch (state) { // case FORCED_CLOSED: // TenacityPropertyRegister.registerCircuitForceReset(foundKey); // TenacityPropertyRegister.registerCircuitForceClosed(foundKey); // break; // case FORCED_OPEN: // TenacityPropertyRegister.registerCircuitForceReset(foundKey); // TenacityPropertyRegister.registerCircuitForceOpen(foundKey); // break; // case FORCED_RESET: // TenacityPropertyRegister.registerCircuitForceReset(foundKey); // break; // default: // throw new IllegalArgumentException("You cannot modify a circuit breaker with the state: " + state); // } // final Optional<CircuitBreaker> circuitBreaker = CircuitBreaker.usingHystrix(foundKey); // if (circuitBreaker.isPresent()) { // return Response.ok(circuitBreaker.get()).build(); // } // } catch (NoSuchElementException err) { // LOGGER.warn("Could not find TenacityPropertyKey {}", key, err); // } // return Response.status(Response.Status.NOT_FOUND).build(); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/servlets/TenacityCircuitBreakersServlet.java import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.CharStreams; import com.yammer.tenacity.core.resources.TenacityCircuitBreakersResource; import org.eclipse.jetty.server.handler.gzip.GzipHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.HttpHeaders; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; package com.yammer.tenacity.core.servlets; public class TenacityCircuitBreakersServlet extends TenacityServlet { private static final long serialVersionUID = 0;
private transient final TenacityCircuitBreakersResource circuitBreakersResource;
yammer/tenacity
tenacity-client/src/test/java/com/yammer/tenacity/client/tests/TenacityResourcesServletTest.java
// Path: tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java // public class TenacityClientBuilder { // protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); // protected final Environment environment; // protected final TenacityPropertyKey tenacityPropertyKey; // // public TenacityClientBuilder(Environment environment, // TenacityPropertyKey tenacityPropertyKey) { // this.environment = environment; // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityClientBuilder using(JerseyClientConfiguration jerseyConfiguration) { // this.jerseyConfiguration = jerseyConfiguration; // return this; // } // // public TenacityClient build() { // final Client client = new JerseyClientBuilder(environment) // .using(jerseyConfiguration) // .build("tenacity-" + tenacityPropertyKey); // return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder // .builder(tenacityPropertyKey) // .build(client)); // } // }
import com.google.common.io.Resources; import com.yammer.tenacity.client.TenacityClientBuilder; import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.testing.junit.DropwizardAppRule; import org.junit.BeforeClass; import org.junit.ClassRule; import java.net.URI;
package com.yammer.tenacity.client.tests; public class TenacityResourcesServletTest extends TenacityResources { @ClassRule public static DropwizardAppRule<Configuration> APP_RULE = new DropwizardAppRule<>(TenacityServletAdminService.class, Resources.getResource("tenacityPropertyKeyServletService.yml").getPath()); @BeforeClass public static void initialization() {
// Path: tenacity-client/src/main/java/com/yammer/tenacity/client/TenacityClientBuilder.java // public class TenacityClientBuilder { // protected JerseyClientConfiguration jerseyConfiguration = new JerseyClientConfiguration(); // protected final Environment environment; // protected final TenacityPropertyKey tenacityPropertyKey; // // public TenacityClientBuilder(Environment environment, // TenacityPropertyKey tenacityPropertyKey) { // this.environment = environment; // this.tenacityPropertyKey = tenacityPropertyKey; // } // // public TenacityClientBuilder using(JerseyClientConfiguration jerseyConfiguration) { // this.jerseyConfiguration = jerseyConfiguration; // return this; // } // // public TenacityClient build() { // final Client client = new JerseyClientBuilder(environment) // .using(jerseyConfiguration) // .build("tenacity-" + tenacityPropertyKey); // return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder // .builder(tenacityPropertyKey) // .build(client)); // } // } // Path: tenacity-client/src/test/java/com/yammer/tenacity/client/tests/TenacityResourcesServletTest.java import com.google.common.io.Resources; import com.yammer.tenacity.client.TenacityClientBuilder; import io.dropwizard.Configuration; import io.dropwizard.client.JerseyClientBuilder; import io.dropwizard.testing.junit.DropwizardAppRule; import org.junit.BeforeClass; import org.junit.ClassRule; import java.net.URI; package com.yammer.tenacity.client.tests; public class TenacityResourcesServletTest extends TenacityResources { @ClassRule public static DropwizardAppRule<Configuration> APP_RULE = new DropwizardAppRule<>(TenacityServletAdminService.class, Resources.getResource("tenacityPropertyKeyServletService.yml").getPath()); @BeforeClass public static void initialization() {
CLIENT = new TenacityClientBuilder(APP_RULE.getEnvironment(), ServletKeys.KEY_ONE)
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityPropertyKeyResourceTest.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // }
import com.google.common.collect.ImmutableList; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import com.yammer.tenacity.core.resources.TenacityPropertyKeysResource; import com.yammer.tenacity.testing.TenacityTestRule; import io.dropwizard.testing.junit.ResourceTestRule; import org.junit.Rule; import org.junit.Test; import javax.ws.rs.core.GenericType; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat;
package com.yammer.tenacity.tests; public class TenacityPropertyKeyResourceTest { public static final String PROPERTY_KEY_URI = "/tenacity/propertykeys";
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityPropertyKeyResourceTest.java import com.google.common.collect.ImmutableList; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import com.yammer.tenacity.core.resources.TenacityPropertyKeysResource; import com.yammer.tenacity.testing.TenacityTestRule; import io.dropwizard.testing.junit.ResourceTestRule; import org.junit.Rule; import org.junit.Test; import javax.ws.rs.core.GenericType; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; package com.yammer.tenacity.tests; public class TenacityPropertyKeyResourceTest { public static final String PROPERTY_KEY_URI = "/tenacity/propertykeys";
private final ImmutableList<TenacityPropertyKey> keys = ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXAMPLE, DependencyKey.SLEEP);
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityPropertyKeyResourceTest.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // }
import com.google.common.collect.ImmutableList; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import com.yammer.tenacity.core.resources.TenacityPropertyKeysResource; import com.yammer.tenacity.testing.TenacityTestRule; import io.dropwizard.testing.junit.ResourceTestRule; import org.junit.Rule; import org.junit.Test; import javax.ws.rs.core.GenericType; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat;
package com.yammer.tenacity.tests; public class TenacityPropertyKeyResourceTest { public static final String PROPERTY_KEY_URI = "/tenacity/propertykeys"; private final ImmutableList<TenacityPropertyKey> keys = ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXAMPLE, DependencyKey.SLEEP); @Rule
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityPropertyKeyResourceTest.java import com.google.common.collect.ImmutableList; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import com.yammer.tenacity.core.resources.TenacityPropertyKeysResource; import com.yammer.tenacity.testing.TenacityTestRule; import io.dropwizard.testing.junit.ResourceTestRule; import org.junit.Rule; import org.junit.Test; import javax.ws.rs.core.GenericType; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; package com.yammer.tenacity.tests; public class TenacityPropertyKeyResourceTest { public static final String PROPERTY_KEY_URI = "/tenacity/propertykeys"; private final ImmutableList<TenacityPropertyKey> keys = ImmutableList.<TenacityPropertyKey>of(DependencyKey.EXAMPLE, DependencyKey.SLEEP); @Rule
public final TenacityTestRule tenacityTestRule = new TenacityTestRule();
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/core/tests/TimeoutObservable.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityObservableCommand.java // public abstract class TenacityObservableCommand<R> extends HystrixObservableCommand<R> { // protected TenacityObservableCommand(TenacityPropertyKey tenacityPropertyKey) { // super(HystrixObservableCommand.Setter.withGroupKey(TenacityCommand.tenacityGroupKey()) // .andCommandKey(tenacityPropertyKey)); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> TenacityObservableCommand.Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new TenacityObservableCommand.Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<Observable<R>> run; // protected Supplier<Observable<R>> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<Observable<R>> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<Observable<R>> fun) { // fallback = fun; // return this; // } // // public TenacityObservableCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityObservableCommand<R>(key) { // @Override // protected Observable<R> construct() { // return run.get(); // } // }; // } else { // return new TenacityObservableCommand<R>(key) { // @Override // protected Observable<R> construct() { // return run.get(); // } // // @Override // protected Observable<R> resumeWithFallback() { // return fallback.get(); // } // }; // } // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract Observable<R> construct(); // } // // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/DependencyKey.java // public enum DependencyKey implements TenacityPropertyKey, TenacityPropertyKeyFactory { // EXAMPLE, OVERRIDE, SLEEP, THREAD_ISOLATION_TIMEOUT, NON_EXISTENT_HEALTHCHECK, EXISTENT_HEALTHCHECK, ANOTHER_EXISTENT_HEALTHCHECK, // TENACITY_AUTH_TIMEOUT, CLIENT_TIMEOUT, OBSERVABLE_TIMEOUT, GENERAL; // // @Override // public TenacityPropertyKey from(String value) { // return valueOf(value); // } // }
import com.yammer.tenacity.core.TenacityObservableCommand; import com.yammer.tenacity.tests.DependencyKey; import io.dropwizard.util.Duration; import rx.Observable; import rx.schedulers.Schedulers; import static org.junit.Assert.fail;
package com.yammer.tenacity.core.tests; public class TimeoutObservable extends TenacityObservableCommand<Boolean> { private final Duration sleepDuration; public TimeoutObservable(Duration sleepDuration) {
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityObservableCommand.java // public abstract class TenacityObservableCommand<R> extends HystrixObservableCommand<R> { // protected TenacityObservableCommand(TenacityPropertyKey tenacityPropertyKey) { // super(HystrixObservableCommand.Setter.withGroupKey(TenacityCommand.tenacityGroupKey()) // .andCommandKey(tenacityPropertyKey)); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> TenacityObservableCommand.Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new TenacityObservableCommand.Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<Observable<R>> run; // protected Supplier<Observable<R>> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<Observable<R>> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<Observable<R>> fun) { // fallback = fun; // return this; // } // // public TenacityObservableCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityObservableCommand<R>(key) { // @Override // protected Observable<R> construct() { // return run.get(); // } // }; // } else { // return new TenacityObservableCommand<R>(key) { // @Override // protected Observable<R> construct() { // return run.get(); // } // // @Override // protected Observable<R> resumeWithFallback() { // return fallback.get(); // } // }; // } // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract Observable<R> construct(); // } // // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/DependencyKey.java // public enum DependencyKey implements TenacityPropertyKey, TenacityPropertyKeyFactory { // EXAMPLE, OVERRIDE, SLEEP, THREAD_ISOLATION_TIMEOUT, NON_EXISTENT_HEALTHCHECK, EXISTENT_HEALTHCHECK, ANOTHER_EXISTENT_HEALTHCHECK, // TENACITY_AUTH_TIMEOUT, CLIENT_TIMEOUT, OBSERVABLE_TIMEOUT, GENERAL; // // @Override // public TenacityPropertyKey from(String value) { // return valueOf(value); // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/core/tests/TimeoutObservable.java import com.yammer.tenacity.core.TenacityObservableCommand; import com.yammer.tenacity.tests.DependencyKey; import io.dropwizard.util.Duration; import rx.Observable; import rx.schedulers.Schedulers; import static org.junit.Assert.fail; package com.yammer.tenacity.core.tests; public class TimeoutObservable extends TenacityObservableCommand<Boolean> { private final Duration sleepDuration; public TimeoutObservable(Duration sleepDuration) {
super(DependencyKey.OBSERVABLE_TIMEOUT);
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/logging/ExceptionLoggingCommandHookTest.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLogger.java // public abstract class ExceptionLogger<E extends Exception> { // // protected final Class<E> clazz; // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // /** // * Specify the class that this exception logger can handle // */ // protected ExceptionLogger() { // this.clazz = Generics.getTypeParameter(this.getClass(), Exception.class); // } // // /** // * Make sure you check that this ExceptionLogger can actually handle the type of exception // */ // public boolean canHandleException(Exception exception) { // return this.clazz.isInstance(exception); // } // // @SuppressWarnings("unchecked") // /** // * Actually log the exception // * @throws IllegalStateException it relieves an exception that it can't log // */ // public <T> void log(Exception exception, HystrixInvokableInfo<T> commandInstance) { // checkState(canHandleException(exception)); // // logException((E) exception, commandInstance); // } // // /** // * @param exception the exception that you should log // * @param commandInstance you get access to the command that failed, so you can specify what kind it was // */ // protected abstract <T> void logException(E exception, HystrixInvokableInfo<T> commandInstance); // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLoggingCommandHook.java // public class ExceptionLoggingCommandHook extends HystrixCommandExecutionHook { // // private final List<ExceptionLogger<? extends Exception>> exceptionLoggers; // // /** // * Empty constructor only sets the DefaultExceptionLogger, which will log every type of exception // */ // public ExceptionLoggingCommandHook() { // this(new DefaultExceptionLogger()); // } // // public ExceptionLoggingCommandHook(ExceptionLogger<? extends Exception> exceptionLogger) { // this(ImmutableList.of(exceptionLogger)); // } // // public ExceptionLoggingCommandHook(Iterable<ExceptionLogger<? extends Exception>> exceptionLoggers) { // this.exceptionLoggers = ImmutableList.copyOf(exceptionLoggers); // } // // @SuppressWarnings("unchecked") // @Override // public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception exception) { // for (ExceptionLogger<? extends Exception> logger: exceptionLoggers) { // if (logger.canHandleException(exception) && isHystrixInvokableInfo(commandInstance)) { // logger.log(exception, (HystrixInvokableInfo<T>)commandInstance); // return exception; // } // } // // return exception; // } // // private <T> boolean isHystrixInvokableInfo(HystrixInvokable<T> commandInstance) { // return commandInstance instanceof HystrixInvokableInfo; // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // }
import com.google.common.collect.ImmutableList; import com.netflix.hystrix.HystrixCommand; import com.yammer.tenacity.core.logging.ExceptionLogger; import com.yammer.tenacity.core.logging.ExceptionLoggingCommandHook; import com.yammer.tenacity.testing.TenacityTestRule; import com.yammer.tenacity.tests.TenacityFailingCommand; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*;
package com.yammer.tenacity.tests.logging; @RunWith(MockitoJUnitRunner.class) public class ExceptionLoggingCommandHookTest { @Rule
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLogger.java // public abstract class ExceptionLogger<E extends Exception> { // // protected final Class<E> clazz; // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // /** // * Specify the class that this exception logger can handle // */ // protected ExceptionLogger() { // this.clazz = Generics.getTypeParameter(this.getClass(), Exception.class); // } // // /** // * Make sure you check that this ExceptionLogger can actually handle the type of exception // */ // public boolean canHandleException(Exception exception) { // return this.clazz.isInstance(exception); // } // // @SuppressWarnings("unchecked") // /** // * Actually log the exception // * @throws IllegalStateException it relieves an exception that it can't log // */ // public <T> void log(Exception exception, HystrixInvokableInfo<T> commandInstance) { // checkState(canHandleException(exception)); // // logException((E) exception, commandInstance); // } // // /** // * @param exception the exception that you should log // * @param commandInstance you get access to the command that failed, so you can specify what kind it was // */ // protected abstract <T> void logException(E exception, HystrixInvokableInfo<T> commandInstance); // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLoggingCommandHook.java // public class ExceptionLoggingCommandHook extends HystrixCommandExecutionHook { // // private final List<ExceptionLogger<? extends Exception>> exceptionLoggers; // // /** // * Empty constructor only sets the DefaultExceptionLogger, which will log every type of exception // */ // public ExceptionLoggingCommandHook() { // this(new DefaultExceptionLogger()); // } // // public ExceptionLoggingCommandHook(ExceptionLogger<? extends Exception> exceptionLogger) { // this(ImmutableList.of(exceptionLogger)); // } // // public ExceptionLoggingCommandHook(Iterable<ExceptionLogger<? extends Exception>> exceptionLoggers) { // this.exceptionLoggers = ImmutableList.copyOf(exceptionLoggers); // } // // @SuppressWarnings("unchecked") // @Override // public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception exception) { // for (ExceptionLogger<? extends Exception> logger: exceptionLoggers) { // if (logger.canHandleException(exception) && isHystrixInvokableInfo(commandInstance)) { // logger.log(exception, (HystrixInvokableInfo<T>)commandInstance); // return exception; // } // } // // return exception; // } // // private <T> boolean isHystrixInvokableInfo(HystrixInvokable<T> commandInstance) { // return commandInstance instanceof HystrixInvokableInfo; // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/logging/ExceptionLoggingCommandHookTest.java import com.google.common.collect.ImmutableList; import com.netflix.hystrix.HystrixCommand; import com.yammer.tenacity.core.logging.ExceptionLogger; import com.yammer.tenacity.core.logging.ExceptionLoggingCommandHook; import com.yammer.tenacity.testing.TenacityTestRule; import com.yammer.tenacity.tests.TenacityFailingCommand; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; package com.yammer.tenacity.tests.logging; @RunWith(MockitoJUnitRunner.class) public class ExceptionLoggingCommandHookTest { @Rule
public final TenacityTestRule tenacityTestRule = new TenacityTestRule();
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/logging/ExceptionLoggingCommandHookTest.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLogger.java // public abstract class ExceptionLogger<E extends Exception> { // // protected final Class<E> clazz; // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // /** // * Specify the class that this exception logger can handle // */ // protected ExceptionLogger() { // this.clazz = Generics.getTypeParameter(this.getClass(), Exception.class); // } // // /** // * Make sure you check that this ExceptionLogger can actually handle the type of exception // */ // public boolean canHandleException(Exception exception) { // return this.clazz.isInstance(exception); // } // // @SuppressWarnings("unchecked") // /** // * Actually log the exception // * @throws IllegalStateException it relieves an exception that it can't log // */ // public <T> void log(Exception exception, HystrixInvokableInfo<T> commandInstance) { // checkState(canHandleException(exception)); // // logException((E) exception, commandInstance); // } // // /** // * @param exception the exception that you should log // * @param commandInstance you get access to the command that failed, so you can specify what kind it was // */ // protected abstract <T> void logException(E exception, HystrixInvokableInfo<T> commandInstance); // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLoggingCommandHook.java // public class ExceptionLoggingCommandHook extends HystrixCommandExecutionHook { // // private final List<ExceptionLogger<? extends Exception>> exceptionLoggers; // // /** // * Empty constructor only sets the DefaultExceptionLogger, which will log every type of exception // */ // public ExceptionLoggingCommandHook() { // this(new DefaultExceptionLogger()); // } // // public ExceptionLoggingCommandHook(ExceptionLogger<? extends Exception> exceptionLogger) { // this(ImmutableList.of(exceptionLogger)); // } // // public ExceptionLoggingCommandHook(Iterable<ExceptionLogger<? extends Exception>> exceptionLoggers) { // this.exceptionLoggers = ImmutableList.copyOf(exceptionLoggers); // } // // @SuppressWarnings("unchecked") // @Override // public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception exception) { // for (ExceptionLogger<? extends Exception> logger: exceptionLoggers) { // if (logger.canHandleException(exception) && isHystrixInvokableInfo(commandInstance)) { // logger.log(exception, (HystrixInvokableInfo<T>)commandInstance); // return exception; // } // } // // return exception; // } // // private <T> boolean isHystrixInvokableInfo(HystrixInvokable<T> commandInstance) { // return commandInstance instanceof HystrixInvokableInfo; // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // }
import com.google.common.collect.ImmutableList; import com.netflix.hystrix.HystrixCommand; import com.yammer.tenacity.core.logging.ExceptionLogger; import com.yammer.tenacity.core.logging.ExceptionLoggingCommandHook; import com.yammer.tenacity.testing.TenacityTestRule; import com.yammer.tenacity.tests.TenacityFailingCommand; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*;
package com.yammer.tenacity.tests.logging; @RunWith(MockitoJUnitRunner.class) public class ExceptionLoggingCommandHookTest { @Rule public final TenacityTestRule tenacityTestRule = new TenacityTestRule(); private final HystrixCommand<String> failedCommand = new TenacityFailingCommand(); private final Exception exception = new Exception(); @Mock
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLogger.java // public abstract class ExceptionLogger<E extends Exception> { // // protected final Class<E> clazz; // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // /** // * Specify the class that this exception logger can handle // */ // protected ExceptionLogger() { // this.clazz = Generics.getTypeParameter(this.getClass(), Exception.class); // } // // /** // * Make sure you check that this ExceptionLogger can actually handle the type of exception // */ // public boolean canHandleException(Exception exception) { // return this.clazz.isInstance(exception); // } // // @SuppressWarnings("unchecked") // /** // * Actually log the exception // * @throws IllegalStateException it relieves an exception that it can't log // */ // public <T> void log(Exception exception, HystrixInvokableInfo<T> commandInstance) { // checkState(canHandleException(exception)); // // logException((E) exception, commandInstance); // } // // /** // * @param exception the exception that you should log // * @param commandInstance you get access to the command that failed, so you can specify what kind it was // */ // protected abstract <T> void logException(E exception, HystrixInvokableInfo<T> commandInstance); // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLoggingCommandHook.java // public class ExceptionLoggingCommandHook extends HystrixCommandExecutionHook { // // private final List<ExceptionLogger<? extends Exception>> exceptionLoggers; // // /** // * Empty constructor only sets the DefaultExceptionLogger, which will log every type of exception // */ // public ExceptionLoggingCommandHook() { // this(new DefaultExceptionLogger()); // } // // public ExceptionLoggingCommandHook(ExceptionLogger<? extends Exception> exceptionLogger) { // this(ImmutableList.of(exceptionLogger)); // } // // public ExceptionLoggingCommandHook(Iterable<ExceptionLogger<? extends Exception>> exceptionLoggers) { // this.exceptionLoggers = ImmutableList.copyOf(exceptionLoggers); // } // // @SuppressWarnings("unchecked") // @Override // public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception exception) { // for (ExceptionLogger<? extends Exception> logger: exceptionLoggers) { // if (logger.canHandleException(exception) && isHystrixInvokableInfo(commandInstance)) { // logger.log(exception, (HystrixInvokableInfo<T>)commandInstance); // return exception; // } // } // // return exception; // } // // private <T> boolean isHystrixInvokableInfo(HystrixInvokable<T> commandInstance) { // return commandInstance instanceof HystrixInvokableInfo; // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/logging/ExceptionLoggingCommandHookTest.java import com.google.common.collect.ImmutableList; import com.netflix.hystrix.HystrixCommand; import com.yammer.tenacity.core.logging.ExceptionLogger; import com.yammer.tenacity.core.logging.ExceptionLoggingCommandHook; import com.yammer.tenacity.testing.TenacityTestRule; import com.yammer.tenacity.tests.TenacityFailingCommand; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; package com.yammer.tenacity.tests.logging; @RunWith(MockitoJUnitRunner.class) public class ExceptionLoggingCommandHookTest { @Rule public final TenacityTestRule tenacityTestRule = new TenacityTestRule(); private final HystrixCommand<String> failedCommand = new TenacityFailingCommand(); private final Exception exception = new Exception(); @Mock
private ExceptionLogger<RuntimeException> firstLogger;
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/logging/ExceptionLoggingCommandHookTest.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLogger.java // public abstract class ExceptionLogger<E extends Exception> { // // protected final Class<E> clazz; // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // /** // * Specify the class that this exception logger can handle // */ // protected ExceptionLogger() { // this.clazz = Generics.getTypeParameter(this.getClass(), Exception.class); // } // // /** // * Make sure you check that this ExceptionLogger can actually handle the type of exception // */ // public boolean canHandleException(Exception exception) { // return this.clazz.isInstance(exception); // } // // @SuppressWarnings("unchecked") // /** // * Actually log the exception // * @throws IllegalStateException it relieves an exception that it can't log // */ // public <T> void log(Exception exception, HystrixInvokableInfo<T> commandInstance) { // checkState(canHandleException(exception)); // // logException((E) exception, commandInstance); // } // // /** // * @param exception the exception that you should log // * @param commandInstance you get access to the command that failed, so you can specify what kind it was // */ // protected abstract <T> void logException(E exception, HystrixInvokableInfo<T> commandInstance); // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLoggingCommandHook.java // public class ExceptionLoggingCommandHook extends HystrixCommandExecutionHook { // // private final List<ExceptionLogger<? extends Exception>> exceptionLoggers; // // /** // * Empty constructor only sets the DefaultExceptionLogger, which will log every type of exception // */ // public ExceptionLoggingCommandHook() { // this(new DefaultExceptionLogger()); // } // // public ExceptionLoggingCommandHook(ExceptionLogger<? extends Exception> exceptionLogger) { // this(ImmutableList.of(exceptionLogger)); // } // // public ExceptionLoggingCommandHook(Iterable<ExceptionLogger<? extends Exception>> exceptionLoggers) { // this.exceptionLoggers = ImmutableList.copyOf(exceptionLoggers); // } // // @SuppressWarnings("unchecked") // @Override // public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception exception) { // for (ExceptionLogger<? extends Exception> logger: exceptionLoggers) { // if (logger.canHandleException(exception) && isHystrixInvokableInfo(commandInstance)) { // logger.log(exception, (HystrixInvokableInfo<T>)commandInstance); // return exception; // } // } // // return exception; // } // // private <T> boolean isHystrixInvokableInfo(HystrixInvokable<T> commandInstance) { // return commandInstance instanceof HystrixInvokableInfo; // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // }
import com.google.common.collect.ImmutableList; import com.netflix.hystrix.HystrixCommand; import com.yammer.tenacity.core.logging.ExceptionLogger; import com.yammer.tenacity.core.logging.ExceptionLoggingCommandHook; import com.yammer.tenacity.testing.TenacityTestRule; import com.yammer.tenacity.tests.TenacityFailingCommand; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*;
package com.yammer.tenacity.tests.logging; @RunWith(MockitoJUnitRunner.class) public class ExceptionLoggingCommandHookTest { @Rule public final TenacityTestRule tenacityTestRule = new TenacityTestRule(); private final HystrixCommand<String> failedCommand = new TenacityFailingCommand(); private final Exception exception = new Exception(); @Mock private ExceptionLogger<RuntimeException> firstLogger; @Mock private ExceptionLogger<RuntimeException> secondLogger; @Mock private ExceptionLogger<RuntimeException> thirdLogger;
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLogger.java // public abstract class ExceptionLogger<E extends Exception> { // // protected final Class<E> clazz; // protected final Logger logger = LoggerFactory.getLogger(this.getClass()); // // /** // * Specify the class that this exception logger can handle // */ // protected ExceptionLogger() { // this.clazz = Generics.getTypeParameter(this.getClass(), Exception.class); // } // // /** // * Make sure you check that this ExceptionLogger can actually handle the type of exception // */ // public boolean canHandleException(Exception exception) { // return this.clazz.isInstance(exception); // } // // @SuppressWarnings("unchecked") // /** // * Actually log the exception // * @throws IllegalStateException it relieves an exception that it can't log // */ // public <T> void log(Exception exception, HystrixInvokableInfo<T> commandInstance) { // checkState(canHandleException(exception)); // // logException((E) exception, commandInstance); // } // // /** // * @param exception the exception that you should log // * @param commandInstance you get access to the command that failed, so you can specify what kind it was // */ // protected abstract <T> void logException(E exception, HystrixInvokableInfo<T> commandInstance); // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/logging/ExceptionLoggingCommandHook.java // public class ExceptionLoggingCommandHook extends HystrixCommandExecutionHook { // // private final List<ExceptionLogger<? extends Exception>> exceptionLoggers; // // /** // * Empty constructor only sets the DefaultExceptionLogger, which will log every type of exception // */ // public ExceptionLoggingCommandHook() { // this(new DefaultExceptionLogger()); // } // // public ExceptionLoggingCommandHook(ExceptionLogger<? extends Exception> exceptionLogger) { // this(ImmutableList.of(exceptionLogger)); // } // // public ExceptionLoggingCommandHook(Iterable<ExceptionLogger<? extends Exception>> exceptionLoggers) { // this.exceptionLoggers = ImmutableList.copyOf(exceptionLoggers); // } // // @SuppressWarnings("unchecked") // @Override // public <T> Exception onExecutionError(HystrixInvokable<T> commandInstance, Exception exception) { // for (ExceptionLogger<? extends Exception> logger: exceptionLoggers) { // if (logger.canHandleException(exception) && isHystrixInvokableInfo(commandInstance)) { // logger.log(exception, (HystrixInvokableInfo<T>)commandInstance); // return exception; // } // } // // return exception; // } // // private <T> boolean isHystrixInvokableInfo(HystrixInvokable<T> commandInstance) { // return commandInstance instanceof HystrixInvokableInfo; // } // } // // Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/logging/ExceptionLoggingCommandHookTest.java import com.google.common.collect.ImmutableList; import com.netflix.hystrix.HystrixCommand; import com.yammer.tenacity.core.logging.ExceptionLogger; import com.yammer.tenacity.core.logging.ExceptionLoggingCommandHook; import com.yammer.tenacity.testing.TenacityTestRule; import com.yammer.tenacity.tests.TenacityFailingCommand; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; package com.yammer.tenacity.tests.logging; @RunWith(MockitoJUnitRunner.class) public class ExceptionLoggingCommandHookTest { @Rule public final TenacityTestRule tenacityTestRule = new TenacityTestRule(); private final HystrixCommand<String> failedCommand = new TenacityFailingCommand(); private final Exception exception = new Exception(); @Mock private ExceptionLogger<RuntimeException> firstLogger; @Mock private ExceptionLogger<RuntimeException> secondLogger; @Mock private ExceptionLogger<RuntimeException> thirdLogger;
private ExceptionLoggingCommandHook hook;
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/core/CircuitBreakers.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.google.common.collect.ImmutableList; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import java.util.Collection; import java.util.Optional; import java.util.stream.Stream;
package com.yammer.tenacity.core.core; public class CircuitBreakers { private CircuitBreakers() {}
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/core/CircuitBreakers.java import com.google.common.collect.ImmutableList; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import java.util.Collection; import java.util.Optional; import java.util.stream.Stream; package com.yammer.tenacity.core.core; public class CircuitBreakers { private CircuitBreakers() {}
private static Stream<CircuitBreaker> toCircuitBreakers(Collection<TenacityPropertyKey> keys) {
yammer/tenacity
tenacity-client/src/test/java/com/yammer/tenacity/client/tests/TenacityServletAdminService.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/bundle/TenacityBundleBuilder.java // public class TenacityBundleBuilder<T extends Configuration> { // protected final ImmutableList.Builder<ExceptionMapper<? extends Throwable>> exceptionMapperBuilder = ImmutableList.builder(); // protected Optional<HystrixCommandExecutionHook> executionHook = Optional.empty(); // protected TenacityBundleConfigurationFactory<T> configurationFactory; // protected final ImmutableList.Builder<HealthCheck> healthCheckBuilder = ImmutableList.builder(); // protected boolean usingTenacityCircuitBreakerHealthCheck = false; // protected boolean usingAdminPort = false; // // public static <T extends Configuration> TenacityBundleBuilder<T> newBuilder() { // return new TenacityBundleBuilder<>(); // } // // public <E extends Throwable> TenacityBundleBuilder<T> addExceptionMapper(ExceptionMapper<E> exceptionMapper) { // exceptionMapperBuilder.add(exceptionMapper); // return this; // } // // public TenacityBundleBuilder<T> withCircuitBreakerHealthCheck() { // usingTenacityCircuitBreakerHealthCheck = true; // return this; // } // // public TenacityBundleBuilder<T> usingAdminPort() { // usingAdminPort = true; // return this; // } // // public TenacityBundleBuilder<T> mapAllHystrixRuntimeExceptionsTo(int statusCode) { // exceptionMapperBuilder.add(new TenacityExceptionMapper(statusCode)); // exceptionMapperBuilder.add(new TenacityContainerExceptionMapper(statusCode)); // return this; // } // // public TenacityBundleBuilder<T> commandExecutionHook(HystrixCommandExecutionHook executionHook) { // this.executionHook = Optional.of(executionHook); // return this; // } // // public TenacityBundleBuilder<T> configurationFactory(TenacityBundleConfigurationFactory<T> configurationFactory) { // this.configurationFactory = configurationFactory; // return this; // } // // public TenacityConfiguredBundle<T> build() { // if (configurationFactory == null) { // throw new IllegalArgumentException("Must supply a Configuration Factory"); // } // // return new TenacityConfiguredBundle<>( // configurationFactory, // executionHook, // exceptionMapperBuilder.build(), // usingTenacityCircuitBreakerHealthCheck, // usingAdminPort); // } // }
import com.yammer.tenacity.core.bundle.TenacityBundleBuilder; import io.dropwizard.Configuration;
package com.yammer.tenacity.client.tests; public class TenacityServletAdminService extends TenacityServletService { @Override
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/bundle/TenacityBundleBuilder.java // public class TenacityBundleBuilder<T extends Configuration> { // protected final ImmutableList.Builder<ExceptionMapper<? extends Throwable>> exceptionMapperBuilder = ImmutableList.builder(); // protected Optional<HystrixCommandExecutionHook> executionHook = Optional.empty(); // protected TenacityBundleConfigurationFactory<T> configurationFactory; // protected final ImmutableList.Builder<HealthCheck> healthCheckBuilder = ImmutableList.builder(); // protected boolean usingTenacityCircuitBreakerHealthCheck = false; // protected boolean usingAdminPort = false; // // public static <T extends Configuration> TenacityBundleBuilder<T> newBuilder() { // return new TenacityBundleBuilder<>(); // } // // public <E extends Throwable> TenacityBundleBuilder<T> addExceptionMapper(ExceptionMapper<E> exceptionMapper) { // exceptionMapperBuilder.add(exceptionMapper); // return this; // } // // public TenacityBundleBuilder<T> withCircuitBreakerHealthCheck() { // usingTenacityCircuitBreakerHealthCheck = true; // return this; // } // // public TenacityBundleBuilder<T> usingAdminPort() { // usingAdminPort = true; // return this; // } // // public TenacityBundleBuilder<T> mapAllHystrixRuntimeExceptionsTo(int statusCode) { // exceptionMapperBuilder.add(new TenacityExceptionMapper(statusCode)); // exceptionMapperBuilder.add(new TenacityContainerExceptionMapper(statusCode)); // return this; // } // // public TenacityBundleBuilder<T> commandExecutionHook(HystrixCommandExecutionHook executionHook) { // this.executionHook = Optional.of(executionHook); // return this; // } // // public TenacityBundleBuilder<T> configurationFactory(TenacityBundleConfigurationFactory<T> configurationFactory) { // this.configurationFactory = configurationFactory; // return this; // } // // public TenacityConfiguredBundle<T> build() { // if (configurationFactory == null) { // throw new IllegalArgumentException("Must supply a Configuration Factory"); // } // // return new TenacityConfiguredBundle<>( // configurationFactory, // executionHook, // exceptionMapperBuilder.build(), // usingTenacityCircuitBreakerHealthCheck, // usingAdminPort); // } // } // Path: tenacity-client/src/test/java/com/yammer/tenacity/client/tests/TenacityServletAdminService.java import com.yammer.tenacity.core.bundle.TenacityBundleBuilder; import io.dropwizard.Configuration; package com.yammer.tenacity.client.tests; public class TenacityServletAdminService extends TenacityServletService { @Override
protected TenacityBundleBuilder<Configuration> tenacityBundleBuilder() {
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityWebTarget.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.google.common.primitives.Ints; import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.util.Duration; import org.glassfish.jersey.client.ClientProperties; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.Map; import java.util.Objects;
package com.yammer.tenacity.core.http; public class TenacityWebTarget implements WebTarget { private final WebTarget delegate;
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityWebTarget.java import com.google.common.primitives.Ints; import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.util.Duration; import org.glassfish.jersey.client.ClientProperties; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.Map; import java.util.Objects; package com.yammer.tenacity.core.http; public class TenacityWebTarget implements WebTarget { private final WebTarget delegate;
protected final TenacityPropertyKey tenacityPropertyKey;
yammer/tenacity
tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityWebTarget.java
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // }
import com.google.common.primitives.Ints; import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.util.Duration; import org.glassfish.jersey.client.ClientProperties; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.Map; import java.util.Objects;
package com.yammer.tenacity.core.http; public class TenacityWebTarget implements WebTarget { private final WebTarget delegate; protected final TenacityPropertyKey tenacityPropertyKey; protected final Duration timeoutPadding; public TenacityWebTarget(WebTarget delegate, TenacityPropertyKey tenacityPropertyKey, Duration timeoutPadding) { this.delegate = delegate; this.tenacityPropertyKey = tenacityPropertyKey; this.timeoutPadding = timeoutPadding; } protected void setTimeoutWithTenacity(Invocation.Builder builder) {
// Path: tenacity-core/src/main/java/com/yammer/tenacity/core/TenacityCommand.java // public abstract class TenacityCommand<R> extends HystrixCommand<R> { // protected TenacityCommand(TenacityPropertyKey tenacityPropertyKey) { // this(tenacityPropertyKey, tenacityPropertyKey); // } // // protected TenacityCommand(TenacityPropertyKey commandKey, // TenacityPropertyKey threadpoolKey) { // super(HystrixCommand.Setter.withGroupKey(tenacityGroupKey()) // .andCommandKey(commandKey) // .andThreadPoolKey(threadpoolKey)); // } // // static HystrixCommandGroupKey tenacityGroupKey() { // return commandGroupKeyFrom("TENACITY"); // } // // public static HystrixCommandGroupKey commandGroupKeyFrom(String key) { // return HystrixCommandGroupKey.Factory.asKey(key); // } // // public static HystrixCommandProperties getCommandProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getCommandProperties(key, null); // } // // public HystrixCommandProperties getCommandProperties() { // return HystrixPropertiesFactory.getCommandProperties(getCommandKey(), null); // } // // public static HystrixThreadPoolProperties getThreadpoolProperties(TenacityPropertyKey key) { // return HystrixPropertiesFactory.getThreadPoolProperties(key, null); // } // // public static <R> Builder<R> builder(TenacityPropertyKey tenacityPropertyKey) { // return new Builder<>(tenacityPropertyKey); // } // // public HystrixThreadPoolProperties getThreadpoolProperties() { // return HystrixPropertiesFactory.getThreadPoolProperties(getThreadPoolKey(), null); // } // // public HystrixCommandMetrics getCommandMetrics() { // return HystrixCommandMetrics.getInstance(getCommandKey()); // } // // public static HystrixCommandMetrics getCommandMetrics(TenacityPropertyKey key) { // return HystrixCommandMetrics.getInstance(key); // } // // public HystrixThreadPoolMetrics getThreadpoolMetrics() { // return HystrixThreadPoolMetrics.getInstance(getThreadPoolKey()); // } // // public static HystrixThreadPoolMetrics getThreadpoolMetrics(TenacityPropertyKey key) { // return HystrixThreadPoolMetrics.getInstance(key); // } // // public HystrixCircuitBreaker getCircuitBreaker() { // return HystrixCircuitBreaker.Factory.getInstance(getCommandKey()); // } // // public static HystrixCircuitBreaker getCircuitBreaker(TenacityPropertyKey key) { // return HystrixCircuitBreaker.Factory.getInstance(key); // } // // public CumulativeCommandEventCounterStream getCumulativeCommandEventCounterStream() { // return CumulativeCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public RollingCommandEventCounterStream getRollingCommandEventCounterStream() { // return RollingCommandEventCounterStream.getInstance(getCommandKey(), getCommandProperties()); // } // // public static class Builder<R> { // protected final TenacityPropertyKey key; // protected Supplier<R> run; // protected Supplier<R> fallback; // // public Builder(TenacityPropertyKey key) { // this.key = key; // } // // public Builder<R> run(Supplier<R> fun) { // run = fun; // return this; // } // // public Builder<R> fallback(Supplier<R> fun) { // fallback = fun; // return this; // } // // public TenacityCommand<R> build() { // if (run == null) { // throw new IllegalStateException("Run must be supplied."); // } // if (fallback == null) { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // }; // } else { // return new TenacityCommand<R>(key) { // @Override // protected R run() throws Exception { // return run.get(); // } // // @Override // protected R getFallback() { // return fallback.get(); // } // }; // } // } // // public R execute() { // return build().execute(); // } // // public Future<R> queue() { // return build().queue(); // } // // public Observable<R> observe() { // return build().observe(); // } // // public Observable<R> lazyObservable() { // return build().toObservable(); // } // } // // @Override // protected abstract R run() throws Exception; // } // // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/properties/TenacityPropertyKey.java // public interface TenacityPropertyKey extends HystrixCommandKey, HystrixThreadPoolKey { // default Predicate<TenacityPropertyKey> isEqualPredicate() { // return (value) -> value.name().equals(name()); // } // // default TenacityPropertyKey validate(Collection<TenacityPropertyKey> keys) { // return keys.stream() // .filter(isEqualPredicate()) // .findAny() // .orElseThrow(() -> new NoSuchElementException("No TenacityPropertyKey " + name())); // } // } // Path: tenacity-core/src/main/java/com/yammer/tenacity/core/http/TenacityWebTarget.java import com.google.common.primitives.Ints; import com.yammer.tenacity.core.TenacityCommand; import com.yammer.tenacity.core.properties.TenacityPropertyKey; import io.dropwizard.util.Duration; import org.glassfish.jersey.client.ClientProperties; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.Map; import java.util.Objects; package com.yammer.tenacity.core.http; public class TenacityWebTarget implements WebTarget { private final WebTarget delegate; protected final TenacityPropertyKey tenacityPropertyKey; protected final Duration timeoutPadding; public TenacityWebTarget(WebTarget delegate, TenacityPropertyKey tenacityPropertyKey, Duration timeoutPadding) { this.delegate = delegate; this.tenacityPropertyKey = tenacityPropertyKey; this.timeoutPadding = timeoutPadding; } protected void setTimeoutWithTenacity(Invocation.Builder builder) {
builder.property(ClientProperties.READ_TIMEOUT, Ints.checkedCast(TenacityCommand
yammer/tenacity
tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityCircuitBreakerTest.java
// Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // }
import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import com.yammer.tenacity.testing.TenacityTestRule; import org.junit.Rule; import org.junit.Test; import java.net.URISyntaxException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package com.yammer.tenacity.tests; public class TenacityCircuitBreakerTest { @Rule
// Path: tenacity-testing/src/main/java/com/yammer/tenacity/testing/TenacityTestRule.java // public class TenacityTestRule implements TestRule { // private void setup() { // resetStreams(); // Hystrix.reset(); // final AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); // configuration.setProperty("hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds", "100"); // } // // public void teardown() { // Hystrix.reset(1, TimeUnit.SECONDS); // ConfigurationManager.getConfigInstance().clear(); // } // // private void resetStreams() { // /* BucketedCounterStream */ // CumulativeCommandEventCounterStream.reset(); // RollingCommandEventCounterStream.reset(); // CumulativeCollapserEventCounterStream.reset(); // RollingCollapserEventCounterStream.reset(); // CumulativeThreadPoolEventCounterStream.reset(); // RollingThreadPoolEventCounterStream.reset(); // HealthCountsStream.reset(); // /* --------------------- */ // // /* RollingConcurrencyStream */ // RollingThreadPoolMaxConcurrencyStream.reset(); // RollingCommandMaxConcurrencyStream.reset(); // /* ------------------------ */ // // /* RollingDistributionStream */ // RollingCommandLatencyDistributionStream.reset(); // RollingCommandUserLatencyDistributionStream.reset(); // RollingCollapserBatchSizeDistributionStream.reset(); // /* ------------------------- */ // } // // @Override // public Statement apply(final Statement base, Description description) { // return new Statement() { // @Override // public void evaluate() throws Throwable { // try { // setup(); // base.evaluate(); // } finally { // teardown(); // } // } // }; // } // } // Path: tenacity-core/src/test/java/com/yammer/tenacity/tests/TenacityCircuitBreakerTest.java import com.netflix.hystrix.HystrixCommandMetrics; import com.netflix.hystrix.util.HystrixRollingNumberEvent; import com.yammer.tenacity.testing.TenacityTestRule; import org.junit.Rule; import org.junit.Test; import java.net.URISyntaxException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package com.yammer.tenacity.tests; public class TenacityCircuitBreakerTest { @Rule
public final TenacityTestRule tenacityTestRule = new TenacityTestRule();