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
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/WePayApi.java
// Path: src/main/java/com/lookfirst/wepay/api/Token.java // @Data // public class Token implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique user ID of the user */ // private String userId; // /** The access token that you can use to make calls on behalf of the user */ // private String accessToken; // /** The token type - for now only "BEARER" is supported */ // private String tokenType; // /** How much time till the access_token expires. If NULL or not present, the access token will be valid until the user revokes the access_token */ // private String expiresIn; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/TokenRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class TokenRequest extends WePayRequest<Token> { // // public static final String ENDPOINT = "/oauth2/token"; // // /** Yes The client ID issued to the app by WePay - see your client ID on your app screen */ // private Long clientId; // /** Yes The uri the user will be redirected to after authorization. Must be the same as passed in /v2/oauth2/authorize */ // private String redirectUri; // /** Yes The client secret issued to the app by WePay - see your client secret on your app screen */ // private String clientSecret; // /** Yes The code returned by /v2/oauth2/authorize */ // private String code; // // /** */ // @Override // public String getEndpoint() { // return "/oauth2/token"; // } // // } // // Path: src/main/java/com/lookfirst/wepay/api/req/WePayRequest.java // public abstract class WePayRequest<T> { // @JsonIgnore // public abstract String getEndpoint(); // } // // Path: src/main/java/com/lookfirst/wepay/util/DataProvider.java // public interface DataProvider { // InputStream getData(String uri, String postJson, String token) throws IOException; // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.lookfirst.wepay.api.Token; import com.lookfirst.wepay.api.req.TokenRequest; import com.lookfirst.wepay.api.req.WePayRequest; import com.lookfirst.wepay.util.DataProvider; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List;
* permission to make API calls * @see <a href="https://www.wepay.com/developer/reference/oauth2">https://www.wepay.com/developer/reference/oauth2</a> * @param scopes List of scope fields for which your application wants access * @param redirectUri Where user goes after logging in at WePay (domain must match application settings) * @param userName user_name,user_email which will be pre-filled on login form, state to be returned in querystring of redirect_uri * @return string URI to which you must redirect your user to grant access to your application */ public String getAuthorizationUri(List<Scope> scopes, String redirectUri, String state, String userName, String userEmail) { // this method must use www instead of just naked domain for security reasons. String host = key.isProduction() ? "https://www.wepay.com" : "https://stage.wepay.com"; String uri = host + "/v2/oauth2/authorize?"; uri += "client_id=" + urlEncode(key.getClientId()) + "&"; uri += "redirect_uri=" + urlEncode(redirectUri) + "&"; uri += "scope=" + urlEncode(StringUtils.join(scopes, ",")); if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; } /** * Exchange a temporary access code for a (semi-)permanent access token * @param code 'code' field from query string passed to your redirect_uri page * @param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri) * @return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"} */
// Path: src/main/java/com/lookfirst/wepay/api/Token.java // @Data // public class Token implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique user ID of the user */ // private String userId; // /** The access token that you can use to make calls on behalf of the user */ // private String accessToken; // /** The token type - for now only "BEARER" is supported */ // private String tokenType; // /** How much time till the access_token expires. If NULL or not present, the access token will be valid until the user revokes the access_token */ // private String expiresIn; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/TokenRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class TokenRequest extends WePayRequest<Token> { // // public static final String ENDPOINT = "/oauth2/token"; // // /** Yes The client ID issued to the app by WePay - see your client ID on your app screen */ // private Long clientId; // /** Yes The uri the user will be redirected to after authorization. Must be the same as passed in /v2/oauth2/authorize */ // private String redirectUri; // /** Yes The client secret issued to the app by WePay - see your client secret on your app screen */ // private String clientSecret; // /** Yes The code returned by /v2/oauth2/authorize */ // private String code; // // /** */ // @Override // public String getEndpoint() { // return "/oauth2/token"; // } // // } // // Path: src/main/java/com/lookfirst/wepay/api/req/WePayRequest.java // public abstract class WePayRequest<T> { // @JsonIgnore // public abstract String getEndpoint(); // } // // Path: src/main/java/com/lookfirst/wepay/util/DataProvider.java // public interface DataProvider { // InputStream getData(String uri, String postJson, String token) throws IOException; // } // Path: src/main/java/com/lookfirst/wepay/WePayApi.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.lookfirst.wepay.api.Token; import com.lookfirst.wepay.api.req.TokenRequest; import com.lookfirst.wepay.api.req.WePayRequest; import com.lookfirst.wepay.util.DataProvider; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; * permission to make API calls * @see <a href="https://www.wepay.com/developer/reference/oauth2">https://www.wepay.com/developer/reference/oauth2</a> * @param scopes List of scope fields for which your application wants access * @param redirectUri Where user goes after logging in at WePay (domain must match application settings) * @param userName user_name,user_email which will be pre-filled on login form, state to be returned in querystring of redirect_uri * @return string URI to which you must redirect your user to grant access to your application */ public String getAuthorizationUri(List<Scope> scopes, String redirectUri, String state, String userName, String userEmail) { // this method must use www instead of just naked domain for security reasons. String host = key.isProduction() ? "https://www.wepay.com" : "https://stage.wepay.com"; String uri = host + "/v2/oauth2/authorize?"; uri += "client_id=" + urlEncode(key.getClientId()) + "&"; uri += "redirect_uri=" + urlEncode(redirectUri) + "&"; uri += "scope=" + urlEncode(StringUtils.join(scopes, ",")); if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; } /** * Exchange a temporary access code for a (semi-)permanent access token * @param code 'code' field from query string passed to your redirect_uri page * @param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri) * @return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"} */
public Token getToken(String code, String redirectUrl) throws IOException, WePayException {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/WePayApi.java
// Path: src/main/java/com/lookfirst/wepay/api/Token.java // @Data // public class Token implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique user ID of the user */ // private String userId; // /** The access token that you can use to make calls on behalf of the user */ // private String accessToken; // /** The token type - for now only "BEARER" is supported */ // private String tokenType; // /** How much time till the access_token expires. If NULL or not present, the access token will be valid until the user revokes the access_token */ // private String expiresIn; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/TokenRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class TokenRequest extends WePayRequest<Token> { // // public static final String ENDPOINT = "/oauth2/token"; // // /** Yes The client ID issued to the app by WePay - see your client ID on your app screen */ // private Long clientId; // /** Yes The uri the user will be redirected to after authorization. Must be the same as passed in /v2/oauth2/authorize */ // private String redirectUri; // /** Yes The client secret issued to the app by WePay - see your client secret on your app screen */ // private String clientSecret; // /** Yes The code returned by /v2/oauth2/authorize */ // private String code; // // /** */ // @Override // public String getEndpoint() { // return "/oauth2/token"; // } // // } // // Path: src/main/java/com/lookfirst/wepay/api/req/WePayRequest.java // public abstract class WePayRequest<T> { // @JsonIgnore // public abstract String getEndpoint(); // } // // Path: src/main/java/com/lookfirst/wepay/util/DataProvider.java // public interface DataProvider { // InputStream getData(String uri, String postJson, String token) throws IOException; // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.lookfirst.wepay.api.Token; import com.lookfirst.wepay.api.req.TokenRequest; import com.lookfirst.wepay.api.req.WePayRequest; import com.lookfirst.wepay.util.DataProvider; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List;
* @param scopes List of scope fields for which your application wants access * @param redirectUri Where user goes after logging in at WePay (domain must match application settings) * @param userName user_name,user_email which will be pre-filled on login form, state to be returned in querystring of redirect_uri * @return string URI to which you must redirect your user to grant access to your application */ public String getAuthorizationUri(List<Scope> scopes, String redirectUri, String state, String userName, String userEmail) { // this method must use www instead of just naked domain for security reasons. String host = key.isProduction() ? "https://www.wepay.com" : "https://stage.wepay.com"; String uri = host + "/v2/oauth2/authorize?"; uri += "client_id=" + urlEncode(key.getClientId()) + "&"; uri += "redirect_uri=" + urlEncode(redirectUri) + "&"; uri += "scope=" + urlEncode(StringUtils.join(scopes, ",")); if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; } /** * Exchange a temporary access code for a (semi-)permanent access token * @param code 'code' field from query string passed to your redirect_uri page * @param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri) * @return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"} */ public Token getToken(String code, String redirectUrl) throws IOException, WePayException {
// Path: src/main/java/com/lookfirst/wepay/api/Token.java // @Data // public class Token implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique user ID of the user */ // private String userId; // /** The access token that you can use to make calls on behalf of the user */ // private String accessToken; // /** The token type - for now only "BEARER" is supported */ // private String tokenType; // /** How much time till the access_token expires. If NULL or not present, the access token will be valid until the user revokes the access_token */ // private String expiresIn; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/TokenRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class TokenRequest extends WePayRequest<Token> { // // public static final String ENDPOINT = "/oauth2/token"; // // /** Yes The client ID issued to the app by WePay - see your client ID on your app screen */ // private Long clientId; // /** Yes The uri the user will be redirected to after authorization. Must be the same as passed in /v2/oauth2/authorize */ // private String redirectUri; // /** Yes The client secret issued to the app by WePay - see your client secret on your app screen */ // private String clientSecret; // /** Yes The code returned by /v2/oauth2/authorize */ // private String code; // // /** */ // @Override // public String getEndpoint() { // return "/oauth2/token"; // } // // } // // Path: src/main/java/com/lookfirst/wepay/api/req/WePayRequest.java // public abstract class WePayRequest<T> { // @JsonIgnore // public abstract String getEndpoint(); // } // // Path: src/main/java/com/lookfirst/wepay/util/DataProvider.java // public interface DataProvider { // InputStream getData(String uri, String postJson, String token) throws IOException; // } // Path: src/main/java/com/lookfirst/wepay/WePayApi.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.lookfirst.wepay.api.Token; import com.lookfirst.wepay.api.req.TokenRequest; import com.lookfirst.wepay.api.req.WePayRequest; import com.lookfirst.wepay.util.DataProvider; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; * @param scopes List of scope fields for which your application wants access * @param redirectUri Where user goes after logging in at WePay (domain must match application settings) * @param userName user_name,user_email which will be pre-filled on login form, state to be returned in querystring of redirect_uri * @return string URI to which you must redirect your user to grant access to your application */ public String getAuthorizationUri(List<Scope> scopes, String redirectUri, String state, String userName, String userEmail) { // this method must use www instead of just naked domain for security reasons. String host = key.isProduction() ? "https://www.wepay.com" : "https://stage.wepay.com"; String uri = host + "/v2/oauth2/authorize?"; uri += "client_id=" + urlEncode(key.getClientId()) + "&"; uri += "redirect_uri=" + urlEncode(redirectUri) + "&"; uri += "scope=" + urlEncode(StringUtils.join(scopes, ",")); if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; } /** * Exchange a temporary access code for a (semi-)permanent access token * @param code 'code' field from query string passed to your redirect_uri page * @param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri) * @return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"} */ public Token getToken(String code, String redirectUrl) throws IOException, WePayException {
TokenRequest request = new TokenRequest();
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/WePayApi.java
// Path: src/main/java/com/lookfirst/wepay/api/Token.java // @Data // public class Token implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique user ID of the user */ // private String userId; // /** The access token that you can use to make calls on behalf of the user */ // private String accessToken; // /** The token type - for now only "BEARER" is supported */ // private String tokenType; // /** How much time till the access_token expires. If NULL or not present, the access token will be valid until the user revokes the access_token */ // private String expiresIn; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/TokenRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class TokenRequest extends WePayRequest<Token> { // // public static final String ENDPOINT = "/oauth2/token"; // // /** Yes The client ID issued to the app by WePay - see your client ID on your app screen */ // private Long clientId; // /** Yes The uri the user will be redirected to after authorization. Must be the same as passed in /v2/oauth2/authorize */ // private String redirectUri; // /** Yes The client secret issued to the app by WePay - see your client secret on your app screen */ // private String clientSecret; // /** Yes The code returned by /v2/oauth2/authorize */ // private String code; // // /** */ // @Override // public String getEndpoint() { // return "/oauth2/token"; // } // // } // // Path: src/main/java/com/lookfirst/wepay/api/req/WePayRequest.java // public abstract class WePayRequest<T> { // @JsonIgnore // public abstract String getEndpoint(); // } // // Path: src/main/java/com/lookfirst/wepay/util/DataProvider.java // public interface DataProvider { // InputStream getData(String uri, String postJson, String token) throws IOException; // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.lookfirst.wepay.api.Token; import com.lookfirst.wepay.api.req.TokenRequest; import com.lookfirst.wepay.api.req.WePayRequest; import com.lookfirst.wepay.util.DataProvider; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List;
if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; } /** * Exchange a temporary access code for a (semi-)permanent access token * @param code 'code' field from query string passed to your redirect_uri page * @param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri) * @return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"} */ public Token getToken(String code, String redirectUrl) throws IOException, WePayException { TokenRequest request = new TokenRequest(); request.setClientId(key.getClientId()); request.setClientSecret(key.getClientSecret()); request.setRedirectUri(redirectUrl); request.setCode(code); return execute(null, request); } /** * Make API calls against authenticated user. * Turn up logging to trace level to see the request / response. */
// Path: src/main/java/com/lookfirst/wepay/api/Token.java // @Data // public class Token implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique user ID of the user */ // private String userId; // /** The access token that you can use to make calls on behalf of the user */ // private String accessToken; // /** The token type - for now only "BEARER" is supported */ // private String tokenType; // /** How much time till the access_token expires. If NULL or not present, the access token will be valid until the user revokes the access_token */ // private String expiresIn; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/TokenRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class TokenRequest extends WePayRequest<Token> { // // public static final String ENDPOINT = "/oauth2/token"; // // /** Yes The client ID issued to the app by WePay - see your client ID on your app screen */ // private Long clientId; // /** Yes The uri the user will be redirected to after authorization. Must be the same as passed in /v2/oauth2/authorize */ // private String redirectUri; // /** Yes The client secret issued to the app by WePay - see your client secret on your app screen */ // private String clientSecret; // /** Yes The code returned by /v2/oauth2/authorize */ // private String code; // // /** */ // @Override // public String getEndpoint() { // return "/oauth2/token"; // } // // } // // Path: src/main/java/com/lookfirst/wepay/api/req/WePayRequest.java // public abstract class WePayRequest<T> { // @JsonIgnore // public abstract String getEndpoint(); // } // // Path: src/main/java/com/lookfirst/wepay/util/DataProvider.java // public interface DataProvider { // InputStream getData(String uri, String postJson, String token) throws IOException; // } // Path: src/main/java/com/lookfirst/wepay/WePayApi.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.SerializationFeature; import com.lookfirst.wepay.api.Token; import com.lookfirst.wepay.api.req.TokenRequest; import com.lookfirst.wepay.api.req.WePayRequest; import com.lookfirst.wepay.util.DataProvider; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; } /** * Exchange a temporary access code for a (semi-)permanent access token * @param code 'code' field from query string passed to your redirect_uri page * @param redirectUrl Where user went after logging in at WePay (must match value from getAuthorizationUri) * @return json {"user_id":"123456","access_token":"1337h4x0rzabcd12345","token_type":"BEARER"} */ public Token getToken(String code, String redirectUrl) throws IOException, WePayException { TokenRequest request = new TokenRequest(); request.setClientId(key.getClientId()); request.setClientSecret(key.getClientSecret()); request.setRedirectUri(redirectUrl); request.setCode(code); return execute(null, request); } /** * Make API calls against authenticated user. * Turn up logging to trace level to see the request / response. */
public <T> T execute(String token, WePayRequest<T> req) throws IOException, WePayException {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutCaptureRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutState.java // @Data // @EqualsAndHashCode(callSuper=true) // public class CheckoutState extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The state the payment is in. See the IPN section for a list of payment states. */ // private State state; // }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutState;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * If auto_capture was set to 0 when the checkout was created, you will need to make this call * to release funds to the account. Until you make this call the money will be held by WePay. * You can only make this call if the checkout is in state 'reserved'. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutState.java // @Data // @EqualsAndHashCode(callSuper=true) // public class CheckoutState extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The state the payment is in. See the IPN section for a list of payment states. */ // private State state; // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutCaptureRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutState; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * If auto_capture was set to 0 when the checkout was created, you will need to make this call * to release funds to the account. Until you make this call the money will be held by WePay. * You can only make this call if the checkout is in state 'reserved'. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class CheckoutCaptureRequest extends WePayRequest<CheckoutState> {
lookfirst/WePay-Java-SDK
src/test/java/com/lookfirst/wepay/WePayApiTest.java
// Path: src/main/java/com/lookfirst/wepay/WePayApi.java // @AllArgsConstructor // public enum Scope { // MANAGE_ACCOUNTS ("manage_accounts"), // Open and interact with accounts // VIEW_BALANCE ("view_balance"), // View account balances // COLLECT_PAYMENTS ("collect_payments"), // Create and interact with checkouts // REFUND_PAYMENTS ("refund_payments"), // Refund checkouts // VIEW_USER ("view_user"), // Get details about authenticated user // PREAPPROVE_PAYMENTS ("preapprove_payments"),// preapproval // SEND_MONEY ("send_money"); // /disbursement & /transfer // // private String scope; // // public static List<Scope> getAll() { // return Arrays.asList(values()); // } // // public String toString() { // return scope; // } // }
import com.lookfirst.wepay.WePayApi.Scope; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test;
package com.lookfirst.wepay; /** * Testing the api class. */ @Test public class WePayApiTest { private WePayApi api; @BeforeSuite public void setup() { WePayKey key = new WePayKey(false, 123L, "secret"); api = new WePayApi(key); } public void testGetAuthorizationUri() {
// Path: src/main/java/com/lookfirst/wepay/WePayApi.java // @AllArgsConstructor // public enum Scope { // MANAGE_ACCOUNTS ("manage_accounts"), // Open and interact with accounts // VIEW_BALANCE ("view_balance"), // View account balances // COLLECT_PAYMENTS ("collect_payments"), // Create and interact with checkouts // REFUND_PAYMENTS ("refund_payments"), // Refund checkouts // VIEW_USER ("view_user"), // Get details about authenticated user // PREAPPROVE_PAYMENTS ("preapprove_payments"),// preapproval // SEND_MONEY ("send_money"); // /disbursement & /transfer // // private String scope; // // public static List<Scope> getAll() { // return Arrays.asList(values()); // } // // public String toString() { // return scope; // } // } // Path: src/test/java/com/lookfirst/wepay/WePayApiTest.java import com.lookfirst.wepay.WePayApi.Scope; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; package com.lookfirst.wepay; /** * Testing the api class. */ @Test public class WePayApiTest { private WePayApi api; @BeforeSuite public void setup() { WePayKey key = new WePayKey(false, 123L, "secret"); api = new WePayApi(key); } public void testGetAuthorizationUri() {
String result = api.getAuthorizationUri(Scope.getAll(), "http://test/redirect", "state");
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/TransferRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/Transfer.java // @Deprecated // @Data // @EqualsAndHashCode(callSuper=true) // public class Transfer extends TransferInstruction { // private static final long serialVersionUID = 1L; // // /** The unique ID of the transfer. */ // public String transferId; // /** The unique ID of the account the money is coming from. */ // public String accountId; // /** No The unique ID of the disbursement you want to look up transfers for. */ // public String disbursementId; // /** The state that the disbursement is in (new, sent, or failed). */ // public String state; // }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Transfer;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/disbursement * * This call allows you to look up the details of a transfer. A transfer is an object that * represents the movement of money from a WePay account to an email address. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Deprecated @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/Transfer.java // @Deprecated // @Data // @EqualsAndHashCode(callSuper=true) // public class Transfer extends TransferInstruction { // private static final long serialVersionUID = 1L; // // /** The unique ID of the transfer. */ // public String transferId; // /** The unique ID of the account the money is coming from. */ // public String accountId; // /** No The unique ID of the disbursement you want to look up transfers for. */ // public String disbursementId; // /** The state that the disbursement is in (new, sent, or failed). */ // public String state; // } // Path: src/main/java/com/lookfirst/wepay/api/req/TransferRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Transfer; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/disbursement * * This call allows you to look up the details of a transfer. A transfer is an object that * represents the movement of money from a WePay account to an email address. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Deprecated @Data @EqualsAndHashCode(callSuper=false)
public class TransferRequest extends WePayRequest<Transfer> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/UserSendConfirmationRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/WePayUser.java // @Data // public class WePayUser implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the user. */ // private String userId; // /** The first name of the user */ // private String firstName; // /** The last name of the user */ // private String lastName; // /** The email of the user */ // private String email; // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // private String state; // // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // public boolean isRegistered() { // return state != null && state.equals("registered"); // } // }
import com.lookfirst.wepay.api.WePayUser; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/user * * For users who were registered via the /user/register call, this API call lets you resend the API registration confirmation email. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/WePayUser.java // @Data // public class WePayUser implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the user. */ // private String userId; // /** The first name of the user */ // private String firstName; // /** The last name of the user */ // private String lastName; // /** The email of the user */ // private String email; // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // private String state; // // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // public boolean isRegistered() { // return state != null && state.equals("registered"); // } // } // Path: src/main/java/com/lookfirst/wepay/api/req/UserSendConfirmationRequest.java import com.lookfirst.wepay.api.WePayUser; import lombok.Data; import lombok.EqualsAndHashCode; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/user * * For users who were registered via the /user/register call, this API call lets you resend the API registration confirmation email. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class UserSendConfirmationRequest extends WePayRequest<WePayUser> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/WithdrawalModifyRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/Withdrawal.java // @Data // @EqualsAndHashCode(callSuper=false) // public class Withdrawal implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the withdrawal. */ // private Long withdrawalId; // /** The unique ID of the account that the money is coming from. */ // private Long accountId; // /** The state that the withdrawal is in See the section on payment states for a list of possible states. */ // private State state; // /** The uri that the account owner will return to after completing the withdrawal. Set to app homepage if not passed in /withdrawal/create. */ // private String redirectUri; // /** The uri that you will send the account owner to to complete the withdrawal. */ // private String withdrawalUri; // /** The uri that we will post notifications to each time the state on this withdrawal changes. */ // private String callbackUri; // /** The amount on money withdrawn from the WePay account to the bank account. */ // private BigDecimal amount; // /** The currency used, default "USD" ("USD" for now). */ // private String currency; // /** A short description for the reason of the withdrawal (255 characters). */ // private String note; // /** Whether the recipient of the money has been confirmed (for bank withdrawals this is the receiving bank account). */ // private boolean recipientConfirmed; // /** The type of withdrawal. Will be "check" for a sent paper check, or "ach" for a withdrawal to a bank account. */ // private WithdrawalType type; // /** The unixtime when the withdrawal was created. */ // private Long createTime; // /** The unixtime when the withdrawal was captured and credited to the payee's bank account. Returns 0 if withdrawal is not yet captured. */ // private Long captureTime; // }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Withdrawal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/withdrawal * * This call allows you to change the callback_uri on a withdrawal. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/Withdrawal.java // @Data // @EqualsAndHashCode(callSuper=false) // public class Withdrawal implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the withdrawal. */ // private Long withdrawalId; // /** The unique ID of the account that the money is coming from. */ // private Long accountId; // /** The state that the withdrawal is in See the section on payment states for a list of possible states. */ // private State state; // /** The uri that the account owner will return to after completing the withdrawal. Set to app homepage if not passed in /withdrawal/create. */ // private String redirectUri; // /** The uri that you will send the account owner to to complete the withdrawal. */ // private String withdrawalUri; // /** The uri that we will post notifications to each time the state on this withdrawal changes. */ // private String callbackUri; // /** The amount on money withdrawn from the WePay account to the bank account. */ // private BigDecimal amount; // /** The currency used, default "USD" ("USD" for now). */ // private String currency; // /** A short description for the reason of the withdrawal (255 characters). */ // private String note; // /** Whether the recipient of the money has been confirmed (for bank withdrawals this is the receiving bank account). */ // private boolean recipientConfirmed; // /** The type of withdrawal. Will be "check" for a sent paper check, or "ach" for a withdrawal to a bank account. */ // private WithdrawalType type; // /** The unixtime when the withdrawal was created. */ // private Long createTime; // /** The unixtime when the withdrawal was captured and credited to the payee's bank account. Returns 0 if withdrawal is not yet captured. */ // private Long captureTime; // } // Path: src/main/java/com/lookfirst/wepay/api/req/WithdrawalModifyRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Withdrawal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/withdrawal * * This call allows you to change the callback_uri on a withdrawal. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class WithdrawalModifyRequest extends WePayRequest<Withdrawal> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/PreapprovalRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/Preapproval.java // @Data // public class Preapproval implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the preapproval. */ // private Long preapprovalId; // /** The uri that you send the user to so they can enter their payment info and approve the preapproval. */ // private String preapprovalUri; // /** A uri that you can send the user to if they need to update their payment method. */ // private String manageUri; // /** The unique ID of the WePay account where the money will go. */ // private Long accountId; // // /** A short description of what the payer is being charged for. */ // private String shortDescription; // /** A longer description of what the payer is being charged for (if set). */ // private String longDescription; // // /** The currency that any charges will take place in (for now always USD). */ // private String currency; // /** The amount in dollars that the application can charge the payer automatically every period. */ // private BigDecimal amount; // /** Who is paying the fee (either "payer" for the person paying, "payee" for the person receiving the money, "payer_from_app" if payer is paying for app fee and the app is paying WePay fees, or "payee_from_app" if payee is paying for app fee and app is paying for WePay fees). */ // private FeePayer feePayer; // /** The state that the preapproval is in. See the object states page for the full list. */ // private State state; // /** The uri that the payer will be redirected to after approving the preapproval. */ // private String redirectUri; // /** The fee that will go to the API application's account (if set). Limited to 20% of the preapproval amount. */ // private BigDecimal appFee; // /** How often the API application can execute payments for a payer with this preapproval. Can be: hourly, daily, weekly, biweekly, monthly, bimonthly, quarterly, yearly, and once. Once period is if you only want to get authorization for a future charge and don't need it to be recurring. */ // private String period; // /** The number of times the API application can execute payments per period. */ // private Integer frequency; // /** When the API application can begin executing payments with this preapproval. Will be a unix timestamp. */ // private Long startTime; // /** The last time that the API application can execute a payment with this preapproval. Will be a unix timestamp. */ // private Long endTime; // /** The reference_id passed by the application (if set). */ // private String referenceId; // /** The uri which instant payment notifications will be sent to. */ // private String callbackUri; // /** The shipping address that the payer entered (if applicable). It will be in the following format: // // US Addresses: // {"address1":"380 Portage Ave","address2":"","city":"Palo Alto","state":"CA","zip":"94306","country":"US"}. // // Non-US Addresses: // {"address1":"100 Main St","address2":"","city":"Toronto","region":"ON","postcode":"M4E 1Z5","country":"CA"} // // Use ISO 3166-1 codes when specifying the country. // */ // private ShippingAddress address; // /** The amount that was paid in shipping fees (if any). */ // private BigDecimal shippingFee; // /** The dollar amount of taxes paid (if any). */ // private BigDecimal tax; // /** Whether or not the preapproval automatically executes the payments every period. */ // private boolean autoRecur; // /** The name of the payer. */ // private String payerName; // /** The email of the payer. */ // private String payeeEmail; // /** The unixtime when the preapproval was created. */ // private Long createTime; // /** The unixtime of the next scheduled charge +/- 5 minutes (will only show up for approved auto_recur preapprovals). */ // private Long nextDueTime; // /** The checkout ID of the last successful checkout (state captured) for the preapproval. */ // private Long lastCheckoutId; // /** The unixtime when the last successful checkout occurred. */ // private Long lastCheckoutTime; // }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Preapproval;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/preapproval * * This call allows you to lookup the details of a payment preapproval on WePay. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/Preapproval.java // @Data // public class Preapproval implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the preapproval. */ // private Long preapprovalId; // /** The uri that you send the user to so they can enter their payment info and approve the preapproval. */ // private String preapprovalUri; // /** A uri that you can send the user to if they need to update their payment method. */ // private String manageUri; // /** The unique ID of the WePay account where the money will go. */ // private Long accountId; // // /** A short description of what the payer is being charged for. */ // private String shortDescription; // /** A longer description of what the payer is being charged for (if set). */ // private String longDescription; // // /** The currency that any charges will take place in (for now always USD). */ // private String currency; // /** The amount in dollars that the application can charge the payer automatically every period. */ // private BigDecimal amount; // /** Who is paying the fee (either "payer" for the person paying, "payee" for the person receiving the money, "payer_from_app" if payer is paying for app fee and the app is paying WePay fees, or "payee_from_app" if payee is paying for app fee and app is paying for WePay fees). */ // private FeePayer feePayer; // /** The state that the preapproval is in. See the object states page for the full list. */ // private State state; // /** The uri that the payer will be redirected to after approving the preapproval. */ // private String redirectUri; // /** The fee that will go to the API application's account (if set). Limited to 20% of the preapproval amount. */ // private BigDecimal appFee; // /** How often the API application can execute payments for a payer with this preapproval. Can be: hourly, daily, weekly, biweekly, monthly, bimonthly, quarterly, yearly, and once. Once period is if you only want to get authorization for a future charge and don't need it to be recurring. */ // private String period; // /** The number of times the API application can execute payments per period. */ // private Integer frequency; // /** When the API application can begin executing payments with this preapproval. Will be a unix timestamp. */ // private Long startTime; // /** The last time that the API application can execute a payment with this preapproval. Will be a unix timestamp. */ // private Long endTime; // /** The reference_id passed by the application (if set). */ // private String referenceId; // /** The uri which instant payment notifications will be sent to. */ // private String callbackUri; // /** The shipping address that the payer entered (if applicable). It will be in the following format: // // US Addresses: // {"address1":"380 Portage Ave","address2":"","city":"Palo Alto","state":"CA","zip":"94306","country":"US"}. // // Non-US Addresses: // {"address1":"100 Main St","address2":"","city":"Toronto","region":"ON","postcode":"M4E 1Z5","country":"CA"} // // Use ISO 3166-1 codes when specifying the country. // */ // private ShippingAddress address; // /** The amount that was paid in shipping fees (if any). */ // private BigDecimal shippingFee; // /** The dollar amount of taxes paid (if any). */ // private BigDecimal tax; // /** Whether or not the preapproval automatically executes the payments every period. */ // private boolean autoRecur; // /** The name of the payer. */ // private String payerName; // /** The email of the payer. */ // private String payeeEmail; // /** The unixtime when the preapproval was created. */ // private Long createTime; // /** The unixtime of the next scheduled charge +/- 5 minutes (will only show up for approved auto_recur preapprovals). */ // private Long nextDueTime; // /** The checkout ID of the last successful checkout (state captured) for the preapproval. */ // private Long lastCheckoutId; // /** The unixtime when the last successful checkout occurred. */ // private Long lastCheckoutTime; // } // Path: src/main/java/com/lookfirst/wepay/api/req/PreapprovalRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Preapproval; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/preapproval * * This call allows you to lookup the details of a payment preapproval on WePay. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class PreapprovalRequest extends WePayRequest<Preapproval> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/WithdrawalRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/Withdrawal.java // @Data // @EqualsAndHashCode(callSuper=false) // public class Withdrawal implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the withdrawal. */ // private Long withdrawalId; // /** The unique ID of the account that the money is coming from. */ // private Long accountId; // /** The state that the withdrawal is in See the section on payment states for a list of possible states. */ // private State state; // /** The uri that the account owner will return to after completing the withdrawal. Set to app homepage if not passed in /withdrawal/create. */ // private String redirectUri; // /** The uri that you will send the account owner to to complete the withdrawal. */ // private String withdrawalUri; // /** The uri that we will post notifications to each time the state on this withdrawal changes. */ // private String callbackUri; // /** The amount on money withdrawn from the WePay account to the bank account. */ // private BigDecimal amount; // /** The currency used, default "USD" ("USD" for now). */ // private String currency; // /** A short description for the reason of the withdrawal (255 characters). */ // private String note; // /** Whether the recipient of the money has been confirmed (for bank withdrawals this is the receiving bank account). */ // private boolean recipientConfirmed; // /** The type of withdrawal. Will be "check" for a sent paper check, or "ach" for a withdrawal to a bank account. */ // private WithdrawalType type; // /** The unixtime when the withdrawal was created. */ // private Long createTime; // /** The unixtime when the withdrawal was captured and credited to the payee's bank account. Returns 0 if withdrawal is not yet captured. */ // private Long captureTime; // }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Withdrawal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/withdrawal * * This call allows you to lookup the details of a withdrawal. * A withdrawal object represents the movement of money from a WePay account to a bank account. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/Withdrawal.java // @Data // @EqualsAndHashCode(callSuper=false) // public class Withdrawal implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the withdrawal. */ // private Long withdrawalId; // /** The unique ID of the account that the money is coming from. */ // private Long accountId; // /** The state that the withdrawal is in See the section on payment states for a list of possible states. */ // private State state; // /** The uri that the account owner will return to after completing the withdrawal. Set to app homepage if not passed in /withdrawal/create. */ // private String redirectUri; // /** The uri that you will send the account owner to to complete the withdrawal. */ // private String withdrawalUri; // /** The uri that we will post notifications to each time the state on this withdrawal changes. */ // private String callbackUri; // /** The amount on money withdrawn from the WePay account to the bank account. */ // private BigDecimal amount; // /** The currency used, default "USD" ("USD" for now). */ // private String currency; // /** A short description for the reason of the withdrawal (255 characters). */ // private String note; // /** Whether the recipient of the money has been confirmed (for bank withdrawals this is the receiving bank account). */ // private boolean recipientConfirmed; // /** The type of withdrawal. Will be "check" for a sent paper check, or "ach" for a withdrawal to a bank account. */ // private WithdrawalType type; // /** The unixtime when the withdrawal was created. */ // private Long createTime; // /** The unixtime when the withdrawal was captured and credited to the payee's bank account. Returns 0 if withdrawal is not yet captured. */ // private Long captureTime; // } // Path: src/main/java/com/lookfirst/wepay/api/req/WithdrawalRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.Withdrawal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/withdrawal * * This call allows you to lookup the details of a withdrawal. * A withdrawal object represents the movement of money from a WePay account to a bank account. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class WithdrawalRequest extends WePayRequest<Withdrawal> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // }
import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // }
import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */
private PaymentType type;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // }
import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */ private PaymentType type; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** The amount that the payer will pay. */ private BigDecimal amount; /** The currency used, default "USD" ("USD" for now). */ private String currency; /** The amount that the application will receive in fees. App fees go into the API applications WePay account. */ private BigDecimal appFee; /** Who will pay the fees (WePay's fees and any app fees). Set to "Payer" to charge fees to the person paying (Payer will pay amount + fees, payee will receive amount). Set to "Payee" to charge fees to the person receiving money (Payer will pay amount, Payee will receive amount - fees). Defaults to "Payer". */
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */ private PaymentType type; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** The amount that the payer will pay. */ private BigDecimal amount; /** The currency used, default "USD" ("USD" for now). */ private String currency; /** The amount that the application will receive in fees. App fees go into the API applications WePay account. */ private BigDecimal appFee; /** Who will pay the fees (WePay's fees and any app fees). Set to "Payer" to charge fees to the person paying (Payer will pay amount + fees, payee will receive amount). Set to "Payee" to charge fees to the person receiving money (Payer will pay amount, Payee will receive amount - fees). Defaults to "Payer". */
private FeePayer feePayer;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // }
import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */ private PaymentType type; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** The amount that the payer will pay. */ private BigDecimal amount; /** The currency used, default "USD" ("USD" for now). */ private String currency; /** The amount that the application will receive in fees. App fees go into the API applications WePay account. */ private BigDecimal appFee; /** Who will pay the fees (WePay's fees and any app fees). Set to "Payer" to charge fees to the person paying (Payer will pay amount + fees, payee will receive amount). Set to "Payee" to charge fees to the person receiving money (Payer will pay amount, Payee will receive amount - fees). Defaults to "Payer". */ private FeePayer feePayer; /** The uri the payer will be redirected to after paying. */ private String redirectUri; /** The uri that will receive any Instant Payment Notifications sent. Needs to be a full uri (ex https://www.wepay.com ) */ private String callbackUri; /** The uri that the payer will be redirected to if cookies cannot be set in the iframe; will only work if mode is iframe. */ private String fallbackUri; /** A boolean value (0 or 1). Default is 1. If set to 0 then the payment will not automatically be released to the account and will be held by WePay in payment state 'reserved'. To release funds to the account you must call /checkout/capture */ private boolean autoCapture; /** A boolean value (0 or 1). If set to 1 then the payer will be asked to enter a shipping address when they pay. After payment you can retrieve this shipping address by calling /checkout */ private boolean requireShipping; /** The amount that you want to charge for shipping. */ private BigDecimal shippingFee; /** A boolean value (0 or 1). If set to 1 and the account has a relevant tax entry (see /account/set_tax), then tax will be charged. */ private boolean chargeTax; /** What mode the checkout will be displayed in. The options are 'iframe' or 'regular'. Choose 'iframe' if this is an iframe checkout. Mode defaults to 'regular'. */
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */ private PaymentType type; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** The amount that the payer will pay. */ private BigDecimal amount; /** The currency used, default "USD" ("USD" for now). */ private String currency; /** The amount that the application will receive in fees. App fees go into the API applications WePay account. */ private BigDecimal appFee; /** Who will pay the fees (WePay's fees and any app fees). Set to "Payer" to charge fees to the person paying (Payer will pay amount + fees, payee will receive amount). Set to "Payee" to charge fees to the person receiving money (Payer will pay amount, Payee will receive amount - fees). Defaults to "Payer". */ private FeePayer feePayer; /** The uri the payer will be redirected to after paying. */ private String redirectUri; /** The uri that will receive any Instant Payment Notifications sent. Needs to be a full uri (ex https://www.wepay.com ) */ private String callbackUri; /** The uri that the payer will be redirected to if cookies cannot be set in the iframe; will only work if mode is iframe. */ private String fallbackUri; /** A boolean value (0 or 1). Default is 1. If set to 0 then the payment will not automatically be released to the account and will be held by WePay in payment state 'reserved'. To release funds to the account you must call /checkout/capture */ private boolean autoCapture; /** A boolean value (0 or 1). If set to 1 then the payer will be asked to enter a shipping address when they pay. After payment you can retrieve this shipping address by calling /checkout */ private boolean requireShipping; /** The amount that you want to charge for shipping. */ private BigDecimal shippingFee; /** A boolean value (0 or 1). If set to 1 and the account has a relevant tax entry (see /account/set_tax), then tax will be charged. */ private boolean chargeTax; /** What mode the checkout will be displayed in. The options are 'iframe' or 'regular'. Choose 'iframe' if this is an iframe checkout. Mode defaults to 'regular'. */
private Mode mode;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // }
import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */ private PaymentType type; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** The amount that the payer will pay. */ private BigDecimal amount; /** The currency used, default "USD" ("USD" for now). */ private String currency; /** The amount that the application will receive in fees. App fees go into the API applications WePay account. */ private BigDecimal appFee; /** Who will pay the fees (WePay's fees and any app fees). Set to "Payer" to charge fees to the person paying (Payer will pay amount + fees, payee will receive amount). Set to "Payee" to charge fees to the person receiving money (Payer will pay amount, Payee will receive amount - fees). Defaults to "Payer". */ private FeePayer feePayer; /** The uri the payer will be redirected to after paying. */ private String redirectUri; /** The uri that will receive any Instant Payment Notifications sent. Needs to be a full uri (ex https://www.wepay.com ) */ private String callbackUri; /** The uri that the payer will be redirected to if cookies cannot be set in the iframe; will only work if mode is iframe. */ private String fallbackUri; /** A boolean value (0 or 1). Default is 1. If set to 0 then the payment will not automatically be released to the account and will be held by WePay in payment state 'reserved'. To release funds to the account you must call /checkout/capture */ private boolean autoCapture; /** A boolean value (0 or 1). If set to 1 then the payer will be asked to enter a shipping address when they pay. After payment you can retrieve this shipping address by calling /checkout */ private boolean requireShipping; /** The amount that you want to charge for shipping. */ private BigDecimal shippingFee; /** A boolean value (0 or 1). If set to 1 and the account has a relevant tax entry (see /account/set_tax), then tax will be charged. */ private boolean chargeTax; /** What mode the checkout will be displayed in. The options are 'iframe' or 'regular'. Choose 'iframe' if this is an iframe checkout. Mode defaults to 'regular'. */ private Mode mode; /** The ID of a preapproval object. If you include a valid preapproval_id the checkout will be executed immediately, and the payer will be charged without having to go to the checkout_uri. You should not have to send the payer to the checkout_uri. */ private Long preapprovalId; /** A JSON object that lets you pre fill certain fields in the checkout. Allowed fields are 'name', 'email', 'phone_number', 'address', 'city', 'state', 'zip', Pass the prefill-info as a JSON object like so: {"name":"Bill Clerico","phone_number":"855-469-3729"} */
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutUri.java // @Data // @EqualsAndHashCode(callSuper=false) // public class CheckoutUri extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The uri you can send a user to so they can pay. */ // private String checkoutUri; // // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum PaymentType { GOODS, SERVICE, DONATION, EVENT, PERSONAL } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutCreateRequest.java import com.lookfirst.wepay.api.CheckoutUri; import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PaymentType; import com.lookfirst.wepay.api.Constants.PrefillInfo; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Creates a checkout for an account. The application can send a user to the checkout_uri so the user can pay the account for the amount specified. * NOTE: Checkouts will be expired 30 minutes after they are created if their is no activity on them (ie they were abandoned after creation). * * When the payer completes the payment, they will be returned to the redirect_uri you used in the /checkout/create call. * The checkout_id and the payment authorization code will be uri encoded in the redirect_uri so that you can confirm that the payment was made. * You can also use the Instant Payment Notifications system to receive push notifications of checkout state changes. * If you did not specify a redirect_uri, they will be returned to the application homepage. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutCreateRequest extends WePayRequest<CheckoutUri> { /** The unique ID of the account you want to create a checkout for. */ private Long accountId; /** A short description of what is being paid for. */ private String shortDescription; /** A long description of what is being paid for. */ private String longDescription; /** A short message that will be included in the payment confirmation email to the payer. */ private String payerEmailMessage; /** A short message that will be included in the payment confirmation email to the payee. */ private String payeeEmailMessage; /** Required. The the checkout type (one of the following: GOODS, SERVICE, DONATION, or PERSONAL) */ private PaymentType type; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** The amount that the payer will pay. */ private BigDecimal amount; /** The currency used, default "USD" ("USD" for now). */ private String currency; /** The amount that the application will receive in fees. App fees go into the API applications WePay account. */ private BigDecimal appFee; /** Who will pay the fees (WePay's fees and any app fees). Set to "Payer" to charge fees to the person paying (Payer will pay amount + fees, payee will receive amount). Set to "Payee" to charge fees to the person receiving money (Payer will pay amount, Payee will receive amount - fees). Defaults to "Payer". */ private FeePayer feePayer; /** The uri the payer will be redirected to after paying. */ private String redirectUri; /** The uri that will receive any Instant Payment Notifications sent. Needs to be a full uri (ex https://www.wepay.com ) */ private String callbackUri; /** The uri that the payer will be redirected to if cookies cannot be set in the iframe; will only work if mode is iframe. */ private String fallbackUri; /** A boolean value (0 or 1). Default is 1. If set to 0 then the payment will not automatically be released to the account and will be held by WePay in payment state 'reserved'. To release funds to the account you must call /checkout/capture */ private boolean autoCapture; /** A boolean value (0 or 1). If set to 1 then the payer will be asked to enter a shipping address when they pay. After payment you can retrieve this shipping address by calling /checkout */ private boolean requireShipping; /** The amount that you want to charge for shipping. */ private BigDecimal shippingFee; /** A boolean value (0 or 1). If set to 1 and the account has a relevant tax entry (see /account/set_tax), then tax will be charged. */ private boolean chargeTax; /** What mode the checkout will be displayed in. The options are 'iframe' or 'regular'. Choose 'iframe' if this is an iframe checkout. Mode defaults to 'regular'. */ private Mode mode; /** The ID of a preapproval object. If you include a valid preapproval_id the checkout will be executed immediately, and the payer will be charged without having to go to the checkout_uri. You should not have to send the payer to the checkout_uri. */ private Long preapprovalId; /** A JSON object that lets you pre fill certain fields in the checkout. Allowed fields are 'name', 'email', 'phone_number', 'address', 'city', 'state', 'zip', Pass the prefill-info as a JSON object like so: {"name":"Bill Clerico","phone_number":"855-469-3729"} */
private PrefillInfo prefillInfo;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/UserModifyRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/WePayUser.java // @Data // public class WePayUser implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the user. */ // private String userId; // /** The first name of the user */ // private String firstName; // /** The last name of the user */ // private String lastName; // /** The email of the user */ // private String email; // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // private String state; // // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // public boolean isRegistered() { // return state != null && state.equals("registered"); // } // }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.WePayUser;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/user * * This call allows you to add a callback_uri to the user object. * If you add a callback_uri you will receive IPNs with the user_id each * time the user revokes their access_token or is deleted. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/WePayUser.java // @Data // public class WePayUser implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the user. */ // private String userId; // /** The first name of the user */ // private String firstName; // /** The last name of the user */ // private String lastName; // /** The email of the user */ // private String email; // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // private String state; // // /** Either "registered" if the user has registered, or "pending" if the user still needs to confirm their registration */ // public boolean isRegistered() { // return state != null && state.equals("registered"); // } // } // Path: src/main/java/com/lookfirst/wepay/api/req/UserModifyRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.WePayUser; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/user * * This call allows you to add a callback_uri to the user object. * If you add a callback_uri you will receive IPNs with the user_id each * time the user revokes their access_token or is deleted. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class UserModifyRequest extends WePayRequest<WePayUser> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/PreapprovalCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // } // // Path: src/main/java/com/lookfirst/wepay/api/Preapproval.java // @Data // public class Preapproval implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the preapproval. */ // private Long preapprovalId; // /** The uri that you send the user to so they can enter their payment info and approve the preapproval. */ // private String preapprovalUri; // /** A uri that you can send the user to if they need to update their payment method. */ // private String manageUri; // /** The unique ID of the WePay account where the money will go. */ // private Long accountId; // // /** A short description of what the payer is being charged for. */ // private String shortDescription; // /** A longer description of what the payer is being charged for (if set). */ // private String longDescription; // // /** The currency that any charges will take place in (for now always USD). */ // private String currency; // /** The amount in dollars that the application can charge the payer automatically every period. */ // private BigDecimal amount; // /** Who is paying the fee (either "payer" for the person paying, "payee" for the person receiving the money, "payer_from_app" if payer is paying for app fee and the app is paying WePay fees, or "payee_from_app" if payee is paying for app fee and app is paying for WePay fees). */ // private FeePayer feePayer; // /** The state that the preapproval is in. See the object states page for the full list. */ // private State state; // /** The uri that the payer will be redirected to after approving the preapproval. */ // private String redirectUri; // /** The fee that will go to the API application's account (if set). Limited to 20% of the preapproval amount. */ // private BigDecimal appFee; // /** How often the API application can execute payments for a payer with this preapproval. Can be: hourly, daily, weekly, biweekly, monthly, bimonthly, quarterly, yearly, and once. Once period is if you only want to get authorization for a future charge and don't need it to be recurring. */ // private String period; // /** The number of times the API application can execute payments per period. */ // private Integer frequency; // /** When the API application can begin executing payments with this preapproval. Will be a unix timestamp. */ // private Long startTime; // /** The last time that the API application can execute a payment with this preapproval. Will be a unix timestamp. */ // private Long endTime; // /** The reference_id passed by the application (if set). */ // private String referenceId; // /** The uri which instant payment notifications will be sent to. */ // private String callbackUri; // /** The shipping address that the payer entered (if applicable). It will be in the following format: // // US Addresses: // {"address1":"380 Portage Ave","address2":"","city":"Palo Alto","state":"CA","zip":"94306","country":"US"}. // // Non-US Addresses: // {"address1":"100 Main St","address2":"","city":"Toronto","region":"ON","postcode":"M4E 1Z5","country":"CA"} // // Use ISO 3166-1 codes when specifying the country. // */ // private ShippingAddress address; // /** The amount that was paid in shipping fees (if any). */ // private BigDecimal shippingFee; // /** The dollar amount of taxes paid (if any). */ // private BigDecimal tax; // /** Whether or not the preapproval automatically executes the payments every period. */ // private boolean autoRecur; // /** The name of the payer. */ // private String payerName; // /** The email of the payer. */ // private String payeeEmail; // /** The unixtime when the preapproval was created. */ // private Long createTime; // /** The unixtime of the next scheduled charge +/- 5 minutes (will only show up for approved auto_recur preapprovals). */ // private Long nextDueTime; // /** The checkout ID of the last successful checkout (state captured) for the preapproval. */ // private Long lastCheckoutId; // /** The unixtime when the last successful checkout occurred. */ // private Long lastCheckoutTime; // }
import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PrefillInfo; import com.lookfirst.wepay.api.Preapproval; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/preapproval * * Creates a new payment preapproval request object for the user associated * with the access token used to make this call. If reference_id is passed, * it MUST be unique for the application/user pair or an error will be returned. * * To make the payments execute automatically every month, set auto_recur to true. * If you set auto_recur to true, then the first payment will execute at the * start_time for that preapproval. If you do not pass a start_time in the * /preapproval/create call, then the start_time will default to the time that * /preapproval/create was called. The payments will then automatically execute * every period after the start_time. So if you set the start_time to January * 20th, then the first payment will occur on January 20th, and the next payment * will occur on February 20th, and so on. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum FeePayer { payer, payee, payer_from_app, payee_from_app } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum Mode { iframe, regular } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // @Data // public static class PrefillInfo { // String name; // String email; // String phoneNumber; // String address; // String city; // String state; // String zip; // String country; // String region; // String postcode; // } // // Path: src/main/java/com/lookfirst/wepay/api/Preapproval.java // @Data // public class Preapproval implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the preapproval. */ // private Long preapprovalId; // /** The uri that you send the user to so they can enter their payment info and approve the preapproval. */ // private String preapprovalUri; // /** A uri that you can send the user to if they need to update their payment method. */ // private String manageUri; // /** The unique ID of the WePay account where the money will go. */ // private Long accountId; // // /** A short description of what the payer is being charged for. */ // private String shortDescription; // /** A longer description of what the payer is being charged for (if set). */ // private String longDescription; // // /** The currency that any charges will take place in (for now always USD). */ // private String currency; // /** The amount in dollars that the application can charge the payer automatically every period. */ // private BigDecimal amount; // /** Who is paying the fee (either "payer" for the person paying, "payee" for the person receiving the money, "payer_from_app" if payer is paying for app fee and the app is paying WePay fees, or "payee_from_app" if payee is paying for app fee and app is paying for WePay fees). */ // private FeePayer feePayer; // /** The state that the preapproval is in. See the object states page for the full list. */ // private State state; // /** The uri that the payer will be redirected to after approving the preapproval. */ // private String redirectUri; // /** The fee that will go to the API application's account (if set). Limited to 20% of the preapproval amount. */ // private BigDecimal appFee; // /** How often the API application can execute payments for a payer with this preapproval. Can be: hourly, daily, weekly, biweekly, monthly, bimonthly, quarterly, yearly, and once. Once period is if you only want to get authorization for a future charge and don't need it to be recurring. */ // private String period; // /** The number of times the API application can execute payments per period. */ // private Integer frequency; // /** When the API application can begin executing payments with this preapproval. Will be a unix timestamp. */ // private Long startTime; // /** The last time that the API application can execute a payment with this preapproval. Will be a unix timestamp. */ // private Long endTime; // /** The reference_id passed by the application (if set). */ // private String referenceId; // /** The uri which instant payment notifications will be sent to. */ // private String callbackUri; // /** The shipping address that the payer entered (if applicable). It will be in the following format: // // US Addresses: // {"address1":"380 Portage Ave","address2":"","city":"Palo Alto","state":"CA","zip":"94306","country":"US"}. // // Non-US Addresses: // {"address1":"100 Main St","address2":"","city":"Toronto","region":"ON","postcode":"M4E 1Z5","country":"CA"} // // Use ISO 3166-1 codes when specifying the country. // */ // private ShippingAddress address; // /** The amount that was paid in shipping fees (if any). */ // private BigDecimal shippingFee; // /** The dollar amount of taxes paid (if any). */ // private BigDecimal tax; // /** Whether or not the preapproval automatically executes the payments every period. */ // private boolean autoRecur; // /** The name of the payer. */ // private String payerName; // /** The email of the payer. */ // private String payeeEmail; // /** The unixtime when the preapproval was created. */ // private Long createTime; // /** The unixtime of the next scheduled charge +/- 5 minutes (will only show up for approved auto_recur preapprovals). */ // private Long nextDueTime; // /** The checkout ID of the last successful checkout (state captured) for the preapproval. */ // private Long lastCheckoutId; // /** The unixtime when the last successful checkout occurred. */ // private Long lastCheckoutTime; // } // Path: src/main/java/com/lookfirst/wepay/api/req/PreapprovalCreateRequest.java import com.lookfirst.wepay.api.Constants.FeePayer; import com.lookfirst.wepay.api.Constants.Mode; import com.lookfirst.wepay.api.Constants.PrefillInfo; import com.lookfirst.wepay.api.Preapproval; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/preapproval * * Creates a new payment preapproval request object for the user associated * with the access token used to make this call. If reference_id is passed, * it MUST be unique for the application/user pair or an error will be returned. * * To make the payments execute automatically every month, set auto_recur to true. * If you set auto_recur to true, then the first payment will execute at the * start_time for that preapproval. If you do not pass a start_time in the * /preapproval/create call, then the start_time will default to the time that * /preapproval/create was called. The payments will then automatically execute * every period after the start_time. So if you set the start_time to January * 20th, then the first payment will occur on January 20th, and the next payment * will occur on February 20th, and so on. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class PreapprovalCreateRequest extends WePayRequest<Preapproval> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // }
import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/batch * * Creates a batch call that will allow you to make multiple API calls within a single API call. * Each call will have a reference_id that can be used to identify that call. In addition, an * access_token will be passed for each call in the list, allowing you to make batch API calls for multiple users. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/batch * * Creates a batch call that will allow you to make multiple API calls within a single API call. * Each call will have a reference_id that can be used to identify that call. In addition, an * access_token will be passed for each call in the list, allowing you to make batch API calls for multiple users. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class BatchCreateRequest extends WePayRequest<Calls> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // }
import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/batch * * Creates a batch call that will allow you to make multiple API calls within a single API call. * Each call will have a reference_id that can be used to identify that call. In addition, an * access_token will be passed for each call in the list, allowing you to make batch API calls for multiple users. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class BatchCreateRequest extends WePayRequest<Calls> { /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ private Long clientId; /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ private String clientSecret; /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, * an "authorization" parameter -- access token for the user that is making the API call, a unique * "reference_id", and an array of the "parameters" for the API call. */
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/batch * * Creates a batch call that will allow you to make multiple API calls within a single API call. * Each call will have a reference_id that can be used to identify that call. In addition, an * access_token will be passed for each call in the list, allowing you to make batch API calls for multiple users. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class BatchCreateRequest extends WePayRequest<Calls> { /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ private Long clientId; /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ private String clientSecret; /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, * an "authorization" parameter -- access token for the user that is making the API call, a unique * "reference_id", and an array of the "parameters" for the API call. */
private List<Call> calls;
lookfirst/WePay-Java-SDK
src/test/java/com/lookfirst/wepay/BatchTest.java
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // }
import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List;
@BeforeTest private void setup() { key = new WePayKey(false, 123L, "secret"); } public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}";
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // } // Path: src/test/java/com/lookfirst/wepay/BatchTest.java import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List; @BeforeTest private void setup() { key = new WePayKey(false, 123L, "secret"); } public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}";
WePayApi api = new WePayApi(key, new FakeDataProvider(response));
lookfirst/WePay-Java-SDK
src/test/java/com/lookfirst/wepay/BatchTest.java
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // }
import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List;
private void setup() { key = new WePayKey(false, 123L, "secret"); } public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}"; WePayApi api = new WePayApi(key, new FakeDataProvider(response));
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // } // Path: src/test/java/com/lookfirst/wepay/BatchTest.java import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List; private void setup() { key = new WePayKey(false, 123L, "secret"); } public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}"; WePayApi api = new WePayApi(key, new FakeDataProvider(response));
BatchCreateRequest batch = new BatchCreateRequest();
lookfirst/WePay-Java-SDK
src/test/java/com/lookfirst/wepay/BatchTest.java
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // }
import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List;
key = new WePayKey(false, 123L, "secret"); } public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}"; WePayApi api = new WePayApi(key, new FakeDataProvider(response)); BatchCreateRequest batch = new BatchCreateRequest();
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // } // Path: src/test/java/com/lookfirst/wepay/BatchTest.java import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List; key = new WePayKey(false, 123L, "secret"); } public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}"; WePayApi api = new WePayApi(key, new FakeDataProvider(response)); BatchCreateRequest batch = new BatchCreateRequest();
Calls calls = api.execute("token", batch);
lookfirst/WePay-Java-SDK
src/test/java/com/lookfirst/wepay/BatchTest.java
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // }
import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List;
} public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}"; WePayApi api = new WePayApi(key, new FakeDataProvider(response)); BatchCreateRequest batch = new BatchCreateRequest(); Calls calls = api.execute("token", batch);
// Path: src/main/java/com/lookfirst/wepay/api/Call.java // @Data // public class Call implements Serializable { // private static final long serialVersionUID = 1L; // // /** The name of the API call you want to make (ie. /checkout/find). */ // private String call; // // /** The access token of the user that is making the API call. */ // private String authorization; // // /** A unique id that you can attach to an API call so that you can specifically identify that call. */ // private String referenceId; // // /** The parameters required by the API call that you specified in the "call" parameter. */ // private Map<String, String> parameters; // } // // Path: src/main/java/com/lookfirst/wepay/api/Calls.java // @Data // public class Calls implements Serializable { // private static final long serialVersionUID = 1L; // // @JsonProperty // private List<Call> calls; // } // // Path: src/main/java/com/lookfirst/wepay/api/req/BatchCreateRequest.java // @Data // @EqualsAndHashCode(callSuper=false) // public class BatchCreateRequest extends WePayRequest<Calls> { // // /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ // private Long clientId; // // /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ // private String clientSecret; // // /** An array of the API calls that you would like to make. Each API call should have a "call" parameter, // * an "authorization" parameter -- access token for the user that is making the API call, a unique // * "reference_id", and an array of the "parameters" for the API call. */ // private List<Call> calls; // // /** */ // @Override // public String getEndpoint() { // return "/batch/create"; // } // } // // Path: src/test/java/com/lookfirst/wepay/util/FakeDataProvider.java // @AllArgsConstructor // public class FakeDataProvider implements DataProvider { // @NonNull // final String data; // // @Override // public InputStream getData(String uri, String postJson, String token) throws IOException { // return new ByteArrayInputStream(data.getBytes()); // } // } // Path: src/test/java/com/lookfirst/wepay/BatchTest.java import com.lookfirst.wepay.api.Call; import com.lookfirst.wepay.api.Calls; import com.lookfirst.wepay.api.req.BatchCreateRequest; import com.lookfirst.wepay.util.FakeDataProvider; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.List; } public void testBatch() throws Exception { String response = "{\n" + " \"calls\": [\n" + " {\n" + " \"call\":\"/user\",\n" + " \"reference_id\":\"1341351\",\n" + " \"response\":{\n" + " \"user_id\":54312,\n" + " \"email\":\"test@example.com\",\n" + " \"first_name\":\"bob\",\n" + " \"last_name\":\"smith\"\n" + " }\n" + " },\n" + " {\n" + " \"call\":\"/checkout/create\",\n" + " \"reference_id\":\"23535111\",\n" + " \"response\":{\n" + " \"error\":\"access_denied\",\n" + " \"error_description\":\"this account can no longer transact\",\n" + " \"error_code\":3004\n" + " }\n" + " }\n" + " ]\n" + "}"; WePayApi api = new WePayApi(key, new FakeDataProvider(response)); BatchCreateRequest batch = new BatchCreateRequest(); Calls calls = api.execute("token", batch);
List<Call> callList = calls.getCalls();
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutRefundRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutState.java // @Data // @EqualsAndHashCode(callSuper=true) // public class CheckoutState extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The state the payment is in. See the IPN section for a list of payment states. */ // private State state; // }
import java.math.BigDecimal; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutState;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Refunds the payment associated with the checkout created by the application. Checkout must be in "reserved" or "captured" state. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutState.java // @Data // @EqualsAndHashCode(callSuper=true) // public class CheckoutState extends CheckoutId { // private static final long serialVersionUID = 1L; // // /** The state the payment is in. See the IPN section for a list of payment states. */ // private State state; // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutRefundRequest.java import java.math.BigDecimal; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutState; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * Refunds the payment associated with the checkout created by the application. Checkout must be in "reserved" or "captured" state. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class CheckoutRefundRequest extends WePayRequest<CheckoutState> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CreditCardFindRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CreditCard.java // @Data // public class CreditCard implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the credit_card. */ // public String creditCardId; // /** The string that identifies the credit_card such as MasterCard xxxxxx4769. */ // public String creditCardName; // /** The state that the credit card is in. */ // public String state; // /** The name on the card (ie "Bob Smith"). */ // public String userName; // /** The email address of the user who owns the card. */ // public String email; // /** The unique reference ID of the account (this is set by the application in the /account/create or /account/modify call). */ // public String referenceId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CreditCard; import com.lookfirst.wepay.api.Constants.SortOrder;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/credit_card * * This call allows you to lookup the details of the a credit card that you have tokenized. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/CreditCard.java // @Data // public class CreditCard implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the credit_card. */ // public String creditCardId; // /** The string that identifies the credit_card such as MasterCard xxxxxx4769. */ // public String creditCardName; // /** The state that the credit card is in. */ // public String state; // /** The name on the card (ie "Bob Smith"). */ // public String userName; // /** The email address of the user who owns the card. */ // public String email; // /** The unique reference ID of the account (this is set by the application in the /account/create or /account/modify call). */ // public String referenceId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // Path: src/main/java/com/lookfirst/wepay/api/req/CreditCardFindRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CreditCard; import com.lookfirst.wepay.api.Constants.SortOrder; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/credit_card * * This call allows you to lookup the details of the a credit card that you have tokenized. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class CreditCardFindRequest extends WePayRequest<CreditCard> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CreditCardFindRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CreditCard.java // @Data // public class CreditCard implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the credit_card. */ // public String creditCardId; // /** The string that identifies the credit_card such as MasterCard xxxxxx4769. */ // public String creditCardName; // /** The state that the credit card is in. */ // public String state; // /** The name on the card (ie "Bob Smith"). */ // public String userName; // /** The email address of the user who owns the card. */ // public String email; // /** The unique reference ID of the account (this is set by the application in the /account/create or /account/modify call). */ // public String referenceId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC }
import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CreditCard; import com.lookfirst.wepay.api.Constants.SortOrder;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/credit_card * * This call allows you to lookup the details of the a credit card that you have tokenized. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CreditCardFindRequest extends WePayRequest<CreditCard> { /** The ID your your API application. You can find it on your app dashboard. */ private Long clientId; /** The secret for your API application. You can find it on your app dashboard. */ private String clientSecret; /** The unique ID of the credit_card you want to look up. */ private Long creditCardId; /** The reference ID of the credit_card you want to find. */ private String referenceId; /** The maximum number of results you want returned. Defaults to 50. */ private Integer limit; /** The start position for your search (default 0). */ private Integer start; /** Sort the results of the search by time created. Use 'DESC' for most recent to least recent. Use 'ASC' for least recent to most recent. Defaults to 'DESC'. */
// Path: src/main/java/com/lookfirst/wepay/api/CreditCard.java // @Data // public class CreditCard implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the credit_card. */ // public String creditCardId; // /** The string that identifies the credit_card such as MasterCard xxxxxx4769. */ // public String creditCardName; // /** The state that the credit card is in. */ // public String state; // /** The name on the card (ie "Bob Smith"). */ // public String userName; // /** The email address of the user who owns the card. */ // public String email; // /** The unique reference ID of the account (this is set by the application in the /account/create or /account/modify call). */ // public String referenceId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // Path: src/main/java/com/lookfirst/wepay/api/req/CreditCardFindRequest.java import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CreditCard; import com.lookfirst.wepay.api.Constants.SortOrder; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/credit_card * * This call allows you to lookup the details of the a credit card that you have tokenized. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CreditCardFindRequest extends WePayRequest<CreditCard> { /** The ID your your API application. You can find it on your app dashboard. */ private Long clientId; /** The secret for your API application. You can find it on your app dashboard. */ private String clientSecret; /** The unique ID of the credit_card you want to look up. */ private Long creditCardId; /** The reference ID of the credit_card you want to find. */ private String referenceId; /** The maximum number of results you want returned. Defaults to 50. */ private Integer limit; /** The start position for your search (default 0). */ private Integer start; /** Sort the results of the search by time created. Use 'DESC' for most recent to least recent. Use 'ASC' for least recent to most recent. Defaults to 'DESC'. */
private SortOrder sortOrder;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/AppModifyRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/AppUri.java // @Data // public class AppUri implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the app. */ // private String clientId; // /** The approval status of the API application. */ // private String status; // /** The theme object associated with the App (if applicable). */ // private ThemeObject themeObject; // /** An array of Google Analytics domains associated with the app. */ // private List<String> gaqDomains; // } // // Path: src/main/java/com/lookfirst/wepay/api/ThemeObject.java // @Data // public class ThemeObject implements Serializable { // private static final long serialVersionUID = 1L; // // /** Sets a name for the theme */ // public String name; // /** Sets colors on important elements such as headers */ // public String primaryColor; // /** Sets colors on secondary elements such as info boxes, and the focus styles on text inputs */ // public String secondaryColor; // /** Sets the background color for the page frame on onsite pages, and the iframe background on iframe checkouts */ // public String backgroundColor; // /** Sets the color on primary action buttons */ // public String buttonColor; // }
import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.AppUri; import com.lookfirst.wepay.api.ThemeObject;
package com.lookfirst.wepay.api.req; /** * https://www.wepay.com/developer/reference/app * * This call lets you modify details of your API application (such as adding a theme for your app). * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/AppUri.java // @Data // public class AppUri implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the app. */ // private String clientId; // /** The approval status of the API application. */ // private String status; // /** The theme object associated with the App (if applicable). */ // private ThemeObject themeObject; // /** An array of Google Analytics domains associated with the app. */ // private List<String> gaqDomains; // } // // Path: src/main/java/com/lookfirst/wepay/api/ThemeObject.java // @Data // public class ThemeObject implements Serializable { // private static final long serialVersionUID = 1L; // // /** Sets a name for the theme */ // public String name; // /** Sets colors on important elements such as headers */ // public String primaryColor; // /** Sets colors on secondary elements such as info boxes, and the focus styles on text inputs */ // public String secondaryColor; // /** Sets the background color for the page frame on onsite pages, and the iframe background on iframe checkouts */ // public String backgroundColor; // /** Sets the color on primary action buttons */ // public String buttonColor; // } // Path: src/main/java/com/lookfirst/wepay/api/req/AppModifyRequest.java import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.AppUri; import com.lookfirst.wepay.api.ThemeObject; package com.lookfirst.wepay.api.req; /** * https://www.wepay.com/developer/reference/app * * This call lets you modify details of your API application (such as adding a theme for your app). * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class AppModifyRequest extends WePayRequest<AppUri> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/AppModifyRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/AppUri.java // @Data // public class AppUri implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the app. */ // private String clientId; // /** The approval status of the API application. */ // private String status; // /** The theme object associated with the App (if applicable). */ // private ThemeObject themeObject; // /** An array of Google Analytics domains associated with the app. */ // private List<String> gaqDomains; // } // // Path: src/main/java/com/lookfirst/wepay/api/ThemeObject.java // @Data // public class ThemeObject implements Serializable { // private static final long serialVersionUID = 1L; // // /** Sets a name for the theme */ // public String name; // /** Sets colors on important elements such as headers */ // public String primaryColor; // /** Sets colors on secondary elements such as info boxes, and the focus styles on text inputs */ // public String secondaryColor; // /** Sets the background color for the page frame on onsite pages, and the iframe background on iframe checkouts */ // public String backgroundColor; // /** Sets the color on primary action buttons */ // public String buttonColor; // }
import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.AppUri; import com.lookfirst.wepay.api.ThemeObject;
package com.lookfirst.wepay.api.req; /** * https://www.wepay.com/developer/reference/app * * This call lets you modify details of your API application (such as adding a theme for your app). * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class AppModifyRequest extends WePayRequest<AppUri> { /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ private String clientId; /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ private String clientSecret; /** The theme object associated with the App (if applicable). */
// Path: src/main/java/com/lookfirst/wepay/api/AppUri.java // @Data // public class AppUri implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the app. */ // private String clientId; // /** The approval status of the API application. */ // private String status; // /** The theme object associated with the App (if applicable). */ // private ThemeObject themeObject; // /** An array of Google Analytics domains associated with the app. */ // private List<String> gaqDomains; // } // // Path: src/main/java/com/lookfirst/wepay/api/ThemeObject.java // @Data // public class ThemeObject implements Serializable { // private static final long serialVersionUID = 1L; // // /** Sets a name for the theme */ // public String name; // /** Sets colors on important elements such as headers */ // public String primaryColor; // /** Sets colors on secondary elements such as info boxes, and the focus styles on text inputs */ // public String secondaryColor; // /** Sets the background color for the page frame on onsite pages, and the iframe background on iframe checkouts */ // public String backgroundColor; // /** Sets the color on primary action buttons */ // public String buttonColor; // } // Path: src/main/java/com/lookfirst/wepay/api/req/AppModifyRequest.java import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.AppUri; import com.lookfirst.wepay.api.ThemeObject; package com.lookfirst.wepay.api.req; /** * https://www.wepay.com/developer/reference/app * * This call lets you modify details of your API application (such as adding a theme for your app). * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class AppModifyRequest extends WePayRequest<AppUri> { /** The integer client ID issued to the app by WePay - see your client ID on your app screen. */ private String clientId; /** The string client secret issued to the app by WePay - see your client secret on your app screen. */ private String clientSecret; /** The theme object associated with the App (if applicable). */
private ThemeObject themeObject;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutFindRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutId.java // @Data // public class CheckoutId implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the checkout */ // private Long checkoutId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum State { // action_required { // @Override // public String toString() { return "action required"; } // }, // active, // approved, // authorized, // available, // cancelled, // captured, // charged_back { // @Override // public String toString() { return "charged back"; } // }, // completed, // deleted, // disabled, // ended, // expired, // failed, // invalid, // new_ { // @Override // public String toString() { return "new"; } // }, // pending, // refunded, // registered, // reserved, // retrying, // revoked, // settled, // started, // stopped, // transition, // trial // }
import java.math.BigDecimal; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutId; import com.lookfirst.wepay.api.Constants.SortOrder; import com.lookfirst.wepay.api.Constants.State;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * This call allows you to search for checkouts associated with an account. Returns an array of matching checkout IDs. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutId.java // @Data // public class CheckoutId implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the checkout */ // private Long checkoutId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum State { // action_required { // @Override // public String toString() { return "action required"; } // }, // active, // approved, // authorized, // available, // cancelled, // captured, // charged_back { // @Override // public String toString() { return "charged back"; } // }, // completed, // deleted, // disabled, // ended, // expired, // failed, // invalid, // new_ { // @Override // public String toString() { return "new"; } // }, // pending, // refunded, // registered, // reserved, // retrying, // revoked, // settled, // started, // stopped, // transition, // trial // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutFindRequest.java import java.math.BigDecimal; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutId; import com.lookfirst.wepay.api.Constants.SortOrder; import com.lookfirst.wepay.api.Constants.State; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * This call allows you to search for checkouts associated with an account. Returns an array of matching checkout IDs. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class CheckoutFindRequest extends WePayRequest<List<CheckoutId>> {
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutFindRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutId.java // @Data // public class CheckoutId implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the checkout */ // private Long checkoutId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum State { // action_required { // @Override // public String toString() { return "action required"; } // }, // active, // approved, // authorized, // available, // cancelled, // captured, // charged_back { // @Override // public String toString() { return "charged back"; } // }, // completed, // deleted, // disabled, // ended, // expired, // failed, // invalid, // new_ { // @Override // public String toString() { return "new"; } // }, // pending, // refunded, // registered, // reserved, // retrying, // revoked, // settled, // started, // stopped, // transition, // trial // }
import java.math.BigDecimal; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutId; import com.lookfirst.wepay.api.Constants.SortOrder; import com.lookfirst.wepay.api.Constants.State;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * This call allows you to search for checkouts associated with an account. Returns an array of matching checkout IDs. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutFindRequest extends WePayRequest<List<CheckoutId>> { /** The unique ID of the account whose checkouts you are searching. */ private Long accountId; /** The start position for your search (default 0). */ private Integer start; /** The maximum number of returned entries (default 50). */ private Integer limit; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** What state the checkout is in (see the Instant Payment Notifications reference for details). */
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutId.java // @Data // public class CheckoutId implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the checkout */ // private Long checkoutId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum State { // action_required { // @Override // public String toString() { return "action required"; } // }, // active, // approved, // authorized, // available, // cancelled, // captured, // charged_back { // @Override // public String toString() { return "charged back"; } // }, // completed, // deleted, // disabled, // ended, // expired, // failed, // invalid, // new_ { // @Override // public String toString() { return "new"; } // }, // pending, // refunded, // registered, // reserved, // retrying, // revoked, // settled, // started, // stopped, // transition, // trial // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutFindRequest.java import java.math.BigDecimal; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutId; import com.lookfirst.wepay.api.Constants.SortOrder; import com.lookfirst.wepay.api.Constants.State; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * This call allows you to search for checkouts associated with an account. Returns an array of matching checkout IDs. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutFindRequest extends WePayRequest<List<CheckoutId>> { /** The unique ID of the account whose checkouts you are searching. */ private Long accountId; /** The start position for your search (default 0). */ private Integer start; /** The maximum number of returned entries (default 50). */ private Integer limit; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** What state the checkout is in (see the Instant Payment Notifications reference for details). */
private State state;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/CheckoutFindRequest.java
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutId.java // @Data // public class CheckoutId implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the checkout */ // private Long checkoutId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum State { // action_required { // @Override // public String toString() { return "action required"; } // }, // active, // approved, // authorized, // available, // cancelled, // captured, // charged_back { // @Override // public String toString() { return "charged back"; } // }, // completed, // deleted, // disabled, // ended, // expired, // failed, // invalid, // new_ { // @Override // public String toString() { return "new"; } // }, // pending, // refunded, // registered, // reserved, // retrying, // revoked, // settled, // started, // stopped, // transition, // trial // }
import java.math.BigDecimal; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutId; import com.lookfirst.wepay.api.Constants.SortOrder; import com.lookfirst.wepay.api.Constants.State;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * This call allows you to search for checkouts associated with an account. Returns an array of matching checkout IDs. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutFindRequest extends WePayRequest<List<CheckoutId>> { /** The unique ID of the account whose checkouts you are searching. */ private Long accountId; /** The start position for your search (default 0). */ private Integer start; /** The maximum number of returned entries (default 50). */ private Integer limit; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** What state the checkout is in (see the Instant Payment Notifications reference for details). */ private State state; /** The ID of the preapproval that was used to create the checkout. Useful if you want to look up all of the payments for an auto_recurring preapproval. */ private Integer preapprovalId; /** All checkouts after given start time. Can be a unix_timestamp or a valid, parse-able date-time. */ private String startTime; /** All checkouts before given end time. Can be a unix_timestamp or a valid, parse-able date-time. */ private String endTime; /** Sort the results of the search by time created. Use 'DESC' for most recent to least recent. Use 'ASC' for least recent to most recent. Defaults to 'DESC'. */
// Path: src/main/java/com/lookfirst/wepay/api/CheckoutId.java // @Data // public class CheckoutId implements Serializable { // private static final long serialVersionUID = 1L; // // /** The unique ID of the checkout */ // private Long checkoutId; // } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum SortOrder { ASC, DESC } // // Path: src/main/java/com/lookfirst/wepay/api/Constants.java // public static enum State { // action_required { // @Override // public String toString() { return "action required"; } // }, // active, // approved, // authorized, // available, // cancelled, // captured, // charged_back { // @Override // public String toString() { return "charged back"; } // }, // completed, // deleted, // disabled, // ended, // expired, // failed, // invalid, // new_ { // @Override // public String toString() { return "new"; } // }, // pending, // refunded, // registered, // reserved, // retrying, // revoked, // settled, // started, // stopped, // transition, // trial // } // Path: src/main/java/com/lookfirst/wepay/api/req/CheckoutFindRequest.java import java.math.BigDecimal; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import com.lookfirst.wepay.api.CheckoutId; import com.lookfirst.wepay.api.Constants.SortOrder; import com.lookfirst.wepay.api.Constants.State; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/checkout * * This call allows you to search for checkouts associated with an account. Returns an array of matching checkout IDs. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false) public class CheckoutFindRequest extends WePayRequest<List<CheckoutId>> { /** The unique ID of the account whose checkouts you are searching. */ private Long accountId; /** The start position for your search (default 0). */ private Integer start; /** The maximum number of returned entries (default 50). */ private Integer limit; /** The unique reference id of the checkout (set by the application in /checkout/create */ private String referenceId; /** What state the checkout is in (see the Instant Payment Notifications reference for details). */ private State state; /** The ID of the preapproval that was used to create the checkout. Useful if you want to look up all of the payments for an auto_recurring preapproval. */ private Integer preapprovalId; /** All checkouts after given start time. Can be a unix_timestamp or a valid, parse-able date-time. */ private String startTime; /** All checkouts before given end time. Can be a unix_timestamp or a valid, parse-able date-time. */ private String endTime; /** Sort the results of the search by time created. Use 'DESC' for most recent to least recent. Use 'ASC' for least recent to most recent. Defaults to 'DESC'. */
private SortOrder sortOrder;
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/api/req/AccountGetUpdateUri.java
// Path: src/main/java/com/lookfirst/wepay/api/AccountUri.java // @Data // @EqualsAndHashCode(callSuper=true) // public class AccountUri extends AccountId { // private static final long serialVersionUID = 1L; // // /** The URI to add or update info for the specified account id. Do not store the returned URI on your side as it can change. */ // private String uri; // }
import com.lookfirst.wepay.api.AccountUri; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/account * * This call allows you to add or update all incomplete items for an account like KYC info, bank account, etc. It will return a URL that a user can visit to update info for his or her account. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lookfirst/wepay/api/AccountUri.java // @Data // @EqualsAndHashCode(callSuper=true) // public class AccountUri extends AccountId { // private static final long serialVersionUID = 1L; // // /** The URI to add or update info for the specified account id. Do not store the returned URI on your side as it can change. */ // private String uri; // } // Path: src/main/java/com/lookfirst/wepay/api/req/AccountGetUpdateUri.java import com.lookfirst.wepay.api.AccountUri; import lombok.Data; import lombok.EqualsAndHashCode; package com.lookfirst.wepay.api.req; /** * https://stage.wepay.com/developer/reference/account * * This call allows you to add or update all incomplete items for an account like KYC info, bank account, etc. It will return a URL that a user can visit to update info for his or her account. * * @author Jon Scott Stevens * @author Jeff Schnitzer */ @Data @EqualsAndHashCode(callSuper=false)
public class AccountGetUpdateUri extends WePayRequest<AccountUri> {
angelozerr/angularjs-eclipse
org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/dialogs/OpenAngularElementSelectionDialog.java
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIPlugin.java // public class AngularUIPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.angularjs.ui"; //$NON-NLS-1$ // // // The shared instance // private static AngularUIPlugin plugin; // // /** // * The constructor // */ // public AngularUIPlugin() { // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static AngularUIPlugin getDefault() { // return plugin; // } // // public static IWorkbenchWindow getActiveWorkbenchWindow() { // return getDefault().getWorkbench().getActiveWorkbenchWindow(); // } // // public static Shell getActiveWorkbenchShell() { // IWorkbenchWindow window = getActiveWorkbenchWindow(); // if (window != null) { // return window.getShell(); // } // return null; // } // // /** // * @return Returns the active workbench window's currrent page. // */ // public static IWorkbenchPage getActivePage() { // return getActiveWorkbenchWindow().getActivePage(); // } // // }
import org.eclipse.angularjs.internal.ui.AngularUIPlugin; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.swt.widgets.Shell;
/** * Copyright (c) 2013-2015 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.dialogs; /** * An Angular Element selection dialog used for opening Angular Elements. */ public class OpenAngularElementSelectionDialog extends FilteredAngularElementsSelectionDialog { private static final String DIALOG_SETTINGS = "org.eclipse.angularjs.internal.ui.dialogs.OpenAngularElementSelectionDialog"; //$NON-NLS-1$ public OpenAngularElementSelectionDialog(Shell shell, boolean multi) { super(shell, multi); } @Override protected IDialogSettings getDialogSettings() {
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIPlugin.java // public class AngularUIPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.angularjs.ui"; //$NON-NLS-1$ // // // The shared instance // private static AngularUIPlugin plugin; // // /** // * The constructor // */ // public AngularUIPlugin() { // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static AngularUIPlugin getDefault() { // return plugin; // } // // public static IWorkbenchWindow getActiveWorkbenchWindow() { // return getDefault().getWorkbench().getActiveWorkbenchWindow(); // } // // public static Shell getActiveWorkbenchShell() { // IWorkbenchWindow window = getActiveWorkbenchWindow(); // if (window != null) { // return window.getShell(); // } // return null; // } // // /** // * @return Returns the active workbench window's currrent page. // */ // public static IWorkbenchPage getActivePage() { // return getActiveWorkbenchWindow().getActivePage(); // } // // } // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/dialogs/OpenAngularElementSelectionDialog.java import org.eclipse.angularjs.internal.ui.AngularUIPlugin; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.swt.widgets.Shell; /** * Copyright (c) 2013-2015 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.dialogs; /** * An Angular Element selection dialog used for opening Angular Elements. */ public class OpenAngularElementSelectionDialog extends FilteredAngularElementsSelectionDialog { private static final String DIALOG_SETTINGS = "org.eclipse.angularjs.internal.ui.dialogs.OpenAngularElementSelectionDialog"; //$NON-NLS-1$ public OpenAngularElementSelectionDialog(Shell shell, boolean multi) { super(shell, multi); } @Override protected IDialogSettings getDialogSettings() {
IDialogSettings settings = AngularUIPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS);
angelozerr/angularjs-eclipse
org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/handlers/ConvertProjectToAngularCommandHandler.java
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIMessages.java // public final class AngularUIMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.angularjs.internal.ui.AngularUIMessages"; //$NON-NLS-1$ // // private static ResourceBundle fResourceBundle; // // public static String ConvertProjectToAngular_converting_project_job_title; // // public static String AngularGlobalPreferencesPage_desc; // public static String HTMLAngularGlobalPreferencesPage_desc; // public static String HTMLAngularEditorPreferencesPage_desc; // // public static String Sample_HTMLAngular_doc; // // public static String AngularTyping_Auto_Complete; // public static String AngularTyping_Close_EL; // // // Angular Explorer View // public static String AngularOutline_computing; // // public static String GoToDefinitionAction_text; // public static String GoToDefinitionAction_tooltip; // public static String LinkToControllerAction_text; // public static String LinkToControllerAction_tooltip; // public static String RefreshExplorerAction_text; // public static String RefreshExplorerAction_tooltip; // public static String UnLinkToControllerAction_text; // public static String UnLinkToControllerAction_tooltip; // // public static String AngularExplorerView_openFile_error; // public static String AngularExplorerView_openFileDialog_title; // // public static String LexicalSortingAction_text; // public static String LexicalSortingAction_tooltip; // public static String LexicalSortingAction_description; // // // Hyperlink // public static String HTMLAngularHyperLink_text; // public static String HTMLAngularHyperLink_typeLabel; // // // Preferences // public static String DirectivesPropertyPage_desc; // public static String DirectivesPropertyPage_useOriginalName_label; // public static String DirectivesPropertyPage_startsWithLabel_text; // public static String DirectivesPropertyPage_startsWithNothing_label; // public static String DirectivesPropertyPage_startsWithX_label; // public static String DirectivesPropertyPage_startsWithData_label; // public static String DirectivesPropertyPage_delimiterLabel_text; // public static String DirectivesPropertyPage_colonDelimiter_label; // public static String DirectivesPropertyPage_minusDelimiter_label; // public static String DirectivesPropertyPage_underscoreDelimiter_label; // public static String DirectivesPropertyPage_directiveTestLabel_text; // // public static String ExpressionPropertyPage_startSybol_label; // public static String ExpressionPropertyPage_endSybol_label; // // public static String OpenAngularElementAction_label; // public static String OpenAngularElementAction_description; // public static String OpenAngularElementAction_tooltip; // public static String OpenAngularElementAction_dialogMessage; // public static String OpenAngularElementAction_dialogTitle; // // // Protractor // public static String ProtractorLaunchShortcut_Error; // public static String ProtractorLaunchShortcut_Protractor_Failed; // // public static String ProtractorPreferencesPage_desc; // public static String ProtractorPreferencesPage_defaultCliFile_label; // public static String ProtractorPreferencesPage_debugger_label; // // public static String Protractor_MainTab_location_label; // public static String Protractor_MainTab_Select_a_protractor_config_file; // public static String Protractor_ProtractorTab_name; // public static String Protractor_ProtractorTab_cliFile; // // // private AngularUIMessages() { // } // // public static ResourceBundle getResourceBundle() { // try { // if (fResourceBundle == null) // fResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // } catch (MissingResourceException x) { // fResourceBundle = null; // } // return fResourceBundle; // } // // static { // NLS.initializeMessages(BUNDLE_NAME, AngularUIMessages.class); // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.angularjs.internal.ui.AngularUIMessages; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.preferences.IScopeContext; import org.eclipse.osgi.util.NLS; import tern.eclipse.ide.ui.handlers.AbstractConvertProjectCommandHandler; import tern.server.ITernModule; import tern.server.TernDef; import tern.server.TernPlugin;
/** * Copyright (c) 2013-2014 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.handlers; /** * Convert selected project to Angular project. * */ public class ConvertProjectToAngularCommandHandler extends AbstractConvertProjectCommandHandler { @Override protected String getConvertingProjectJobTitle(IProject project) { return NLS
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIMessages.java // public final class AngularUIMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.angularjs.internal.ui.AngularUIMessages"; //$NON-NLS-1$ // // private static ResourceBundle fResourceBundle; // // public static String ConvertProjectToAngular_converting_project_job_title; // // public static String AngularGlobalPreferencesPage_desc; // public static String HTMLAngularGlobalPreferencesPage_desc; // public static String HTMLAngularEditorPreferencesPage_desc; // // public static String Sample_HTMLAngular_doc; // // public static String AngularTyping_Auto_Complete; // public static String AngularTyping_Close_EL; // // // Angular Explorer View // public static String AngularOutline_computing; // // public static String GoToDefinitionAction_text; // public static String GoToDefinitionAction_tooltip; // public static String LinkToControllerAction_text; // public static String LinkToControllerAction_tooltip; // public static String RefreshExplorerAction_text; // public static String RefreshExplorerAction_tooltip; // public static String UnLinkToControllerAction_text; // public static String UnLinkToControllerAction_tooltip; // // public static String AngularExplorerView_openFile_error; // public static String AngularExplorerView_openFileDialog_title; // // public static String LexicalSortingAction_text; // public static String LexicalSortingAction_tooltip; // public static String LexicalSortingAction_description; // // // Hyperlink // public static String HTMLAngularHyperLink_text; // public static String HTMLAngularHyperLink_typeLabel; // // // Preferences // public static String DirectivesPropertyPage_desc; // public static String DirectivesPropertyPage_useOriginalName_label; // public static String DirectivesPropertyPage_startsWithLabel_text; // public static String DirectivesPropertyPage_startsWithNothing_label; // public static String DirectivesPropertyPage_startsWithX_label; // public static String DirectivesPropertyPage_startsWithData_label; // public static String DirectivesPropertyPage_delimiterLabel_text; // public static String DirectivesPropertyPage_colonDelimiter_label; // public static String DirectivesPropertyPage_minusDelimiter_label; // public static String DirectivesPropertyPage_underscoreDelimiter_label; // public static String DirectivesPropertyPage_directiveTestLabel_text; // // public static String ExpressionPropertyPage_startSybol_label; // public static String ExpressionPropertyPage_endSybol_label; // // public static String OpenAngularElementAction_label; // public static String OpenAngularElementAction_description; // public static String OpenAngularElementAction_tooltip; // public static String OpenAngularElementAction_dialogMessage; // public static String OpenAngularElementAction_dialogTitle; // // // Protractor // public static String ProtractorLaunchShortcut_Error; // public static String ProtractorLaunchShortcut_Protractor_Failed; // // public static String ProtractorPreferencesPage_desc; // public static String ProtractorPreferencesPage_defaultCliFile_label; // public static String ProtractorPreferencesPage_debugger_label; // // public static String Protractor_MainTab_location_label; // public static String Protractor_MainTab_Select_a_protractor_config_file; // public static String Protractor_ProtractorTab_name; // public static String Protractor_ProtractorTab_cliFile; // // // private AngularUIMessages() { // } // // public static ResourceBundle getResourceBundle() { // try { // if (fResourceBundle == null) // fResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // } catch (MissingResourceException x) { // fResourceBundle = null; // } // return fResourceBundle; // } // // static { // NLS.initializeMessages(BUNDLE_NAME, AngularUIMessages.class); // } // } // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/handlers/ConvertProjectToAngularCommandHandler.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.angularjs.internal.ui.AngularUIMessages; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.preferences.IScopeContext; import org.eclipse.osgi.util.NLS; import tern.eclipse.ide.ui.handlers.AbstractConvertProjectCommandHandler; import tern.server.ITernModule; import tern.server.TernDef; import tern.server.TernPlugin; /** * Copyright (c) 2013-2014 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.handlers; /** * Convert selected project to Angular project. * */ public class ConvertProjectToAngularCommandHandler extends AbstractConvertProjectCommandHandler { @Override protected String getConvertingProjectJobTitle(IProject project) { return NLS
.bind(AngularUIMessages.ConvertProjectToAngular_converting_project_job_title,
angelozerr/angularjs-eclipse
org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/preferences/PreferenceConstants.java
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIPlugin.java // public class AngularUIPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.angularjs.ui"; //$NON-NLS-1$ // // // The shared instance // private static AngularUIPlugin plugin; // // /** // * The constructor // */ // public AngularUIPlugin() { // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static AngularUIPlugin getDefault() { // return plugin; // } // // public static IWorkbenchWindow getActiveWorkbenchWindow() { // return getDefault().getWorkbench().getActiveWorkbenchWindow(); // } // // public static Shell getActiveWorkbenchShell() { // IWorkbenchWindow window = getActiveWorkbenchWindow(); // if (window != null) { // return window.getShell(); // } // return null; // } // // /** // * @return Returns the active workbench window's currrent page. // */ // public static IWorkbenchPage getActivePage() { // return getActiveWorkbenchWindow().getActivePage(); // } // // } // // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/style/IStyleConstantsForAngular.java // public interface IStyleConstantsForAngular { // // public static final String ANGULAR_EXPRESSION_BORDER = "angularExpressionBorder"; // public static final String ANGULAR_EXPRESSION = "angularExpression"; // public static final String ANGULAR_DIRECTIVE_NAME = "directiveName"; // public static final String ANGULAR_DIRECTIVE_PARAMETER_NAME = "directiveParameterName"; // // }
import org.eclipse.angularjs.internal.ui.AngularUIPlugin; import org.eclipse.angularjs.internal.ui.style.IStyleConstantsForAngular; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.ui.PlatformUI; import org.eclipse.wst.sse.ui.internal.preferences.ui.ColorHelper;
/** * Copyright (c) 2013-2016 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.preferences; /** * Angular UI preferences constants. * */ public class PreferenceConstants { /** * Returns the Angular UI preferences store. * * @return the Angular UI preferences store. */ public static IPreferenceStore getPreferenceStore() {
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIPlugin.java // public class AngularUIPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.angularjs.ui"; //$NON-NLS-1$ // // // The shared instance // private static AngularUIPlugin plugin; // // /** // * The constructor // */ // public AngularUIPlugin() { // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static AngularUIPlugin getDefault() { // return plugin; // } // // public static IWorkbenchWindow getActiveWorkbenchWindow() { // return getDefault().getWorkbench().getActiveWorkbenchWindow(); // } // // public static Shell getActiveWorkbenchShell() { // IWorkbenchWindow window = getActiveWorkbenchWindow(); // if (window != null) { // return window.getShell(); // } // return null; // } // // /** // * @return Returns the active workbench window's currrent page. // */ // public static IWorkbenchPage getActivePage() { // return getActiveWorkbenchWindow().getActivePage(); // } // // } // // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/style/IStyleConstantsForAngular.java // public interface IStyleConstantsForAngular { // // public static final String ANGULAR_EXPRESSION_BORDER = "angularExpressionBorder"; // public static final String ANGULAR_EXPRESSION = "angularExpression"; // public static final String ANGULAR_DIRECTIVE_NAME = "directiveName"; // public static final String ANGULAR_DIRECTIVE_PARAMETER_NAME = "directiveParameterName"; // // } // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/preferences/PreferenceConstants.java import org.eclipse.angularjs.internal.ui.AngularUIPlugin; import org.eclipse.angularjs.internal.ui.style.IStyleConstantsForAngular; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.ui.PlatformUI; import org.eclipse.wst.sse.ui.internal.preferences.ui.ColorHelper; /** * Copyright (c) 2013-2016 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.preferences; /** * Angular UI preferences constants. * */ public class PreferenceConstants { /** * Returns the Angular UI preferences store. * * @return the Angular UI preferences store. */ public static IPreferenceStore getPreferenceStore() {
return AngularUIPlugin.getDefault().getPreferenceStore();
angelozerr/angularjs-eclipse
org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/preferences/PreferenceConstants.java
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIPlugin.java // public class AngularUIPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.angularjs.ui"; //$NON-NLS-1$ // // // The shared instance // private static AngularUIPlugin plugin; // // /** // * The constructor // */ // public AngularUIPlugin() { // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static AngularUIPlugin getDefault() { // return plugin; // } // // public static IWorkbenchWindow getActiveWorkbenchWindow() { // return getDefault().getWorkbench().getActiveWorkbenchWindow(); // } // // public static Shell getActiveWorkbenchShell() { // IWorkbenchWindow window = getActiveWorkbenchWindow(); // if (window != null) { // return window.getShell(); // } // return null; // } // // /** // * @return Returns the active workbench window's currrent page. // */ // public static IWorkbenchPage getActivePage() { // return getActiveWorkbenchWindow().getActivePage(); // } // // } // // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/style/IStyleConstantsForAngular.java // public interface IStyleConstantsForAngular { // // public static final String ANGULAR_EXPRESSION_BORDER = "angularExpressionBorder"; // public static final String ANGULAR_EXPRESSION = "angularExpression"; // public static final String ANGULAR_DIRECTIVE_NAME = "directiveName"; // public static final String ANGULAR_DIRECTIVE_PARAMETER_NAME = "directiveParameterName"; // // }
import org.eclipse.angularjs.internal.ui.AngularUIPlugin; import org.eclipse.angularjs.internal.ui.style.IStyleConstantsForAngular; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.ui.PlatformUI; import org.eclipse.wst.sse.ui.internal.preferences.ui.ColorHelper;
/** * Copyright (c) 2013-2016 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.preferences; /** * Angular UI preferences constants. * */ public class PreferenceConstants { /** * Returns the Angular UI preferences store. * * @return the Angular UI preferences store. */ public static IPreferenceStore getPreferenceStore() { return AngularUIPlugin.getDefault().getPreferenceStore(); } /** * Initializes the given preference store with the default values. */ public static void initializeDefaultValues() { IPreferenceStore store = getPreferenceStore(); ColorRegistry registry = PlatformUI.getWorkbench().getThemeManager() .getCurrentTheme().getColorRegistry(); // HTML Style Preferences String NOBACKGROUNDBOLD = " | null | false"; //$NON-NLS-1$ String JUSTITALIC = " | null | false | true"; //$NON-NLS-1$ String JUSTBOLD = " | null | true | false"; //$NON-NLS-1$ // SyntaxColoringPage String styleValue = ColorHelper.findRGBString(registry,
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIPlugin.java // public class AngularUIPlugin extends AbstractUIPlugin { // // // The plug-in ID // public static final String PLUGIN_ID = "org.eclipse.angularjs.ui"; //$NON-NLS-1$ // // // The shared instance // private static AngularUIPlugin plugin; // // /** // * The constructor // */ // public AngularUIPlugin() { // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext // * ) // */ // public void start(BundleContext context) throws Exception { // super.start(context); // plugin = this; // } // // /* // * (non-Javadoc) // * // * @see // * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext // * ) // */ // public void stop(BundleContext context) throws Exception { // plugin = null; // super.stop(context); // } // // /** // * Returns the shared instance // * // * @return the shared instance // */ // public static AngularUIPlugin getDefault() { // return plugin; // } // // public static IWorkbenchWindow getActiveWorkbenchWindow() { // return getDefault().getWorkbench().getActiveWorkbenchWindow(); // } // // public static Shell getActiveWorkbenchShell() { // IWorkbenchWindow window = getActiveWorkbenchWindow(); // if (window != null) { // return window.getShell(); // } // return null; // } // // /** // * @return Returns the active workbench window's currrent page. // */ // public static IWorkbenchPage getActivePage() { // return getActiveWorkbenchWindow().getActivePage(); // } // // } // // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/style/IStyleConstantsForAngular.java // public interface IStyleConstantsForAngular { // // public static final String ANGULAR_EXPRESSION_BORDER = "angularExpressionBorder"; // public static final String ANGULAR_EXPRESSION = "angularExpression"; // public static final String ANGULAR_DIRECTIVE_NAME = "directiveName"; // public static final String ANGULAR_DIRECTIVE_PARAMETER_NAME = "directiveParameterName"; // // } // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/preferences/PreferenceConstants.java import org.eclipse.angularjs.internal.ui.AngularUIPlugin; import org.eclipse.angularjs.internal.ui.style.IStyleConstantsForAngular; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ColorRegistry; import org.eclipse.ui.PlatformUI; import org.eclipse.wst.sse.ui.internal.preferences.ui.ColorHelper; /** * Copyright (c) 2013-2016 Angelo ZERR. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation */ package org.eclipse.angularjs.internal.ui.preferences; /** * Angular UI preferences constants. * */ public class PreferenceConstants { /** * Returns the Angular UI preferences store. * * @return the Angular UI preferences store. */ public static IPreferenceStore getPreferenceStore() { return AngularUIPlugin.getDefault().getPreferenceStore(); } /** * Initializes the given preference store with the default values. */ public static void initializeDefaultValues() { IPreferenceStore store = getPreferenceStore(); ColorRegistry registry = PlatformUI.getWorkbench().getThemeManager() .getCurrentTheme().getColorRegistry(); // HTML Style Preferences String NOBACKGROUNDBOLD = " | null | false"; //$NON-NLS-1$ String JUSTITALIC = " | null | false | true"; //$NON-NLS-1$ String JUSTBOLD = " | null | true | false"; //$NON-NLS-1$ // SyntaxColoringPage String styleValue = ColorHelper.findRGBString(registry,
IStyleConstantsForAngular.ANGULAR_EXPRESSION_BORDER, 0, 0, 128)
angelozerr/angularjs-eclipse
org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/launchConfigurations/MainTab.java
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIMessages.java // public final class AngularUIMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.angularjs.internal.ui.AngularUIMessages"; //$NON-NLS-1$ // // private static ResourceBundle fResourceBundle; // // public static String ConvertProjectToAngular_converting_project_job_title; // // public static String AngularGlobalPreferencesPage_desc; // public static String HTMLAngularGlobalPreferencesPage_desc; // public static String HTMLAngularEditorPreferencesPage_desc; // // public static String Sample_HTMLAngular_doc; // // public static String AngularTyping_Auto_Complete; // public static String AngularTyping_Close_EL; // // // Angular Explorer View // public static String AngularOutline_computing; // // public static String GoToDefinitionAction_text; // public static String GoToDefinitionAction_tooltip; // public static String LinkToControllerAction_text; // public static String LinkToControllerAction_tooltip; // public static String RefreshExplorerAction_text; // public static String RefreshExplorerAction_tooltip; // public static String UnLinkToControllerAction_text; // public static String UnLinkToControllerAction_tooltip; // // public static String AngularExplorerView_openFile_error; // public static String AngularExplorerView_openFileDialog_title; // // public static String LexicalSortingAction_text; // public static String LexicalSortingAction_tooltip; // public static String LexicalSortingAction_description; // // // Hyperlink // public static String HTMLAngularHyperLink_text; // public static String HTMLAngularHyperLink_typeLabel; // // // Preferences // public static String DirectivesPropertyPage_desc; // public static String DirectivesPropertyPage_useOriginalName_label; // public static String DirectivesPropertyPage_startsWithLabel_text; // public static String DirectivesPropertyPage_startsWithNothing_label; // public static String DirectivesPropertyPage_startsWithX_label; // public static String DirectivesPropertyPage_startsWithData_label; // public static String DirectivesPropertyPage_delimiterLabel_text; // public static String DirectivesPropertyPage_colonDelimiter_label; // public static String DirectivesPropertyPage_minusDelimiter_label; // public static String DirectivesPropertyPage_underscoreDelimiter_label; // public static String DirectivesPropertyPage_directiveTestLabel_text; // // public static String ExpressionPropertyPage_startSybol_label; // public static String ExpressionPropertyPage_endSybol_label; // // public static String OpenAngularElementAction_label; // public static String OpenAngularElementAction_description; // public static String OpenAngularElementAction_tooltip; // public static String OpenAngularElementAction_dialogMessage; // public static String OpenAngularElementAction_dialogTitle; // // // Protractor // public static String ProtractorLaunchShortcut_Error; // public static String ProtractorLaunchShortcut_Protractor_Failed; // // public static String ProtractorPreferencesPage_desc; // public static String ProtractorPreferencesPage_defaultCliFile_label; // public static String ProtractorPreferencesPage_debugger_label; // // public static String Protractor_MainTab_location_label; // public static String Protractor_MainTab_Select_a_protractor_config_file; // public static String Protractor_ProtractorTab_name; // public static String Protractor_ProtractorTab_cliFile; // // // private AngularUIMessages() { // } // // public static ResourceBundle getResourceBundle() { // try { // if (fResourceBundle == null) // fResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // } catch (MissingResourceException x) { // fResourceBundle = null; // } // return fResourceBundle; // } // // static { // NLS.initializeMessages(BUNDLE_NAME, AngularUIMessages.class); // } // }
import org.eclipse.angularjs.internal.ui.AngularUIMessages; import org.eclipse.core.externaltools.internal.IExternalToolConstants; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.ui.ILaunchConfigurationTab; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.externaltools.internal.launchConfigurations.ExternalToolsMainTab; import org.eclipse.ui.externaltools.internal.ui.FileSelectionDialog; import tern.eclipse.ide.server.nodejs.core.debugger.launchConfigurations.NodejsCliFileHelper;
Dialog.applyDialogFont(parent); } /* * (non-Javadoc) * * @see org.eclipse.ui.externaltools.internal.launchConfigurations. * ExternalToolsMainTab#setDefaults(org.eclipse.debug.core. * ILaunchConfigurationWorkingCopy ) */ @Override public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { super.setDefaults(configuration); // prevent a new blank configuration from being dirty when first created // and not yet edited } private void updateCheckButtons(ILaunchConfiguration configuration) { } /* * (non-Javadoc) * * @see org.eclipse.ui.externaltools.internal.launchConfigurations. * ExternalToolsMainTab#handleWorkspaceLocationButtonSelected() */ @Override protected void handleWorkspaceLocationButtonSelected() { FileSelectionDialog dialog; dialog = new FileSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(),
// Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/AngularUIMessages.java // public final class AngularUIMessages extends NLS { // // private static final String BUNDLE_NAME = "org.eclipse.angularjs.internal.ui.AngularUIMessages"; //$NON-NLS-1$ // // private static ResourceBundle fResourceBundle; // // public static String ConvertProjectToAngular_converting_project_job_title; // // public static String AngularGlobalPreferencesPage_desc; // public static String HTMLAngularGlobalPreferencesPage_desc; // public static String HTMLAngularEditorPreferencesPage_desc; // // public static String Sample_HTMLAngular_doc; // // public static String AngularTyping_Auto_Complete; // public static String AngularTyping_Close_EL; // // // Angular Explorer View // public static String AngularOutline_computing; // // public static String GoToDefinitionAction_text; // public static String GoToDefinitionAction_tooltip; // public static String LinkToControllerAction_text; // public static String LinkToControllerAction_tooltip; // public static String RefreshExplorerAction_text; // public static String RefreshExplorerAction_tooltip; // public static String UnLinkToControllerAction_text; // public static String UnLinkToControllerAction_tooltip; // // public static String AngularExplorerView_openFile_error; // public static String AngularExplorerView_openFileDialog_title; // // public static String LexicalSortingAction_text; // public static String LexicalSortingAction_tooltip; // public static String LexicalSortingAction_description; // // // Hyperlink // public static String HTMLAngularHyperLink_text; // public static String HTMLAngularHyperLink_typeLabel; // // // Preferences // public static String DirectivesPropertyPage_desc; // public static String DirectivesPropertyPage_useOriginalName_label; // public static String DirectivesPropertyPage_startsWithLabel_text; // public static String DirectivesPropertyPage_startsWithNothing_label; // public static String DirectivesPropertyPage_startsWithX_label; // public static String DirectivesPropertyPage_startsWithData_label; // public static String DirectivesPropertyPage_delimiterLabel_text; // public static String DirectivesPropertyPage_colonDelimiter_label; // public static String DirectivesPropertyPage_minusDelimiter_label; // public static String DirectivesPropertyPage_underscoreDelimiter_label; // public static String DirectivesPropertyPage_directiveTestLabel_text; // // public static String ExpressionPropertyPage_startSybol_label; // public static String ExpressionPropertyPage_endSybol_label; // // public static String OpenAngularElementAction_label; // public static String OpenAngularElementAction_description; // public static String OpenAngularElementAction_tooltip; // public static String OpenAngularElementAction_dialogMessage; // public static String OpenAngularElementAction_dialogTitle; // // // Protractor // public static String ProtractorLaunchShortcut_Error; // public static String ProtractorLaunchShortcut_Protractor_Failed; // // public static String ProtractorPreferencesPage_desc; // public static String ProtractorPreferencesPage_defaultCliFile_label; // public static String ProtractorPreferencesPage_debugger_label; // // public static String Protractor_MainTab_location_label; // public static String Protractor_MainTab_Select_a_protractor_config_file; // public static String Protractor_ProtractorTab_name; // public static String Protractor_ProtractorTab_cliFile; // // // private AngularUIMessages() { // } // // public static ResourceBundle getResourceBundle() { // try { // if (fResourceBundle == null) // fResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // } catch (MissingResourceException x) { // fResourceBundle = null; // } // return fResourceBundle; // } // // static { // NLS.initializeMessages(BUNDLE_NAME, AngularUIMessages.class); // } // } // Path: org.eclipse.angularjs.ui/src/org/eclipse/angularjs/internal/ui/launchConfigurations/MainTab.java import org.eclipse.angularjs.internal.ui.AngularUIMessages; import org.eclipse.core.externaltools.internal.IExternalToolConstants; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.ui.ILaunchConfigurationTab; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.externaltools.internal.launchConfigurations.ExternalToolsMainTab; import org.eclipse.ui.externaltools.internal.ui.FileSelectionDialog; import tern.eclipse.ide.server.nodejs.core.debugger.launchConfigurations.NodejsCliFileHelper; Dialog.applyDialogFont(parent); } /* * (non-Javadoc) * * @see org.eclipse.ui.externaltools.internal.launchConfigurations. * ExternalToolsMainTab#setDefaults(org.eclipse.debug.core. * ILaunchConfigurationWorkingCopy ) */ @Override public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { super.setDefaults(configuration); // prevent a new blank configuration from being dirty when first created // and not yet edited } private void updateCheckButtons(ILaunchConfiguration configuration) { } /* * (non-Javadoc) * * @see org.eclipse.ui.externaltools.internal.launchConfigurations. * ExternalToolsMainTab#handleWorkspaceLocationButtonSelected() */ @Override protected void handleWorkspaceLocationButtonSelected() { FileSelectionDialog dialog; dialog = new FileSelectionDialog(getShell(), ResourcesPlugin.getWorkspace().getRoot(),
AngularUIMessages.Protractor_MainTab_Select_a_protractor_config_file);
unruly/control
src/test/java/co/unruly/control/result/CastsTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // }
import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World";
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // Path: src/test/java/co/unruly/control/result/CastsTest.java import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World";
Result<String, Object> cast = pipe(helloWorld)
unruly/control
src/test/java/co/unruly/control/result/CastsTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // }
import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World"; Result<String, Object> cast = pipe(helloWorld)
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // Path: src/test/java/co/unruly/control/result/CastsTest.java import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World"; Result<String, Object> cast = pipe(helloWorld)
.resolveWith(castTo(String.class));
unruly/control
src/test/java/co/unruly/control/result/CastsTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // }
import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World"; Result<String, Object> cast = pipe(helloWorld) .resolveWith(castTo(String.class));
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // Path: src/test/java/co/unruly/control/result/CastsTest.java import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World"; Result<String, Object> cast = pipe(helloWorld) .resolveWith(castTo(String.class));
assertThat(cast, isSuccessOf("Hello World"));
unruly/control
src/test/java/co/unruly/control/result/CastsTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // }
import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World"; Result<String, Object> cast = pipe(helloWorld) .resolveWith(castTo(String.class)); assertThat(cast, isSuccessOf("Hello World")); } @Test public void castingToIncorrectTypeYieldsFailure() { final Object helloWorld = "Hello World"; Result<Integer, Object> cast = pipe(helloWorld) .resolveWith(castTo(Integer.class));
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> castTo(Class<OS> targetClass) { // return input -> targetClass.isAssignableFrom(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // Path: src/test/java/co/unruly/control/result/CastsTest.java import org.junit.Test; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Introducers.castTo; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class CastsTest { @Test public void castingToCorrectTypeYieldsSuccess() { final Object helloWorld = "Hello World"; Result<String, Object> cast = pipe(helloWorld) .resolveWith(castTo(String.class)); assertThat(cast, isSuccessOf("Hello World")); } @Test public void castingToIncorrectTypeYieldsFailure() { final Object helloWorld = "Hello World"; Result<Integer, Object> cast = pipe(helloWorld) .resolveWith(castTo(Integer.class));
assertThat(cast, isFailureOf("Hello World"));
unruly/control
src/test/java/co/unruly/control/result/TryTest.java
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder;
package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() {
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/test/java/co/unruly/control/result/TryTest.java import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() {
Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException)
unruly/control
src/test/java/co/unruly/control/result/TryTest.java
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder;
package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException)
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/test/java/co/unruly/control/result/TryTest.java import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException)
.andThen(ifFailed(Exception::getMessage));
unruly/control
src/test/java/co/unruly/control/result/TryTest.java
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder;
package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3")
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/test/java/co/unruly/control/result/TryTest.java import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3")
.flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream))
unruly/control
src/test/java/co/unruly/control/result/TryTest.java
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder;
package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream))
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/test/java/co/unruly/control/result/TryTest.java import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream))
.map(onSuccess(x -> String.format("Success: %s", x)))
unruly/control
src/test/java/co/unruly/control/result/TryTest.java
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder;
package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream)) .map(onSuccess(x -> String.format("Success: %s", x)))
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/test/java/co/unruly/control/result/TryTest.java import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream)) .map(onSuccess(x -> String.format("Success: %s", x)))
.map(onFailure(Exception::getMessage))
unruly/control
src/test/java/co/unruly/control/result/TryTest.java
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder;
package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream)) .map(onSuccess(x -> String.format("Success: %s", x))) .map(onFailure(Exception::getMessage))
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/test/java/co/unruly/control/result/TryTest.java import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; package co.unruly.control.result; //import static co.unruly.control.result.Results.ifFailed; public class TryTest { @Test public void canHandleRuntimeExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsRuntimeException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream)) .map(onSuccess(x -> String.format("Success: %s", x))) .map(onFailure(Exception::getMessage))
.map(collapse())
unruly/control
src/test/java/co/unruly/control/result/TryTest.java
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder;
public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream)) .map(onSuccess(x -> String.format("Success: %s", x))) .map(onFailure(Exception::getMessage)) .map(collapse()) .collect(toList()); assertThat(doingStuffWithNumbers, contains( "Success: 1", "For input string: \"two\"", "Success: 1", "Success: 2", "Success: 3" )); } @Test public void canHandleStreamFunctionsUsingTryToAndUnwrap() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .map(tryTo(TryTest::throwsAndMakesStream))
// Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) { // return tryTo(f).andThen(unwrapSuccesses()); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <T> Function<Result<T, T>, T> collapse() { // return r -> r.either(identity(), identity()); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/test/java/co/unruly/control/result/TryTest.java import org.junit.Test; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.Stream; import static co.unruly.control.result.Introducers.tryAndUnwrap; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Resolvers.collapse; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onFailure; import static co.unruly.control.result.Transformers.onSuccess; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; public void canHandleCheckedExceptions() { Function<String, String> doSomething = tryTo(TryTest::throwsCheckedException) .andThen(ifFailed(Exception::getMessage)); assertThat(doSomething.apply("throw"), is("This is a naughty method")); assertThat(doSomething.apply("play nice"), is("Today, I was good")); } @Test public void canHandleStreamFunctionsUsingFlatTry() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .flatMap(tryAndUnwrap(TryTest::throwsAndMakesStream)) .map(onSuccess(x -> String.format("Success: %s", x))) .map(onFailure(Exception::getMessage)) .map(collapse()) .collect(toList()); assertThat(doingStuffWithNumbers, contains( "Success: 1", "For input string: \"two\"", "Success: 1", "Success: 2", "Success: 3" )); } @Test public void canHandleStreamFunctionsUsingTryToAndUnwrap() { List<String> doingStuffWithNumbers = Stream.of("1", "two", "3") .map(tryTo(TryTest::throwsAndMakesStream))
.flatMap(unwrapSuccesses())
unruly/control
src/test/java/co/unruly/control/ThrowingLambdasTest.java
// Path: src/main/java/co/unruly/control/ThrowingLambdas.java // static <T, X extends Exception> Predicate<T> throwingRuntime(ThrowingPredicate<T, X> p) { // return x -> { // try { // return p.test(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // }
import org.junit.Test; import java.util.function.Predicate; import static co.unruly.control.ThrowingLambdas.ThrowingPredicate.throwingRuntime; import static org.junit.Assert.assertTrue;
package co.unruly.control; public class ThrowingLambdasTest { // @Test // public void cannotCompileWhenPassingLambdaThatThrows() throws Exception { // assertTrue(test(2, ThrowingLambdasTest::dodgyIsEven)); // } @Test public void canHandleThrowingMethodsWithAppropriateFunctionalInterfaceType() { assertTrue(tryToTest(2, ThrowingLambdasTest::dodgyIsEven)); } @Test public void canHandleMultiThrowingMethodsWithAppropriateFunctionalInterfaceType() { assertTrue(tryToTest(2, ThrowingLambdasTest::veryDodgyIsEven)); } @Test public void canConvertThrowingLambdasToNonThrowingLambdas() throws Exception {
// Path: src/main/java/co/unruly/control/ThrowingLambdas.java // static <T, X extends Exception> Predicate<T> throwingRuntime(ThrowingPredicate<T, X> p) { // return x -> { // try { // return p.test(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // Path: src/test/java/co/unruly/control/ThrowingLambdasTest.java import org.junit.Test; import java.util.function.Predicate; import static co.unruly.control.ThrowingLambdas.ThrowingPredicate.throwingRuntime; import static org.junit.Assert.assertTrue; package co.unruly.control; public class ThrowingLambdasTest { // @Test // public void cannotCompileWhenPassingLambdaThatThrows() throws Exception { // assertTrue(test(2, ThrowingLambdasTest::dodgyIsEven)); // } @Test public void canHandleThrowingMethodsWithAppropriateFunctionalInterfaceType() { assertTrue(tryToTest(2, ThrowingLambdasTest::dodgyIsEven)); } @Test public void canHandleMultiThrowingMethodsWithAppropriateFunctionalInterfaceType() { assertTrue(tryToTest(2, ThrowingLambdasTest::veryDodgyIsEven)); } @Test public void canConvertThrowingLambdasToNonThrowingLambdas() throws Exception {
assertTrue(test(2, throwingRuntime(ThrowingLambdasTest::dodgyIsEven)));
unruly/control
src/main/java/co/unruly/control/PartialApplication.java
// Path: src/main/java/co/unruly/control/pair/Triple.java // @FunctionalInterface // public interface TriFunction<A, B, C, R> { // R apply(A a, B b, C c); // }
import co.unruly.control.pair.Triple.TriFunction; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier;
package co.unruly.control; /** * A collection of functions to partially apply arguments to functions, to simplify usage * in streams, optionals etc. */ public interface PartialApplication { /** * Binds the provided argument to the function, and returns a Supplier with that argument applied. * * bind(f, a) is equivalent to () -> f.apply(a) */ static <I, O> Supplier<O> bind(Function<I, O> f, I input) { return () -> f.apply(input); } /** * Binds the provided argument to the function, and returns a new Function with that argument already applied. * * bind(f, a) is equivalent to b -> f.apply(a, b) */ static <A, B, R> Function<B, R> bind(BiFunction<A, B, R> f, A firstParam) { return secondParam -> f.apply(firstParam, secondParam); } /** * Binds the provided arguments to the function, and returns a new Supplier with those arguments already applied. * * bind(f, a, b) is equivalent to () -> f.apply(a, b) */ static <A, B, R> Supplier<R> bind(BiFunction<A, B, R> f, A firstParam, B secondParam) { return () -> f.apply(firstParam, secondParam); } /** * Binds the provided argument to the function, and returns a new BiFunction with that argument already applied. * * bind(f, a) is equivalent to (b, c) -> f.apply(a, b, c) */
// Path: src/main/java/co/unruly/control/pair/Triple.java // @FunctionalInterface // public interface TriFunction<A, B, C, R> { // R apply(A a, B b, C c); // } // Path: src/main/java/co/unruly/control/PartialApplication.java import co.unruly.control.pair.Triple.TriFunction; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; package co.unruly.control; /** * A collection of functions to partially apply arguments to functions, to simplify usage * in streams, optionals etc. */ public interface PartialApplication { /** * Binds the provided argument to the function, and returns a Supplier with that argument applied. * * bind(f, a) is equivalent to () -> f.apply(a) */ static <I, O> Supplier<O> bind(Function<I, O> f, I input) { return () -> f.apply(input); } /** * Binds the provided argument to the function, and returns a new Function with that argument already applied. * * bind(f, a) is equivalent to b -> f.apply(a, b) */ static <A, B, R> Function<B, R> bind(BiFunction<A, B, R> f, A firstParam) { return secondParam -> f.apply(firstParam, secondParam); } /** * Binds the provided arguments to the function, and returns a new Supplier with those arguments already applied. * * bind(f, a, b) is equivalent to () -> f.apply(a, b) */ static <A, B, R> Supplier<R> bind(BiFunction<A, B, R> f, A firstParam, B secondParam) { return () -> f.apply(firstParam, secondParam); } /** * Binds the provided argument to the function, and returns a new BiFunction with that argument already applied. * * bind(f, a) is equivalent to (b, c) -> f.apply(a, b, c) */
static <A, B, C, R> BiFunction<B, C, R> bind(TriFunction<A, B, C, R> f, A firstParam) {
unruly/control
src/test/java/co/unruly/control/ZipTest.java
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // }
import co.unruly.control.pair.Pair; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static co.unruly.control.HigherOrderFunctions.withIndices; import static co.unruly.control.HigherOrderFunctions.zip; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains;
package co.unruly.control; public class ZipTest { @Test public void zipsItemsTogether() {
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // } // Path: src/test/java/co/unruly/control/ZipTest.java import co.unruly.control.pair.Pair; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static co.unruly.control.HigherOrderFunctions.withIndices; import static co.unruly.control.HigherOrderFunctions.zip; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; package co.unruly.control; public class ZipTest { @Test public void zipsItemsTogether() {
List<Pair<String, String>> pairs = zip(
unruly/control
src/test/java/co/unruly/control/ZipTest.java
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // }
import co.unruly.control.pair.Pair; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static co.unruly.control.HigherOrderFunctions.withIndices; import static co.unruly.control.HigherOrderFunctions.zip; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains;
package co.unruly.control; public class ZipTest { @Test public void zipsItemsTogether() {
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // } // Path: src/test/java/co/unruly/control/ZipTest.java import co.unruly.control.pair.Pair; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static co.unruly.control.HigherOrderFunctions.withIndices; import static co.unruly.control.HigherOrderFunctions.zip; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; package co.unruly.control; public class ZipTest { @Test public void zipsItemsTogether() {
List<Pair<String, String>> pairs = zip(
unruly/control
src/test/java/co/unruly/control/ZipTest.java
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // }
import co.unruly.control.pair.Pair; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static co.unruly.control.HigherOrderFunctions.withIndices; import static co.unruly.control.HigherOrderFunctions.zip; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains;
package co.unruly.control; public class ZipTest { @Test public void zipsItemsTogether() { List<Pair<String, String>> pairs = zip( Stream.of("hello", "goodbye"), Stream.of("world", "cruel world")) .collect(Collectors.toList()); assertThat(pairs, contains(Pair.of("hello", "world"), Pair.of("goodbye", "cruel world"))); } @Test public void zipsItemsTogetherUsingFunction() { List<Integer> pairs = zip( Stream.of(1,2,3,4,5), Stream.of(1,10,100,1000,10000), (x, y) -> x * y) .collect(Collectors.toList()); assertThat(pairs, contains(1, 20, 300, 4000, 50000)); } @Test public void generatedStreamIsShorterOfInputStreams() { List<Integer> pairs = zip( Stream.of(1,2,3), Stream.of(1,10,100,1000,10000), (x, y) -> x * y) .collect(Collectors.toList()); assertThat(pairs, contains(1, 20, 300)); } @Test public void buildsIndexedList() {
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // } // Path: src/test/java/co/unruly/control/ZipTest.java import co.unruly.control.pair.Pair; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static co.unruly.control.HigherOrderFunctions.withIndices; import static co.unruly.control.HigherOrderFunctions.zip; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; package co.unruly.control; public class ZipTest { @Test public void zipsItemsTogether() { List<Pair<String, String>> pairs = zip( Stream.of("hello", "goodbye"), Stream.of("world", "cruel world")) .collect(Collectors.toList()); assertThat(pairs, contains(Pair.of("hello", "world"), Pair.of("goodbye", "cruel world"))); } @Test public void zipsItemsTogetherUsingFunction() { List<Integer> pairs = zip( Stream.of(1,2,3,4,5), Stream.of(1,10,100,1000,10000), (x, y) -> x * y) .collect(Collectors.toList()); assertThat(pairs, contains(1, 20, 300, 4000, 50000)); } @Test public void generatedStreamIsShorterOfInputStreams() { List<Integer> pairs = zip( Stream.of(1,2,3), Stream.of(1,10,100,1000,10000), (x, y) -> x * y) .collect(Collectors.toList()); assertThat(pairs, contains(1, 20, 300)); } @Test public void buildsIndexedList() {
List<Pair<Integer, String>> indexed = withIndices(Stream.of("zero", "one", "two", "three"))
unruly/control
src/test/java/co/unruly/control/result/MatchTest.java
// Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { // return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); // } // // Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> BoundMatchAttempt<I, O> matchValue(I inputValue, Function<I, Result<O, I>>... potentialMatchers) { // return f -> pipe(inputValue) // .then(attemptMatch(potentialMatchers)) // .then(ifFailed(f)) // .resolve(); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // public interface Recover { // // /** // * Returns a function which takes an Optional value, and returns a failure of the // * wrapped value if it was present, otherwise returns a success using the provided Supplier // */ // static <S, F> Function<Optional<F>, Result<S, F>> whenAbsent(Supplier<S> onEmpty) { // return maybe -> maybe.map(Result::<S, F>failure).orElseGet(() -> Result.success(onEmpty.get())); // } // // /** // * Takes a class and a mapping function and returns a function which takes a value and, if it's of the // * provided class, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F, TF extends F> Function<F, Result<S, F>> ifType(Class<TF> targetClass, Function<TF, S> mapper) { // return Introducers.<F, TF>castTo(targetClass).andThen(Transformers.onSuccess(mapper)); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it satisfies // * the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it doesn't // * satisfy the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifNot(Predicate<F> test, Function<F, S> mapper) { // return ifIs(test.negate(), mapper); // } // // /** // * Takes a value and a mapping function and returns a function which takes a value and, if it is equal to // * the provided value, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifEquals(F expectedValue, Function<F, S> mapper) { // return input -> expectedValue.equals(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Matches the value if the provided function yields an Optional whose value is // * present, returning the value in that Optional. // */ // static <S, F> Function<F, Result<S, F>> ifPresent(Function<F, Optional<S>> successProvider) { // return value -> successProvider // .apply(value) // .map(Result::<S, F>success) // .orElseGet(() -> Result.failure(value)); // } // }
import org.junit.Test; import java.util.Optional; import java.util.function.Function; import static co.unruly.control.result.Match.match; import static co.unruly.control.result.Match.matchValue; import static co.unruly.control.result.Recover.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class MatchTest { @Test public void canMatchOnTypeWithFlowTyping() {
// Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { // return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); // } // // Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> BoundMatchAttempt<I, O> matchValue(I inputValue, Function<I, Result<O, I>>... potentialMatchers) { // return f -> pipe(inputValue) // .then(attemptMatch(potentialMatchers)) // .then(ifFailed(f)) // .resolve(); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // public interface Recover { // // /** // * Returns a function which takes an Optional value, and returns a failure of the // * wrapped value if it was present, otherwise returns a success using the provided Supplier // */ // static <S, F> Function<Optional<F>, Result<S, F>> whenAbsent(Supplier<S> onEmpty) { // return maybe -> maybe.map(Result::<S, F>failure).orElseGet(() -> Result.success(onEmpty.get())); // } // // /** // * Takes a class and a mapping function and returns a function which takes a value and, if it's of the // * provided class, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F, TF extends F> Function<F, Result<S, F>> ifType(Class<TF> targetClass, Function<TF, S> mapper) { // return Introducers.<F, TF>castTo(targetClass).andThen(Transformers.onSuccess(mapper)); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it satisfies // * the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it doesn't // * satisfy the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifNot(Predicate<F> test, Function<F, S> mapper) { // return ifIs(test.negate(), mapper); // } // // /** // * Takes a value and a mapping function and returns a function which takes a value and, if it is equal to // * the provided value, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifEquals(F expectedValue, Function<F, S> mapper) { // return input -> expectedValue.equals(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Matches the value if the provided function yields an Optional whose value is // * present, returning the value in that Optional. // */ // static <S, F> Function<F, Result<S, F>> ifPresent(Function<F, Optional<S>> successProvider) { // return value -> successProvider // .apply(value) // .map(Result::<S, F>success) // .orElseGet(() -> Result.failure(value)); // } // } // Path: src/test/java/co/unruly/control/result/MatchTest.java import org.junit.Test; import java.util.Optional; import java.util.function.Function; import static co.unruly.control.result.Match.match; import static co.unruly.control.result.Match.matchValue; import static co.unruly.control.result.Recover.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class MatchTest { @Test public void canMatchOnTypeWithFlowTyping() {
Function<A, String> matchByType = match(
unruly/control
src/test/java/co/unruly/control/result/MatchTest.java
// Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { // return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); // } // // Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> BoundMatchAttempt<I, O> matchValue(I inputValue, Function<I, Result<O, I>>... potentialMatchers) { // return f -> pipe(inputValue) // .then(attemptMatch(potentialMatchers)) // .then(ifFailed(f)) // .resolve(); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // public interface Recover { // // /** // * Returns a function which takes an Optional value, and returns a failure of the // * wrapped value if it was present, otherwise returns a success using the provided Supplier // */ // static <S, F> Function<Optional<F>, Result<S, F>> whenAbsent(Supplier<S> onEmpty) { // return maybe -> maybe.map(Result::<S, F>failure).orElseGet(() -> Result.success(onEmpty.get())); // } // // /** // * Takes a class and a mapping function and returns a function which takes a value and, if it's of the // * provided class, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F, TF extends F> Function<F, Result<S, F>> ifType(Class<TF> targetClass, Function<TF, S> mapper) { // return Introducers.<F, TF>castTo(targetClass).andThen(Transformers.onSuccess(mapper)); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it satisfies // * the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it doesn't // * satisfy the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifNot(Predicate<F> test, Function<F, S> mapper) { // return ifIs(test.negate(), mapper); // } // // /** // * Takes a value and a mapping function and returns a function which takes a value and, if it is equal to // * the provided value, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifEquals(F expectedValue, Function<F, S> mapper) { // return input -> expectedValue.equals(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Matches the value if the provided function yields an Optional whose value is // * present, returning the value in that Optional. // */ // static <S, F> Function<F, Result<S, F>> ifPresent(Function<F, Optional<S>> successProvider) { // return value -> successProvider // .apply(value) // .map(Result::<S, F>success) // .orElseGet(() -> Result.failure(value)); // } // }
import org.junit.Test; import java.util.Optional; import java.util.function.Function; import static co.unruly.control.result.Match.match; import static co.unruly.control.result.Match.matchValue; import static co.unruly.control.result.Recover.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
} @Test public void canMatchOnValue() { Function<Integer, String> matchByType = match( ifEquals(4, x -> x + " sure looks like a 4 to me!"), ifEquals(7, x -> x + " looks like one of them gosh-darned 7s?") ).otherwise(x -> "I have no idea what a " + x + " is though..."); assertThat(matchByType.apply(3), is("I have no idea what a 3 is though...")); assertThat(matchByType.apply(4), is("4 sure looks like a 4 to me!")); assertThat(matchByType.apply(6), is("I have no idea what a 6 is though...")); assertThat(matchByType.apply(7), is("7 looks like one of them gosh-darned 7s?")); } @Test public void canMatchOnTest() { Function<Integer, String> matchByType = match( ifIs((Integer x) -> x % 2 == 0, x -> x + ", well, that's one of those even numbers"), ifIs(x -> x < 0, x -> x + " is one of those banker's negative number thingies") ).otherwise(x -> x + " is a regular, god-fearing number for god-fearing folks"); assertThat(matchByType.apply(2), is("2, well, that's one of those even numbers")); assertThat(matchByType.apply(-6), is("-6, well, that's one of those even numbers")); assertThat(matchByType.apply(3), is("3 is a regular, god-fearing number for god-fearing folks")); assertThat(matchByType.apply(-9), is("-9 is one of those banker's negative number thingies")); } @Test public void canMatchOnTestPassingArgument() {
// Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { // return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); // } // // Path: src/main/java/co/unruly/control/result/Match.java // @SafeVarargs // public static <I, O> BoundMatchAttempt<I, O> matchValue(I inputValue, Function<I, Result<O, I>>... potentialMatchers) { // return f -> pipe(inputValue) // .then(attemptMatch(potentialMatchers)) // .then(ifFailed(f)) // .resolve(); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // public interface Recover { // // /** // * Returns a function which takes an Optional value, and returns a failure of the // * wrapped value if it was present, otherwise returns a success using the provided Supplier // */ // static <S, F> Function<Optional<F>, Result<S, F>> whenAbsent(Supplier<S> onEmpty) { // return maybe -> maybe.map(Result::<S, F>failure).orElseGet(() -> Result.success(onEmpty.get())); // } // // /** // * Takes a class and a mapping function and returns a function which takes a value and, if it's of the // * provided class, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F, TF extends F> Function<F, Result<S, F>> ifType(Class<TF> targetClass, Function<TF, S> mapper) { // return Introducers.<F, TF>castTo(targetClass).andThen(Transformers.onSuccess(mapper)); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it satisfies // * the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Takes a predicate and a mapping function and returns a function which takes a value and, if it doesn't // * satisfy the predicate, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifNot(Predicate<F> test, Function<F, S> mapper) { // return ifIs(test.negate(), mapper); // } // // /** // * Takes a value and a mapping function and returns a function which takes a value and, if it is equal to // * the provided value, applies the mapping function to it and returns it as a Success, otherwise returning // * the input value as a Failure. // */ // static <S, F> Function<F, Result<S, F>> ifEquals(F expectedValue, Function<F, S> mapper) { // return input -> expectedValue.equals(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // /** // * Matches the value if the provided function yields an Optional whose value is // * present, returning the value in that Optional. // */ // static <S, F> Function<F, Result<S, F>> ifPresent(Function<F, Optional<S>> successProvider) { // return value -> successProvider // .apply(value) // .map(Result::<S, F>success) // .orElseGet(() -> Result.failure(value)); // } // } // Path: src/test/java/co/unruly/control/result/MatchTest.java import org.junit.Test; import java.util.Optional; import java.util.function.Function; import static co.unruly.control.result.Match.match; import static co.unruly.control.result.Match.matchValue; import static co.unruly.control.result.Recover.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; } @Test public void canMatchOnValue() { Function<Integer, String> matchByType = match( ifEquals(4, x -> x + " sure looks like a 4 to me!"), ifEquals(7, x -> x + " looks like one of them gosh-darned 7s?") ).otherwise(x -> "I have no idea what a " + x + " is though..."); assertThat(matchByType.apply(3), is("I have no idea what a 3 is though...")); assertThat(matchByType.apply(4), is("4 sure looks like a 4 to me!")); assertThat(matchByType.apply(6), is("I have no idea what a 6 is though...")); assertThat(matchByType.apply(7), is("7 looks like one of them gosh-darned 7s?")); } @Test public void canMatchOnTest() { Function<Integer, String> matchByType = match( ifIs((Integer x) -> x % 2 == 0, x -> x + ", well, that's one of those even numbers"), ifIs(x -> x < 0, x -> x + " is one of those banker's negative number thingies") ).otherwise(x -> x + " is a regular, god-fearing number for god-fearing folks"); assertThat(matchByType.apply(2), is("2, well, that's one of those even numbers")); assertThat(matchByType.apply(-6), is("-6, well, that's one of those even numbers")); assertThat(matchByType.apply(3), is("3 is a regular, god-fearing number for god-fearing folks")); assertThat(matchByType.apply(-9), is("-9 is one of those banker's negative number thingies")); } @Test public void canMatchOnTestPassingArgument() {
String matchByResult = matchValue(4,
unruly/control
src/main/java/co/unruly/control/result/Match.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // }
import java.util.function.Function; import java.util.stream.Stream; import static co.unruly.control.Piper.pipe; import static co.unruly.control.HigherOrderFunctions.compose; import static co.unruly.control.result.Resolvers.ifFailed;
package co.unruly.control.result; /** * A small DSL for building compact dispatch tables: better than if-expressions, worse than * proper pattern matching. But hey, it's Java, what do you expect? * * This models a match attempt as a sequence of operations on a Result, starting with a Failure * and continuously trying to use flatMapFailure to convert that Result into a Success. */ public class Match { /** * Builds a dispatch function from the provided matchers. Note that in order to yield * a function, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) {
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // Path: src/main/java/co/unruly/control/result/Match.java import java.util.function.Function; import java.util.stream.Stream; import static co.unruly.control.Piper.pipe; import static co.unruly.control.HigherOrderFunctions.compose; import static co.unruly.control.result.Resolvers.ifFailed; package co.unruly.control.result; /** * A small DSL for building compact dispatch tables: better than if-expressions, worse than * proper pattern matching. But hey, it's Java, what do you expect? * * This models a match attempt as a sequence of operations on a Result, starting with a Failure * and continuously trying to use flatMapFailure to convert that Result into a Success. */ public class Match { /** * Builds a dispatch function from the provided matchers. Note that in order to yield * a function, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) {
return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f));
unruly/control
src/main/java/co/unruly/control/result/Match.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // }
import java.util.function.Function; import java.util.stream.Stream; import static co.unruly.control.Piper.pipe; import static co.unruly.control.HigherOrderFunctions.compose; import static co.unruly.control.result.Resolvers.ifFailed;
package co.unruly.control.result; /** * A small DSL for building compact dispatch tables: better than if-expressions, worse than * proper pattern matching. But hey, it's Java, what do you expect? * * This models a match attempt as a sequence of operations on a Result, starting with a Failure * and continuously trying to use flatMapFailure to convert that Result into a Success. */ public class Match { /** * Builds a dispatch function from the provided matchers. Note that in order to yield * a function, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); } /** * Builds a dispatch function from the provided matchers. Note that this returns a Result, * as there's no way to determine if the dispatch table is complete: if no match is found, * returns a Failure of the input value. */ public static <I, O> Function<I, Result<O, I>> attemptMatch(Function<I, Result<O, I>>... potentialMatchers) {
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // Path: src/main/java/co/unruly/control/result/Match.java import java.util.function.Function; import java.util.stream.Stream; import static co.unruly.control.Piper.pipe; import static co.unruly.control.HigherOrderFunctions.compose; import static co.unruly.control.result.Resolvers.ifFailed; package co.unruly.control.result; /** * A small DSL for building compact dispatch tables: better than if-expressions, worse than * proper pattern matching. But hey, it's Java, what do you expect? * * This models a match attempt as a sequence of operations on a Result, starting with a Failure * and continuously trying to use flatMapFailure to convert that Result into a Success. */ public class Match { /** * Builds a dispatch function from the provided matchers. Note that in order to yield * a function, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); } /** * Builds a dispatch function from the provided matchers. Note that this returns a Result, * as there's no way to determine if the dispatch table is complete: if no match is found, * returns a Failure of the input value. */ public static <I, O> Function<I, Result<O, I>> attemptMatch(Function<I, Result<O, I>>... potentialMatchers) {
return compose(Stream.of(potentialMatchers).map(Transformers::recover)).compose(Result::failure);
unruly/control
src/main/java/co/unruly/control/result/Match.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // }
import java.util.function.Function; import java.util.stream.Stream; import static co.unruly.control.Piper.pipe; import static co.unruly.control.HigherOrderFunctions.compose; import static co.unruly.control.result.Resolvers.ifFailed;
package co.unruly.control.result; /** * A small DSL for building compact dispatch tables: better than if-expressions, worse than * proper pattern matching. But hey, it's Java, what do you expect? * * This models a match attempt as a sequence of operations on a Result, starting with a Failure * and continuously trying to use flatMapFailure to convert that Result into a Success. */ public class Match { /** * Builds a dispatch function from the provided matchers. Note that in order to yield * a function, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); } /** * Builds a dispatch function from the provided matchers. Note that this returns a Result, * as there's no way to determine if the dispatch table is complete: if no match is found, * returns a Failure of the input value. */ public static <I, O> Function<I, Result<O, I>> attemptMatch(Function<I, Result<O, I>>... potentialMatchers) { return compose(Stream.of(potentialMatchers).map(Transformers::recover)).compose(Result::failure); } /** * Dispatches a value across the provided matchers. Note that in order to yield * a value, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> BoundMatchAttempt<I, O> matchValue(I inputValue, Function<I, Result<O, I>>... potentialMatchers) {
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // Path: src/main/java/co/unruly/control/result/Match.java import java.util.function.Function; import java.util.stream.Stream; import static co.unruly.control.Piper.pipe; import static co.unruly.control.HigherOrderFunctions.compose; import static co.unruly.control.result.Resolvers.ifFailed; package co.unruly.control.result; /** * A small DSL for building compact dispatch tables: better than if-expressions, worse than * proper pattern matching. But hey, it's Java, what do you expect? * * This models a match attempt as a sequence of operations on a Result, starting with a Failure * and continuously trying to use flatMapFailure to convert that Result into a Success. */ public class Match { /** * Builds a dispatch function from the provided matchers. Note that in order to yield * a function, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> MatchAttempt<I, O> match(Function<I, Result<O, I>>... potentialMatchers) { return f -> attemptMatch(potentialMatchers).andThen(ifFailed(f)); } /** * Builds a dispatch function from the provided matchers. Note that this returns a Result, * as there's no way to determine if the dispatch table is complete: if no match is found, * returns a Failure of the input value. */ public static <I, O> Function<I, Result<O, I>> attemptMatch(Function<I, Result<O, I>>... potentialMatchers) { return compose(Stream.of(potentialMatchers).map(Transformers::recover)).compose(Result::failure); } /** * Dispatches a value across the provided matchers. Note that in order to yield * a value, the otherwise() method must be called on the result of this function: * as there's no way to determine if the dispatch table is complete, a base case is * required. */ @SafeVarargs public static <I, O> BoundMatchAttempt<I, O> matchValue(I inputValue, Function<I, Result<O, I>>... potentialMatchers) {
return f -> pipe(inputValue)
unruly/control
src/test/java/examples/ConciseEquals.java
// Path: src/main/java/co/unruly/control/casts/Equality.java // static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { // if(self==other) { // return true; // } // // if(other==null) { // return false; // } // // return pipe(other) // .then(exactCastTo((Class<T>)self.getClass())) // .then(onSuccess(o -> equalityChecker.test(self, o))) // .then(ifFailed(__ -> false)) // .resolve(); // }
import java.util.Objects; import static co.unruly.control.casts.Equality.areEqual;
package examples; /** * Just a demonstration of how we can build a cleaner way to check equality * using Result-based casts under the hood. */ public class ConciseEquals { private final int number; private final String text; public ConciseEquals(int number, String text) { this.number = number; this.text = text; } // The best of the IntelliJ inbuilt equality templates // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConciseEquals that = (ConciseEquals) o; // return number == that.number && // Objects.equals(text, that.text); // } @Override public boolean equals(Object o) {
// Path: src/main/java/co/unruly/control/casts/Equality.java // static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { // if(self==other) { // return true; // } // // if(other==null) { // return false; // } // // return pipe(other) // .then(exactCastTo((Class<T>)self.getClass())) // .then(onSuccess(o -> equalityChecker.test(self, o))) // .then(ifFailed(__ -> false)) // .resolve(); // } // Path: src/test/java/examples/ConciseEquals.java import java.util.Objects; import static co.unruly.control.casts.Equality.areEqual; package examples; /** * Just a demonstration of how we can build a cleaner way to check equality * using Result-based casts under the hood. */ public class ConciseEquals { private final int number; private final String text; public ConciseEquals(int number, String text) { this.number = number; this.text = text; } // The best of the IntelliJ inbuilt equality templates // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ConciseEquals that = (ConciseEquals) o; // return number == that.number && // Objects.equals(text, that.text); // } @Override public boolean equals(Object o) {
return areEqual(this, o, (a, b) ->
unruly/control
src/main/java/co/unruly/control/result/Introducers.java
// Path: src/main/java/co/unruly/control/ThrowingLambdas.java // public interface ThrowingLambdas { // // /** // * A Function which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingFunction<I, O, X extends Exception> { // O apply(I input) throws X; // // default <T> ThrowingFunction<I, T, X> andThen(Function<O, T> nextFunction) { // return x -> nextFunction.apply(apply(x)); // } // // default <T> ThrowingFunction<T, O, X> compose(Function<T, I> nextFunction) { // return x -> apply(nextFunction.apply(x)); // } // // /** // * Converts the provided function into a regular Function, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <I, O, X extends Exception> Function<I, O> throwingRuntime(ThrowingFunction<I, O, X> f) { // return x -> { // try { // return f.apply(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Consumer which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingConsumer<T, X extends Exception> { // void accept(T item) throws X; // // /** // * Converts the provided consumer into a regular Consumer, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <T, X extends Exception> Consumer<T> throwingRuntime(ThrowingConsumer<T, X> p) { // return x -> { // try { // p.accept(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A BiFunction which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingBiFunction<A, B, R, X extends Exception> { // R apply(A first, B second) throws X; // // /** // * Converts the provided bifunction into a regular BiFunction, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <A, B, R, X extends Exception> BiFunction<A, B, R> throwingRuntime(ThrowingBiFunction<A, B, R, X> f) { // return (a, b) -> { // try { // return f.apply(a, b); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Predicate which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingPredicate<T, X extends Exception> { // boolean test(T item) throws X; // // /** // * Converts the provided predicate into a regular Predicate, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <T, X extends Exception> Predicate<T> throwingRuntime(ThrowingPredicate<T, X> p) { // return x -> { // try { // return p.test(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // static <T, X extends Exception> Predicate<T> throwsWhen(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return false; // } catch (Exception ex) { // return true; // } // }; // } // // static <T, X extends Exception> Predicate<T> doesntThrow(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return true; // } catch (Exception ex) { // return false; // } // }; // } // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> failure(F error) { // return new Failure<>(error); // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> success(S value) { // return new Success<>(value); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import co.unruly.control.ThrowingLambdas; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import static co.unruly.control.result.Result.failure; import static co.unruly.control.result.Result.success; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.function.Function.identity;
package co.unruly.control.result; /** * A collection of sample functions which take regular values and output a Result. */ public interface Introducers { /** * Returns a Function which creates a new Success wrapping the provided value */ static <S, F> Function<S, Result<S, F>> success() { return Result::success; } /** * Returns a Function which creates a new Failure wrapping the provided value */
// Path: src/main/java/co/unruly/control/ThrowingLambdas.java // public interface ThrowingLambdas { // // /** // * A Function which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingFunction<I, O, X extends Exception> { // O apply(I input) throws X; // // default <T> ThrowingFunction<I, T, X> andThen(Function<O, T> nextFunction) { // return x -> nextFunction.apply(apply(x)); // } // // default <T> ThrowingFunction<T, O, X> compose(Function<T, I> nextFunction) { // return x -> apply(nextFunction.apply(x)); // } // // /** // * Converts the provided function into a regular Function, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <I, O, X extends Exception> Function<I, O> throwingRuntime(ThrowingFunction<I, O, X> f) { // return x -> { // try { // return f.apply(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Consumer which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingConsumer<T, X extends Exception> { // void accept(T item) throws X; // // /** // * Converts the provided consumer into a regular Consumer, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <T, X extends Exception> Consumer<T> throwingRuntime(ThrowingConsumer<T, X> p) { // return x -> { // try { // p.accept(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A BiFunction which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingBiFunction<A, B, R, X extends Exception> { // R apply(A first, B second) throws X; // // /** // * Converts the provided bifunction into a regular BiFunction, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <A, B, R, X extends Exception> BiFunction<A, B, R> throwingRuntime(ThrowingBiFunction<A, B, R, X> f) { // return (a, b) -> { // try { // return f.apply(a, b); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Predicate which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingPredicate<T, X extends Exception> { // boolean test(T item) throws X; // // /** // * Converts the provided predicate into a regular Predicate, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <T, X extends Exception> Predicate<T> throwingRuntime(ThrowingPredicate<T, X> p) { // return x -> { // try { // return p.test(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // static <T, X extends Exception> Predicate<T> throwsWhen(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return false; // } catch (Exception ex) { // return true; // } // }; // } // // static <T, X extends Exception> Predicate<T> doesntThrow(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return true; // } catch (Exception ex) { // return false; // } // }; // } // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> failure(F error) { // return new Failure<>(error); // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> success(S value) { // return new Success<>(value); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/main/java/co/unruly/control/result/Introducers.java import co.unruly.control.ThrowingLambdas; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import static co.unruly.control.result.Result.failure; import static co.unruly.control.result.Result.success; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.function.Function.identity; package co.unruly.control.result; /** * A collection of sample functions which take regular values and output a Result. */ public interface Introducers { /** * Returns a Function which creates a new Success wrapping the provided value */ static <S, F> Function<S, Result<S, F>> success() { return Result::success; } /** * Returns a Function which creates a new Failure wrapping the provided value */
static <S, F> Function<F, Result<S, F>> failure() {
unruly/control
src/main/java/co/unruly/control/result/Introducers.java
// Path: src/main/java/co/unruly/control/ThrowingLambdas.java // public interface ThrowingLambdas { // // /** // * A Function which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingFunction<I, O, X extends Exception> { // O apply(I input) throws X; // // default <T> ThrowingFunction<I, T, X> andThen(Function<O, T> nextFunction) { // return x -> nextFunction.apply(apply(x)); // } // // default <T> ThrowingFunction<T, O, X> compose(Function<T, I> nextFunction) { // return x -> apply(nextFunction.apply(x)); // } // // /** // * Converts the provided function into a regular Function, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <I, O, X extends Exception> Function<I, O> throwingRuntime(ThrowingFunction<I, O, X> f) { // return x -> { // try { // return f.apply(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Consumer which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingConsumer<T, X extends Exception> { // void accept(T item) throws X; // // /** // * Converts the provided consumer into a regular Consumer, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <T, X extends Exception> Consumer<T> throwingRuntime(ThrowingConsumer<T, X> p) { // return x -> { // try { // p.accept(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A BiFunction which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingBiFunction<A, B, R, X extends Exception> { // R apply(A first, B second) throws X; // // /** // * Converts the provided bifunction into a regular BiFunction, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <A, B, R, X extends Exception> BiFunction<A, B, R> throwingRuntime(ThrowingBiFunction<A, B, R, X> f) { // return (a, b) -> { // try { // return f.apply(a, b); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Predicate which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingPredicate<T, X extends Exception> { // boolean test(T item) throws X; // // /** // * Converts the provided predicate into a regular Predicate, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <T, X extends Exception> Predicate<T> throwingRuntime(ThrowingPredicate<T, X> p) { // return x -> { // try { // return p.test(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // static <T, X extends Exception> Predicate<T> throwsWhen(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return false; // } catch (Exception ex) { // return true; // } // }; // } // // static <T, X extends Exception> Predicate<T> doesntThrow(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return true; // } catch (Exception ex) { // return false; // } // }; // } // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> failure(F error) { // return new Failure<>(error); // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> success(S value) { // return new Success<>(value); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // }
import co.unruly.control.ThrowingLambdas; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import static co.unruly.control.result.Result.failure; import static co.unruly.control.result.Result.success; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.function.Function.identity;
* Returns a function which takes a value, applies the provided function to it, and returns * a success of the output of that function. If an exception is thrown, return a failure of * the specified failure case value. * * Whilst we take a ThrowingFunction which throws a specific checked exception type X, our * eventual Result is of the more general type Exception. That's because it's also possible for the * function to throw other types of RuntimeException, and we have two choices: don't catch (or rethrow) * RuntimeException, or have a more general failure type. Rethrowing exceptions goes against the whole * point of constraining the error path, so we opt for the latter. * * If the provided function throws an Error, we don't catch that. Errors in general are not * intended to be caught. * * Note that idiomatic handling of Exceptions as failure type does allow specialised catch blocks * on specific exception types. */ static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, F failureCase ) { return tryTo(throwingFunction, __ -> failureCase); } /** * Returns a function which takes a value, applies the provided stream-returning function to it, * and return a stream which is the stream returned by the function, with each element wrapped in * a success, or a single failure of the exception thrown by that function if it threw an exception. */ static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) {
// Path: src/main/java/co/unruly/control/ThrowingLambdas.java // public interface ThrowingLambdas { // // /** // * A Function which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingFunction<I, O, X extends Exception> { // O apply(I input) throws X; // // default <T> ThrowingFunction<I, T, X> andThen(Function<O, T> nextFunction) { // return x -> nextFunction.apply(apply(x)); // } // // default <T> ThrowingFunction<T, O, X> compose(Function<T, I> nextFunction) { // return x -> apply(nextFunction.apply(x)); // } // // /** // * Converts the provided function into a regular Function, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <I, O, X extends Exception> Function<I, O> throwingRuntime(ThrowingFunction<I, O, X> f) { // return x -> { // try { // return f.apply(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Consumer which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingConsumer<T, X extends Exception> { // void accept(T item) throws X; // // /** // * Converts the provided consumer into a regular Consumer, where any thrown exceptions are // * wrapped in a RuntimeException. // */ // static <T, X extends Exception> Consumer<T> throwingRuntime(ThrowingConsumer<T, X> p) { // return x -> { // try { // p.accept(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A BiFunction which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingBiFunction<A, B, R, X extends Exception> { // R apply(A first, B second) throws X; // // /** // * Converts the provided bifunction into a regular BiFunction, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <A, B, R, X extends Exception> BiFunction<A, B, R> throwingRuntime(ThrowingBiFunction<A, B, R, X> f) { // return (a, b) -> { // try { // return f.apply(a, b); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // /** // * A Predicate which may throw a checked exception // */ // @FunctionalInterface // interface ThrowingPredicate<T, X extends Exception> { // boolean test(T item) throws X; // // /** // * Converts the provided predicate into a regular Predicate, where any thrown exceptions // * are wrapped in a RuntimeException // */ // static <T, X extends Exception> Predicate<T> throwingRuntime(ThrowingPredicate<T, X> p) { // return x -> { // try { // return p.test(x); // } catch (Exception ex) { // throw new RuntimeException(ex); // } // }; // } // } // // static <T, X extends Exception> Predicate<T> throwsWhen(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return false; // } catch (Exception ex) { // return true; // } // }; // } // // static <T, X extends Exception> Predicate<T> doesntThrow(ThrowingConsumer<T, X> consumer) { // return t -> { // try { // consumer.accept(t); // return true; // } catch (Exception ex) { // return false; // } // }; // } // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> failure(F error) { // return new Failure<>(error); // } // // Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> success(S value) { // return new Success<>(value); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, F> Function<Result<Stream<S>, F>, Stream<Result<S, F>>> unwrapSuccesses() { // return r -> r.either( // successes -> successes.map(Result::success), // failure -> Stream.of(Result.failure(failure)) // ); // } // Path: src/main/java/co/unruly/control/result/Introducers.java import co.unruly.control.ThrowingLambdas; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import static co.unruly.control.result.Result.failure; import static co.unruly.control.result.Result.success; import static co.unruly.control.result.Transformers.unwrapSuccesses; import static java.util.function.Function.identity; * Returns a function which takes a value, applies the provided function to it, and returns * a success of the output of that function. If an exception is thrown, return a failure of * the specified failure case value. * * Whilst we take a ThrowingFunction which throws a specific checked exception type X, our * eventual Result is of the more general type Exception. That's because it's also possible for the * function to throw other types of RuntimeException, and we have two choices: don't catch (or rethrow) * RuntimeException, or have a more general failure type. Rethrowing exceptions goes against the whole * point of constraining the error path, so we opt for the latter. * * If the provided function throws an Error, we don't catch that. Errors in general are not * intended to be caught. * * Note that idiomatic handling of Exceptions as failure type does allow specialised catch blocks * on specific exception types. */ static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, F failureCase ) { return tryTo(throwingFunction, __ -> failureCase); } /** * Returns a function which takes a value, applies the provided stream-returning function to it, * and return a stream which is the stream returned by the function, with each element wrapped in * a success, or a single failure of the exception thrown by that function if it threw an exception. */ static <IS, OS, X extends Exception> Function<IS, Stream<Result<OS, Exception>>> tryAndUnwrap(ThrowingLambdas.ThrowingFunction<IS, Stream<OS>, X> f) {
return tryTo(f).andThen(unwrapSuccesses());
unruly/control
src/main/java/co/unruly/control/result/TypeOf.java
// Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // public interface HigherOrderFunctions { // // /** // * Takes a BiFunction, and reverses the order of the arguments // */ // static <A, B, R> BiFunction<B, A, R> flip(BiFunction<A, B, R> f) { // return (a, b) -> f.apply(b, a); // } // // /** // * Takes a list of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // /** // * Takes a Stream of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Stream<Function<T, T>> functions) { // return functions.reduce(identity(), Function::andThen); // } // // /** // * Takes a list of predicates and composes them into a single predicate, which // * passes when all passed-in predicates pass // */ // static <T> Predicate<T> compose(Predicate<T>... functions) { // return Stream.of(functions).reduce(__ -> true, Predicate::and); // } // // /** // * Turns a Consumer into a Function which applies the consumer and returns the input // */ // static <T> Function<T, T> peek(Consumer<T> action) { // return t -> { // action.accept(t); // return t; // }; // } // // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // } // // /** // * Zips two streams together using the zipper function, resulting in a single stream of // * items from each stream combined using the provided function. // * // * The resultant stream will have the length of the shorter of the two input streams. // * // * Sourced from https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip // */ // static <A , B, C> Stream<C> zip(Stream<A> a, Stream<B> b, BiFunction<A, B, C> zipper) { // Objects.requireNonNull(zipper); // Spliterator<? extends A> aSpliterator = Objects.requireNonNull(a).spliterator(); // Spliterator<? extends B> bSpliterator = Objects.requireNonNull(b).spliterator(); // // // Zipping looses DISTINCT and SORTED characteristics // int characteristics = aSpliterator.characteristics() & bSpliterator.characteristics() & // ~(Spliterator.DISTINCT | Spliterator.SORTED); // // long zipSize = ((characteristics & Spliterator.SIZED) != 0) // ? Math.min(aSpliterator.getExactSizeIfKnown(), bSpliterator.getExactSizeIfKnown()) // : -1; // // Iterator<A> aIterator = Spliterators.iterator(aSpliterator); // Iterator<B> bIterator = Spliterators.iterator(bSpliterator); // Iterator<C> cIterator = new Iterator<C>() { // @Override // public boolean hasNext() { // return aIterator.hasNext() && bIterator.hasNext(); // } // // @Override // public C next() { // return zipper.apply(aIterator.next(), bIterator.next()); // } // }; // // Spliterator<C> split = Spliterators.spliterator(cIterator, zipSize, characteristics); // return (a.isParallel() || b.isParallel()) // ? StreamSupport.stream(split, true) // : StreamSupport.stream(split, false); // } // // /** // * Takes two lists, and returns a list of pairs forming the Cartesian product of those lists. // */ // static <A, B> List<Pair<A, B>> pairs(List<A> as, List<B> bs) { // return as.stream().flatMap(a -> bs.stream().map(b -> Pair.of(a, b))).collect(toList()); // } // // /** // * Takes a value, and returns that same value, upcast to a suitable type. Inference is our friend here. // */ // static <R, T extends R> R upcast(T fv) { // return fv; // } // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // }
import co.unruly.control.HigherOrderFunctions; import java.util.function.Function; import static co.unruly.control.result.Transformers.onSuccess;
package co.unruly.control.result; /** * Some syntax-fu in order to get nice, readable up-casting operations on Results. * * Usage isn't totally obvious from the implementation: to upcast a success to an Animal, for example, you need: * <code> * using(TypeOf.<Animal>forSuccesses()) * </code> * * That'll give you a <code>Function<Result<Bear, String>, Function<Animal, String>></code> (inferring * the types Animal and String from context), which you can then use for mapping a Stream or use in * a Result then-operation chain. */ public interface TypeOf<T> { /** * Generalises the success type for a Result to an appropriate superclass. */ static <T, F, S extends T> Function<Result<S, F>, Result<T, F>> using(ForSuccesses<T> dummy) {
// Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // public interface HigherOrderFunctions { // // /** // * Takes a BiFunction, and reverses the order of the arguments // */ // static <A, B, R> BiFunction<B, A, R> flip(BiFunction<A, B, R> f) { // return (a, b) -> f.apply(b, a); // } // // /** // * Takes a list of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // /** // * Takes a Stream of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Stream<Function<T, T>> functions) { // return functions.reduce(identity(), Function::andThen); // } // // /** // * Takes a list of predicates and composes them into a single predicate, which // * passes when all passed-in predicates pass // */ // static <T> Predicate<T> compose(Predicate<T>... functions) { // return Stream.of(functions).reduce(__ -> true, Predicate::and); // } // // /** // * Turns a Consumer into a Function which applies the consumer and returns the input // */ // static <T> Function<T, T> peek(Consumer<T> action) { // return t -> { // action.accept(t); // return t; // }; // } // // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // } // // /** // * Zips two streams together using the zipper function, resulting in a single stream of // * items from each stream combined using the provided function. // * // * The resultant stream will have the length of the shorter of the two input streams. // * // * Sourced from https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip // */ // static <A , B, C> Stream<C> zip(Stream<A> a, Stream<B> b, BiFunction<A, B, C> zipper) { // Objects.requireNonNull(zipper); // Spliterator<? extends A> aSpliterator = Objects.requireNonNull(a).spliterator(); // Spliterator<? extends B> bSpliterator = Objects.requireNonNull(b).spliterator(); // // // Zipping looses DISTINCT and SORTED characteristics // int characteristics = aSpliterator.characteristics() & bSpliterator.characteristics() & // ~(Spliterator.DISTINCT | Spliterator.SORTED); // // long zipSize = ((characteristics & Spliterator.SIZED) != 0) // ? Math.min(aSpliterator.getExactSizeIfKnown(), bSpliterator.getExactSizeIfKnown()) // : -1; // // Iterator<A> aIterator = Spliterators.iterator(aSpliterator); // Iterator<B> bIterator = Spliterators.iterator(bSpliterator); // Iterator<C> cIterator = new Iterator<C>() { // @Override // public boolean hasNext() { // return aIterator.hasNext() && bIterator.hasNext(); // } // // @Override // public C next() { // return zipper.apply(aIterator.next(), bIterator.next()); // } // }; // // Spliterator<C> split = Spliterators.spliterator(cIterator, zipSize, characteristics); // return (a.isParallel() || b.isParallel()) // ? StreamSupport.stream(split, true) // : StreamSupport.stream(split, false); // } // // /** // * Takes two lists, and returns a list of pairs forming the Cartesian product of those lists. // */ // static <A, B> List<Pair<A, B>> pairs(List<A> as, List<B> bs) { // return as.stream().flatMap(a -> bs.stream().map(b -> Pair.of(a, b))).collect(toList()); // } // // /** // * Takes a value, and returns that same value, upcast to a suitable type. Inference is our friend here. // */ // static <R, T extends R> R upcast(T fv) { // return fv; // } // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // Path: src/main/java/co/unruly/control/result/TypeOf.java import co.unruly.control.HigherOrderFunctions; import java.util.function.Function; import static co.unruly.control.result.Transformers.onSuccess; package co.unruly.control.result; /** * Some syntax-fu in order to get nice, readable up-casting operations on Results. * * Usage isn't totally obvious from the implementation: to upcast a success to an Animal, for example, you need: * <code> * using(TypeOf.<Animal>forSuccesses()) * </code> * * That'll give you a <code>Function<Result<Bear, String>, Function<Animal, String>></code> (inferring * the types Animal and String from context), which you can then use for mapping a Stream or use in * a Result then-operation chain. */ public interface TypeOf<T> { /** * Generalises the success type for a Result to an appropriate superclass. */ static <T, F, S extends T> Function<Result<S, F>, Result<T, F>> using(ForSuccesses<T> dummy) {
return result -> result.then(onSuccess(HigherOrderFunctions::upcast));
unruly/control
src/main/java/co/unruly/control/result/TypeOf.java
// Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // public interface HigherOrderFunctions { // // /** // * Takes a BiFunction, and reverses the order of the arguments // */ // static <A, B, R> BiFunction<B, A, R> flip(BiFunction<A, B, R> f) { // return (a, b) -> f.apply(b, a); // } // // /** // * Takes a list of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // /** // * Takes a Stream of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Stream<Function<T, T>> functions) { // return functions.reduce(identity(), Function::andThen); // } // // /** // * Takes a list of predicates and composes them into a single predicate, which // * passes when all passed-in predicates pass // */ // static <T> Predicate<T> compose(Predicate<T>... functions) { // return Stream.of(functions).reduce(__ -> true, Predicate::and); // } // // /** // * Turns a Consumer into a Function which applies the consumer and returns the input // */ // static <T> Function<T, T> peek(Consumer<T> action) { // return t -> { // action.accept(t); // return t; // }; // } // // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // } // // /** // * Zips two streams together using the zipper function, resulting in a single stream of // * items from each stream combined using the provided function. // * // * The resultant stream will have the length of the shorter of the two input streams. // * // * Sourced from https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip // */ // static <A , B, C> Stream<C> zip(Stream<A> a, Stream<B> b, BiFunction<A, B, C> zipper) { // Objects.requireNonNull(zipper); // Spliterator<? extends A> aSpliterator = Objects.requireNonNull(a).spliterator(); // Spliterator<? extends B> bSpliterator = Objects.requireNonNull(b).spliterator(); // // // Zipping looses DISTINCT and SORTED characteristics // int characteristics = aSpliterator.characteristics() & bSpliterator.characteristics() & // ~(Spliterator.DISTINCT | Spliterator.SORTED); // // long zipSize = ((characteristics & Spliterator.SIZED) != 0) // ? Math.min(aSpliterator.getExactSizeIfKnown(), bSpliterator.getExactSizeIfKnown()) // : -1; // // Iterator<A> aIterator = Spliterators.iterator(aSpliterator); // Iterator<B> bIterator = Spliterators.iterator(bSpliterator); // Iterator<C> cIterator = new Iterator<C>() { // @Override // public boolean hasNext() { // return aIterator.hasNext() && bIterator.hasNext(); // } // // @Override // public C next() { // return zipper.apply(aIterator.next(), bIterator.next()); // } // }; // // Spliterator<C> split = Spliterators.spliterator(cIterator, zipSize, characteristics); // return (a.isParallel() || b.isParallel()) // ? StreamSupport.stream(split, true) // : StreamSupport.stream(split, false); // } // // /** // * Takes two lists, and returns a list of pairs forming the Cartesian product of those lists. // */ // static <A, B> List<Pair<A, B>> pairs(List<A> as, List<B> bs) { // return as.stream().flatMap(a -> bs.stream().map(b -> Pair.of(a, b))).collect(toList()); // } // // /** // * Takes a value, and returns that same value, upcast to a suitable type. Inference is our friend here. // */ // static <R, T extends R> R upcast(T fv) { // return fv; // } // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // }
import co.unruly.control.HigherOrderFunctions; import java.util.function.Function; import static co.unruly.control.result.Transformers.onSuccess;
package co.unruly.control.result; /** * Some syntax-fu in order to get nice, readable up-casting operations on Results. * * Usage isn't totally obvious from the implementation: to upcast a success to an Animal, for example, you need: * <code> * using(TypeOf.<Animal>forSuccesses()) * </code> * * That'll give you a <code>Function<Result<Bear, String>, Function<Animal, String>></code> (inferring * the types Animal and String from context), which you can then use for mapping a Stream or use in * a Result then-operation chain. */ public interface TypeOf<T> { /** * Generalises the success type for a Result to an appropriate superclass. */ static <T, F, S extends T> Function<Result<S, F>, Result<T, F>> using(ForSuccesses<T> dummy) {
// Path: src/main/java/co/unruly/control/HigherOrderFunctions.java // public interface HigherOrderFunctions { // // /** // * Takes a BiFunction, and reverses the order of the arguments // */ // static <A, B, R> BiFunction<B, A, R> flip(BiFunction<A, B, R> f) { // return (a, b) -> f.apply(b, a); // } // // /** // * Takes a list of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Function<T, T>... functions) { // return compose(Stream.of(functions)); // } // // /** // * Takes a Stream of functions (which take and return the same type) and composes // * them into a single function, applying the provided functions in order // */ // static <T> Function<T, T> compose(Stream<Function<T, T>> functions) { // return functions.reduce(identity(), Function::andThen); // } // // /** // * Takes a list of predicates and composes them into a single predicate, which // * passes when all passed-in predicates pass // */ // static <T> Predicate<T> compose(Predicate<T>... functions) { // return Stream.of(functions).reduce(__ -> true, Predicate::and); // } // // /** // * Turns a Consumer into a Function which applies the consumer and returns the input // */ // static <T> Function<T, T> peek(Consumer<T> action) { // return t -> { // action.accept(t); // return t; // }; // } // // static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) { // return zip(iterate(0, x -> x + 1), items); // } // // static <A, B> Stream<Pair<A, B>> zip(Stream<A> a, Stream<B> b) { // return zip(a, b, Pair::of); // } // // /** // * Zips two streams together using the zipper function, resulting in a single stream of // * items from each stream combined using the provided function. // * // * The resultant stream will have the length of the shorter of the two input streams. // * // * Sourced from https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip // */ // static <A , B, C> Stream<C> zip(Stream<A> a, Stream<B> b, BiFunction<A, B, C> zipper) { // Objects.requireNonNull(zipper); // Spliterator<? extends A> aSpliterator = Objects.requireNonNull(a).spliterator(); // Spliterator<? extends B> bSpliterator = Objects.requireNonNull(b).spliterator(); // // // Zipping looses DISTINCT and SORTED characteristics // int characteristics = aSpliterator.characteristics() & bSpliterator.characteristics() & // ~(Spliterator.DISTINCT | Spliterator.SORTED); // // long zipSize = ((characteristics & Spliterator.SIZED) != 0) // ? Math.min(aSpliterator.getExactSizeIfKnown(), bSpliterator.getExactSizeIfKnown()) // : -1; // // Iterator<A> aIterator = Spliterators.iterator(aSpliterator); // Iterator<B> bIterator = Spliterators.iterator(bSpliterator); // Iterator<C> cIterator = new Iterator<C>() { // @Override // public boolean hasNext() { // return aIterator.hasNext() && bIterator.hasNext(); // } // // @Override // public C next() { // return zipper.apply(aIterator.next(), bIterator.next()); // } // }; // // Spliterator<C> split = Spliterators.spliterator(cIterator, zipSize, characteristics); // return (a.isParallel() || b.isParallel()) // ? StreamSupport.stream(split, true) // : StreamSupport.stream(split, false); // } // // /** // * Takes two lists, and returns a list of pairs forming the Cartesian product of those lists. // */ // static <A, B> List<Pair<A, B>> pairs(List<A> as, List<B> bs) { // return as.stream().flatMap(a -> bs.stream().map(b -> Pair.of(a, b))).collect(toList()); // } // // /** // * Takes a value, and returns that same value, upcast to a suitable type. Inference is our friend here. // */ // static <R, T extends R> R upcast(T fv) { // return fv; // } // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // Path: src/main/java/co/unruly/control/result/TypeOf.java import co.unruly.control.HigherOrderFunctions; import java.util.function.Function; import static co.unruly.control.result.Transformers.onSuccess; package co.unruly.control.result; /** * Some syntax-fu in order to get nice, readable up-casting operations on Results. * * Usage isn't totally obvious from the implementation: to upcast a success to an Animal, for example, you need: * <code> * using(TypeOf.<Animal>forSuccesses()) * </code> * * That'll give you a <code>Function<Result<Bear, String>, Function<Animal, String>></code> (inferring * the types Animal and String from context), which you can then use for mapping a Stream or use in * a Result then-operation chain. */ public interface TypeOf<T> { /** * Generalises the success type for a Result to an appropriate superclass. */ static <T, F, S extends T> Function<Result<S, F>, Result<T, F>> using(ForSuccesses<T> dummy) {
return result -> result.then(onSuccess(HigherOrderFunctions::upcast));
unruly/control
src/main/java/co/unruly/control/result/Combiners.java
// Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> success(S value) { // return new Success<>(value); // }
import java.util.function.BiFunction; import java.util.function.Function; import static co.unruly.control.result.Result.success;
package co.unruly.control.result; public interface Combiners { /** * Combines two Results into a single Result. If both arguments are a Success, then * it applies the given function to their values and returns a Success of it. * * If either or both arguments are Failures, then this returns the first failure * it encountered. */ static <A, B, F> Function<Result<A, F>, MergeableResults<A, B, F>> combineWith(Result<B, F> secondArgument) { // ugh ugh ugh we need an abstract class because otherwise it can't infer generics properly can i be sick now? ta return result -> new MergeableResults<A, B, F>() { @Override public <C> Result<C, F> using(BiFunction<A, B, C> combiner) { return result.either( s1 -> secondArgument.either(
// Path: src/main/java/co/unruly/control/result/Result.java // public static <S, F> Result<S, F> success(S value) { // return new Success<>(value); // } // Path: src/main/java/co/unruly/control/result/Combiners.java import java.util.function.BiFunction; import java.util.function.Function; import static co.unruly.control.result.Result.success; package co.unruly.control.result; public interface Combiners { /** * Combines two Results into a single Result. If both arguments are a Success, then * it applies the given function to their values and returns a Success of it. * * If either or both arguments are Failures, then this returns the first failure * it encountered. */ static <A, B, F> Function<Result<A, F>, MergeableResults<A, B, F>> combineWith(Result<B, F> secondArgument) { // ugh ugh ugh we need an abstract class because otherwise it can't infer generics properly can i be sick now? ta return result -> new MergeableResults<A, B, F>() { @Override public <C> Result<C, F> using(BiFunction<A, B, C> combiner) { return result.either( s1 -> secondArgument.either(
s2 -> success(combiner.apply(s1, s2)),
unruly/control
src/main/java/co/unruly/control/casts/Equality.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // }
import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess;
package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; }
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // Path: src/main/java/co/unruly/control/casts/Equality.java import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess; package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; }
return pipe(other)
unruly/control
src/main/java/co/unruly/control/casts/Equality.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // }
import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess;
package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; } return pipe(other)
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // Path: src/main/java/co/unruly/control/casts/Equality.java import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess; package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; } return pipe(other)
.then(exactCastTo((Class<T>)self.getClass()))
unruly/control
src/main/java/co/unruly/control/casts/Equality.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // }
import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess;
package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; } return pipe(other) .then(exactCastTo((Class<T>)self.getClass()))
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // Path: src/main/java/co/unruly/control/casts/Equality.java import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess; package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; } return pipe(other) .then(exactCastTo((Class<T>)self.getClass()))
.then(onSuccess(o -> equalityChecker.test(self, o)))
unruly/control
src/main/java/co/unruly/control/casts/Equality.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // }
import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess;
package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; } return pipe(other) .then(exactCastTo((Class<T>)self.getClass())) .then(onSuccess(o -> equalityChecker.test(self, o)))
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // @SuppressWarnings("unchecked") // static <IS, OS extends IS> Function<IS, Result<OS, IS>> exactCastTo(Class<OS> targetClass) { // return input -> targetClass.equals(input.getClass()) // ? Result.success((OS)input) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Resolvers.java // static <OS, IS extends OS, FS extends OS, F> Function<Result<IS, F>, OS> ifFailed(Function<F, FS> recoveryFunction) { // return r -> r.either(identity(), recoveryFunction); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F> Function<Result<IS, F>, Result<OS, F>> onSuccess(Function<IS, OS> mappingFunction) { // return attempt(mappingFunction.andThen(Result::success)); // } // Path: src/main/java/co/unruly/control/casts/Equality.java import java.util.function.BiPredicate; import static co.unruly.control.Piper.pipe; import static co.unruly.control.result.Introducers.exactCastTo; import static co.unruly.control.result.Resolvers.ifFailed; import static co.unruly.control.result.Transformers.onSuccess; package co.unruly.control.casts; public interface Equality { static <T> boolean areEqual(T self, Object other, BiPredicate<T, T> equalityChecker) { if(self==other) { return true; } if(other==null) { return false; } return pipe(other) .then(exactCastTo((Class<T>)self.getClass())) .then(onSuccess(o -> equalityChecker.test(self, o)))
.then(ifFailed(__ -> false))
unruly/control
src/test/java/co/unruly/control/result/PiperTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // }
import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);");
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // Path: src/test/java/co/unruly/control/result/PiperTest.java import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);");
Result<Integer, String> result = pipe("a=1234;")
unruly/control
src/test/java/co/unruly/control/result/PiperTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // }
import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher)
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // Path: src/test/java/co/unruly/control/result/PiperTest.java import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher)
.then(ifIs(Matcher::find, m -> m.group(1)))
unruly/control
src/test/java/co/unruly/control/result/PiperTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // }
import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1)))
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // Path: src/test/java/co/unruly/control/result/PiperTest.java import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1)))
.then(onFailure(__ -> "Could not find group to match"))
unruly/control
src/test/java/co/unruly/control/result/PiperTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // }
import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match"))
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // Path: src/test/java/co/unruly/control/result/PiperTest.java import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match"))
.then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage())))
unruly/control
src/test/java/co/unruly/control/result/PiperTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // }
import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match"))
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // Path: src/test/java/co/unruly/control/result/PiperTest.java import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match"))
.then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage())))
unruly/control
src/test/java/co/unruly/control/result/PiperTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // }
import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match")) .then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage()))) .resolve();
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // Path: src/test/java/co/unruly/control/result/PiperTest.java import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match")) .then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage()))) .resolve();
assertThat(result, isSuccessOf(1234));
unruly/control
src/test/java/co/unruly/control/result/PiperTest.java
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // }
import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat;
package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match")) .then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage()))) .resolve(); assertThat(result, isSuccessOf(1234)); } @Test public void canChainSeveralOperationsBeforeOneWhichMayFail2() { Pattern pattern = Pattern.compile("a=([^;]);"); Result<Integer, String> result = pipe("cheeseburger") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match")) .then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage()))) .resolve();
// Path: src/main/java/co/unruly/control/Piper.java // public static <T> Piper<T> pipe(T element) { // return new Piper<T>(element); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isFailureOf(F expectedValue) { // return isFailureThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/matchers/ResultMatchers.java // public static <S, F> Matcher<Result<S, F>> isSuccessOf(S expectedValue) { // return isSuccessThat(equalTo(expectedValue)); // } // // Path: src/main/java/co/unruly/control/result/Recover.java // static <S, F> Function<F, Result<S, F>> ifIs(Predicate<F> test, Function<F, S> mapper) { // return input -> test.test(input) // ? Result.success(mapper.apply(input)) // : Result.failure(input); // } // // Path: src/main/java/co/unruly/control/result/Introducers.java // static <IS, OS, X extends Exception, F> Function<IS, Result<OS, F>> tryTo( // ThrowingLambdas.ThrowingFunction<IS, OS, X> throwingFunction, // Function<Exception, F> exceptionMapper // ) { // return input -> { // try { // return Result.success(throwingFunction.apply(input)); // } catch (Exception ex) { // return Result.failure(exceptionMapper.apply(ex)); // } // }; // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <IS, OS, F, OF extends F> Function<Result<IS, F>, Result<OS, F>> attempt(Function<IS, Result<OS, OF>> mappingFunction) { // return r -> r.either(mappingFunction.andThen(onFailure((Function<OF, F>) (fv) -> HigherOrderFunctions.upcast(fv))), Result::failure); // } // // Path: src/main/java/co/unruly/control/result/Transformers.java // static <S, IF, OF> Function<Result<S, IF>, Result<S, OF>> onFailure(Function<IF, OF> mappingFunction) { // return recover(mappingFunction.andThen(Result::failure)); // } // Path: src/test/java/co/unruly/control/result/PiperTest.java import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; import static co.unruly.control.Piper.pipe; import static co.unruly.control.matchers.ResultMatchers.isFailureOf; import static co.unruly.control.matchers.ResultMatchers.isSuccessOf; import static co.unruly.control.result.Recover.ifIs; import static co.unruly.control.result.Introducers.tryTo; import static co.unruly.control.result.Transformers.attempt; import static co.unruly.control.result.Transformers.onFailure; import static org.junit.Assert.assertThat; package co.unruly.control.result; public class PiperTest { @Test public void canChainSeveralOperationsBeforeOneWhichMayFail() { Pattern pattern = Pattern.compile("a=([^;]+);"); Result<Integer, String> result = pipe("a=1234;") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match")) .then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage()))) .resolve(); assertThat(result, isSuccessOf(1234)); } @Test public void canChainSeveralOperationsBeforeOneWhichMayFail2() { Pattern pattern = Pattern.compile("a=([^;]);"); Result<Integer, String> result = pipe("cheeseburger") .then(pattern::matcher) .then(ifIs(Matcher::find, m -> m.group(1))) .then(onFailure(__ -> "Could not find group to match")) .then(attempt(tryTo(Integer::parseInt, ex -> ex.getMessage()))) .resolve();
assertThat(result, isFailureOf("Could not find group to match"));
unruly/control
src/main/java/co/unruly/control/HigherOrderFunctions.java
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // }
import co.unruly.control.pair.Pair; import java.util.*; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.Stream.iterate;
package co.unruly.control; public interface HigherOrderFunctions { /** * Takes a BiFunction, and reverses the order of the arguments */ static <A, B, R> BiFunction<B, A, R> flip(BiFunction<A, B, R> f) { return (a, b) -> f.apply(b, a); } /** * Takes a list of functions (which take and return the same type) and composes * them into a single function, applying the provided functions in order */ static <T> Function<T, T> compose(Function<T, T>... functions) { return compose(Stream.of(functions)); } /** * Takes a Stream of functions (which take and return the same type) and composes * them into a single function, applying the provided functions in order */ static <T> Function<T, T> compose(Stream<Function<T, T>> functions) { return functions.reduce(identity(), Function::andThen); } /** * Takes a list of predicates and composes them into a single predicate, which * passes when all passed-in predicates pass */ static <T> Predicate<T> compose(Predicate<T>... functions) { return Stream.of(functions).reduce(__ -> true, Predicate::and); } /** * Turns a Consumer into a Function which applies the consumer and returns the input */ static <T> Function<T, T> peek(Consumer<T> action) { return t -> { action.accept(t); return t; }; }
// Path: src/main/java/co/unruly/control/pair/Pair.java // public class Pair<L, R> { // // public final L left; // public final R right; // // public Pair(L left, R right) { // this.left = left; // this.right = right; // } // // public static <L, R> Pair<L, R> of(L left, R right) { // return new Pair<>(left, right); // } // // /** // * Gets the left element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public L left() { // return left; // } // // /** // * Gets the right element. Note that Pair also supports direct member access, but this is useful when you need // * a method reference to extract one side of the pair. // */ // public R right() { // return right; // // } // // /** // * Applies the given function to this pair. // */ // public <T> T then(Function<Pair<L, R>, T> function) { // return function.apply(this); // } // // /** // * Applies the given bifunction to this pair, using left for the first argument and right for the second // */ // public <T> T then(BiFunction<L, R, T> function) { // return function.apply(this.left, this.right); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair<?, ?> pair = (Pair<?, ?>) o; // return Objects.equals(left, pair.left) && // Objects.equals(right, pair.right); // } // // @Override // public int hashCode() { // return Objects.hash(left, right); // } // // @Override // public String toString() { // return "Pair{" + // "left=" + left + // ", right=" + right + // '}'; // } // } // Path: src/main/java/co/unruly/control/HigherOrderFunctions.java import co.unruly.control.pair.Pair; import java.util.*; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.Stream.iterate; package co.unruly.control; public interface HigherOrderFunctions { /** * Takes a BiFunction, and reverses the order of the arguments */ static <A, B, R> BiFunction<B, A, R> flip(BiFunction<A, B, R> f) { return (a, b) -> f.apply(b, a); } /** * Takes a list of functions (which take and return the same type) and composes * them into a single function, applying the provided functions in order */ static <T> Function<T, T> compose(Function<T, T>... functions) { return compose(Stream.of(functions)); } /** * Takes a Stream of functions (which take and return the same type) and composes * them into a single function, applying the provided functions in order */ static <T> Function<T, T> compose(Stream<Function<T, T>> functions) { return functions.reduce(identity(), Function::andThen); } /** * Takes a list of predicates and composes them into a single predicate, which * passes when all passed-in predicates pass */ static <T> Predicate<T> compose(Predicate<T>... functions) { return Stream.of(functions).reduce(__ -> true, Predicate::and); } /** * Turns a Consumer into a Function which applies the consumer and returns the input */ static <T> Function<T, T> peek(Consumer<T> action) { return t -> { action.accept(t); return t; }; }
static <T> Stream<Pair<Integer, T>> withIndices(Stream<T> items) {
ccjeng/News
app/src/main/java/com/ccjeng/news/controler/web/NewsHandler.java
// Path: app/src/main/java/com/ccjeng/news/controler/HttpClient.java // public class HttpClient { // // private static OkHttpClient client; // // private HttpClient(){ // } // // /* OkHttpClient Singleton // * */ // public static OkHttpClient getHttpClient() { // if (client == null) { // synchronized (HttpClient.class) { // if (client == null) { // client = new OkHttpClient(); // } // } // } // return client; // } // // }
import android.util.Log; import com.ccjeng.news.controler.HttpClient; import java.io.IOException; import java.io.UnsupportedEncodingException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Request; import rx.Observable; import rx.Subscriber;
package com.ccjeng.news.controler.web; /** * Created by andycheng on 2015/11/15. */ public class NewsHandler { private static final String TAG = "NewsHandler"; private String url; public NewsHandler( String url) { this.url = url; } public Observable<String> getNewsContent(final String charset) { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> subscriber) { final Request request = new Request.Builder() .url(url) .build();
// Path: app/src/main/java/com/ccjeng/news/controler/HttpClient.java // public class HttpClient { // // private static OkHttpClient client; // // private HttpClient(){ // } // // /* OkHttpClient Singleton // * */ // public static OkHttpClient getHttpClient() { // if (client == null) { // synchronized (HttpClient.class) { // if (client == null) { // client = new OkHttpClient(); // } // } // } // return client; // } // // } // Path: app/src/main/java/com/ccjeng/news/controler/web/NewsHandler.java import android.util.Log; import com.ccjeng.news.controler.HttpClient; import java.io.IOException; import java.io.UnsupportedEncodingException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Request; import rx.Observable; import rx.Subscriber; package com.ccjeng.news.controler.web; /** * Created by andycheng on 2015/11/15. */ public class NewsHandler { private static final String TAG = "NewsHandler"; private String url; public NewsHandler( String url) { this.url = url; } public Observable<String> getNewsContent(final String charset) { return Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> subscriber) { final Request request = new Request.Builder() .url(url) .build();
HttpClient.getHttpClient().newCall(request).enqueue(new Callback() {
ccjeng/News
app/src/main/java/com/ccjeng/news/presenter/NewsRSSListView.java
// Path: app/src/main/java/com/ccjeng/news/controler/rss/RSSFeed.java // public class RSSFeed { // // private String title = null; //news title // private int itemCount; //count // private List<RSSItem> itemList; //all items // // // public RSSFeed() { // itemList = new ArrayList<RSSItem>(); // } // // /** // * Add one RSSItem into RSSFeed // * @param item // * @return // */ // public int addItem(RSSItem item) { // itemList.add(item); // itemCount ++; // return itemCount; // } // // public void removeItem(RSSItem item) { // itemList.remove(item); // } // // public RSSItem getItem(int location) { // return itemList.get(location); // } // // /** // * Return all items // * @return // */ // public List<RSSItem> getAllItems() { // return itemList; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public int getItemCount() { // return itemCount; // } // }
import com.ccjeng.news.controler.rss.RSSFeed;
package com.ccjeng.news.presenter; /** * Created by andycheng on 2016/9/22. */ public interface NewsRSSListView { void refreshData(); void showError(int message);
// Path: app/src/main/java/com/ccjeng/news/controler/rss/RSSFeed.java // public class RSSFeed { // // private String title = null; //news title // private int itemCount; //count // private List<RSSItem> itemList; //all items // // // public RSSFeed() { // itemList = new ArrayList<RSSItem>(); // } // // /** // * Add one RSSItem into RSSFeed // * @param item // * @return // */ // public int addItem(RSSItem item) { // itemList.add(item); // itemCount ++; // return itemCount; // } // // public void removeItem(RSSItem item) { // itemList.remove(item); // } // // public RSSItem getItem(int location) { // return itemList.get(location); // } // // /** // * Return all items // * @return // */ // public List<RSSItem> getAllItems() { // return itemList; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public int getItemCount() { // return itemCount; // } // } // Path: app/src/main/java/com/ccjeng/news/presenter/NewsRSSListView.java import com.ccjeng.news.controler.rss.RSSFeed; package com.ccjeng.news.presenter; /** * Created by andycheng on 2016/9/22. */ public interface NewsRSSListView { void refreshData(); void showError(int message);
void setListView(RSSFeed rssFeed);
ccjeng/News
app/src/main/java/com/ccjeng/news/controler/rss/RSSItem.java
// Path: app/src/main/java/com/ccjeng/news/utils/DateTimeFormater.java // public class DateTimeFormater { // private static final String TAG = "DateTimeFormater"; // public static String parse(String datetime){ // // String strDT = ""; // if(datetime == null){ // return ""; // } // // //todo format error: format error: 新頭殼 hide // datetime = datetime.replace(", ",",").replace(" +"," +"); //Fix ETToday format issue: Thu,24 Dec 2015 12:51:00 // // //Storm // //if(datetime.substring(datetime.length()-3, datetime.length()-2).equals(":")){ // // datetime = datetime.trim() + " +0800"; // //}; // // //String dateFromatFrom = "EEE, dd MMM yyyy HH:mm:ss zzz"; // String dateFromatFrom = "EEE,dd MMM yyyy HH:mm:ss zzz"; // String dateFromatTo = "yyyy-MM-dd HH:mm"; // String timeZone = "GMT+8"; // SimpleDateFormat sdfFrom = new SimpleDateFormat(dateFromatFrom, Locale.US); // SimpleDateFormat sdfTo = new SimpleDateFormat(dateFromatTo, Locale.US); // // sdfFrom.setTimeZone(TimeZone.getTimeZone(timeZone)); // // try { // //if not valid, it will throw ParseException // Date date = sdfFrom.parse(datetime); // strDT = sdfTo.format(date); // //Log.d(TAG, datetime +"--" +strDT); // return strDT; // // } catch (ParseException e) { // Log.d(TAG, "ParseException=" + e.toString()); // Log.d(TAG, datetime); // // // e.printStackTrace(); // return datetime; // } // // //return strDT; // } // }
import android.util.Log; import com.ccjeng.news.utils.DateTimeFormater; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element;
package com.ccjeng.news.controler.rss; public class RSSItem { private static final String TAG = "RSSItem"; public static final String TITLE = "title"; public static final String PUBDATE = "pubDate"; private String title = null; private String link = null; private String pubDate = null; private String description = null; private String category = null; private String img = null; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getPubDate() {
// Path: app/src/main/java/com/ccjeng/news/utils/DateTimeFormater.java // public class DateTimeFormater { // private static final String TAG = "DateTimeFormater"; // public static String parse(String datetime){ // // String strDT = ""; // if(datetime == null){ // return ""; // } // // //todo format error: format error: 新頭殼 hide // datetime = datetime.replace(", ",",").replace(" +"," +"); //Fix ETToday format issue: Thu,24 Dec 2015 12:51:00 // // //Storm // //if(datetime.substring(datetime.length()-3, datetime.length()-2).equals(":")){ // // datetime = datetime.trim() + " +0800"; // //}; // // //String dateFromatFrom = "EEE, dd MMM yyyy HH:mm:ss zzz"; // String dateFromatFrom = "EEE,dd MMM yyyy HH:mm:ss zzz"; // String dateFromatTo = "yyyy-MM-dd HH:mm"; // String timeZone = "GMT+8"; // SimpleDateFormat sdfFrom = new SimpleDateFormat(dateFromatFrom, Locale.US); // SimpleDateFormat sdfTo = new SimpleDateFormat(dateFromatTo, Locale.US); // // sdfFrom.setTimeZone(TimeZone.getTimeZone(timeZone)); // // try { // //if not valid, it will throw ParseException // Date date = sdfFrom.parse(datetime); // strDT = sdfTo.format(date); // //Log.d(TAG, datetime +"--" +strDT); // return strDT; // // } catch (ParseException e) { // Log.d(TAG, "ParseException=" + e.toString()); // Log.d(TAG, datetime); // // // e.printStackTrace(); // return datetime; // } // // //return strDT; // } // } // Path: app/src/main/java/com/ccjeng/news/controler/rss/RSSItem.java import android.util.Log; import com.ccjeng.news.utils.DateTimeFormater; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; package com.ccjeng.news.controler.rss; public class RSSItem { private static final String TAG = "RSSItem"; public static final String TITLE = "title"; public static final String PUBDATE = "pubDate"; private String title = null; private String link = null; private String pubDate = null; private String description = null; private String category = null; private String img = null; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getPubDate() {
return DateTimeFormater.parse(pubDate);
ccjeng/News
app/src/main/java/com/ccjeng/news/utils/PreferenceSetting.java
// Path: app/src/main/java/com/ccjeng/news/view/base/BaseApplication.java // public class BaseApplication extends MultiDexApplication { // // public static final boolean APPDEBUG = BuildConfig.DEBUG; // // @Override // public void onCreate() { // super.onCreate(); // //LeakCanary.install(this); // //this.registerActivityLifecycleCallbacks(ActivityStack.getInstance()); // } // // /* Global Variables // * */ // private static String mPrefFontSize = ""; // public static String getPrefFontSize(){ // return mPrefFontSize; // } // public static void setPrefFontSize(String s){ // mPrefFontSize = s; // } // // private static String mPrefFontColor = ""; // public static String getPrefFontColor(){ // return mPrefFontColor; // } // public static void setPrefFontColor(String s){ // mPrefFontColor = s; // } // // private static String mPrefBGColor = ""; // public static String getPrefBGColor(){ // return mPrefBGColor; // } // public static void setPretBGColor(String s){ // mPrefBGColor = s; // } // // private static Boolean mPrefSmartSave = false; // public static Boolean getPrefSmartSave(){ // return mPrefSmartSave; // } // public static void setPretSmartSave(Boolean s){ // mPrefSmartSave = s; // } // // private static Integer mPrefDefaultTab = 0; // public static Integer getPrefDefaultTab(){ // return mPrefDefaultTab; // } // public static void setPretDefaultTab(Integer s){ // mPrefDefaultTab = s; // } // // // The following line should be changed to include the correct property id. // private static final String PROPERTY_ID = "UA-19743390-22"; // public enum TrackerName { // APP_TRACKER // Tracker used only in this app. // } // HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>(); // // public synchronized Tracker getTracker(TrackerName trackerId) { // if (!mTrackers.containsKey(trackerId)) { // // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); // if (APPDEBUG) { // analytics.getInstance(this).setDryRun(true); // } // Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID) // : analytics.newTracker(R.xml.global_tracker); // t.enableAdvertisingIdCollection(true); // mTrackers.put(trackerId, t); // } // return mTrackers.get(trackerId); // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.ccjeng.news.view.base.BaseApplication;
package com.ccjeng.news.utils; /** * Created by andycheng on 2015/11/28. */ public class PreferenceSetting { private static final String TAG = "PreferenceSetting"; public static void getPreference(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String fontSize = prefs.getString("font_size", "1"); String fontColor = prefs.getString("font_color", "#000000"); String bgColor = prefs.getString("bg_color", "#FFFFFF"); Boolean smartSave = prefs.getBoolean("smart_save", false); Boolean enableSmartSave = false; Integer defaultTab = Integer.valueOf(prefs.getString("defaulttab", "0")); if (smartSave) { if (!Network.isWifiAvailable(context)) { enableSmartSave = true; } }
// Path: app/src/main/java/com/ccjeng/news/view/base/BaseApplication.java // public class BaseApplication extends MultiDexApplication { // // public static final boolean APPDEBUG = BuildConfig.DEBUG; // // @Override // public void onCreate() { // super.onCreate(); // //LeakCanary.install(this); // //this.registerActivityLifecycleCallbacks(ActivityStack.getInstance()); // } // // /* Global Variables // * */ // private static String mPrefFontSize = ""; // public static String getPrefFontSize(){ // return mPrefFontSize; // } // public static void setPrefFontSize(String s){ // mPrefFontSize = s; // } // // private static String mPrefFontColor = ""; // public static String getPrefFontColor(){ // return mPrefFontColor; // } // public static void setPrefFontColor(String s){ // mPrefFontColor = s; // } // // private static String mPrefBGColor = ""; // public static String getPrefBGColor(){ // return mPrefBGColor; // } // public static void setPretBGColor(String s){ // mPrefBGColor = s; // } // // private static Boolean mPrefSmartSave = false; // public static Boolean getPrefSmartSave(){ // return mPrefSmartSave; // } // public static void setPretSmartSave(Boolean s){ // mPrefSmartSave = s; // } // // private static Integer mPrefDefaultTab = 0; // public static Integer getPrefDefaultTab(){ // return mPrefDefaultTab; // } // public static void setPretDefaultTab(Integer s){ // mPrefDefaultTab = s; // } // // // The following line should be changed to include the correct property id. // private static final String PROPERTY_ID = "UA-19743390-22"; // public enum TrackerName { // APP_TRACKER // Tracker used only in this app. // } // HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>(); // // public synchronized Tracker getTracker(TrackerName trackerId) { // if (!mTrackers.containsKey(trackerId)) { // // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); // if (APPDEBUG) { // analytics.getInstance(this).setDryRun(true); // } // Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID) // : analytics.newTracker(R.xml.global_tracker); // t.enableAdvertisingIdCollection(true); // mTrackers.put(trackerId, t); // } // return mTrackers.get(trackerId); // } // // } // Path: app/src/main/java/com/ccjeng/news/utils/PreferenceSetting.java import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import com.ccjeng.news.view.base.BaseApplication; package com.ccjeng.news.utils; /** * Created by andycheng on 2015/11/28. */ public class PreferenceSetting { private static final String TAG = "PreferenceSetting"; public static void getPreference(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String fontSize = prefs.getString("font_size", "1"); String fontColor = prefs.getString("font_color", "#000000"); String bgColor = prefs.getString("bg_color", "#FFFFFF"); Boolean smartSave = prefs.getBoolean("smart_save", false); Boolean enableSmartSave = false; Integer defaultTab = Integer.valueOf(prefs.getString("defaulttab", "0")); if (smartSave) { if (!Network.isWifiAvailable(context)) { enableSmartSave = true; } }
BaseApplication.setPrefFontSize(fontSize);
ccjeng/News
app/src/main/java/com/ccjeng/news/view/TabFragment.java
// Path: app/src/main/java/com/ccjeng/news/view/adapter/NewsCategoryAdapter.java // public class NewsCategoryAdapter extends RecyclerView.Adapter<NewsCategoryAdapter.CustomViewHolder>{ // // private String[] mArrayString; // private Context mContext; // // public NewsCategoryAdapter(Context context) { // this.mContext = context; // } // // public void setData(String[] arrayString) { // this.mArrayString = arrayString; // notifyDataSetChanged(); // } // // @Override // public CustomViewHolder onCreateViewHolder(ViewGroup parent, int i) { // View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_item, parent, false); // // CustomViewHolder viewHolder = new CustomViewHolder(view); // // return viewHolder; // } // // @Override // public void onBindViewHolder(CustomViewHolder customViewHolder, int i) { // //Setting text view title // customViewHolder.textView.setText(mArrayString[i]); // } // // @Override // public int getItemCount() { // return (null != mArrayString ? mArrayString.length : 0); // } // // public class CustomViewHolder extends RecyclerView.ViewHolder { // //protected ImageView imageView; // protected TextView textView; // // public CustomViewHolder(View view) { // super(view); // //this.imageView = (ImageView) view.findViewById(R.id.icon); // this.textView = (TextView) view.findViewById(R.id.row); // } // // } // } // // Path: app/src/main/java/com/ccjeng/news/view/adapter/RecyclerItemClickListener.java // public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { // private OnItemClickListener mListener; // // public interface OnItemClickListener { // public void onItemClick(View view, int position); // } // // GestureDetector mGestureDetector; // // public RecyclerItemClickListener(Context context, OnItemClickListener listener) { // mListener = listener; // mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { // @Override // public boolean onSingleTapUp(MotionEvent e) { // return true; // } // }); // } // // @Override // public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { // View childView = view.findChildViewUnder(e.getX(), e.getY()); // if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { // mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); // } // return false; // } // // @Override // public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { // } // // @Override // public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import com.ccjeng.news.R; import com.ccjeng.news.view.adapter.NewsCategoryAdapter; import com.ccjeng.news.view.adapter.RecyclerItemClickListener;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); FrameLayout fl = new FrameLayout(getActivity()); fl.setLayoutParams(params); RecyclerView v = new RecyclerView(getActivity()); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); v.setLayoutManager(llm); v.setHasFixedSize(true); switch (position) { case 0: newsSource = getResources().getStringArray(R.array.newsSourceTW); tabName = "TW"; break; case 1: newsSource = getResources().getStringArray(R.array.newsSourceHK); tabName = "HK"; break; case 2: newsSource = getResources().getStringArray(R.array.newsSourceSG); tabName = "SG"; break; }
// Path: app/src/main/java/com/ccjeng/news/view/adapter/NewsCategoryAdapter.java // public class NewsCategoryAdapter extends RecyclerView.Adapter<NewsCategoryAdapter.CustomViewHolder>{ // // private String[] mArrayString; // private Context mContext; // // public NewsCategoryAdapter(Context context) { // this.mContext = context; // } // // public void setData(String[] arrayString) { // this.mArrayString = arrayString; // notifyDataSetChanged(); // } // // @Override // public CustomViewHolder onCreateViewHolder(ViewGroup parent, int i) { // View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_item, parent, false); // // CustomViewHolder viewHolder = new CustomViewHolder(view); // // return viewHolder; // } // // @Override // public void onBindViewHolder(CustomViewHolder customViewHolder, int i) { // //Setting text view title // customViewHolder.textView.setText(mArrayString[i]); // } // // @Override // public int getItemCount() { // return (null != mArrayString ? mArrayString.length : 0); // } // // public class CustomViewHolder extends RecyclerView.ViewHolder { // //protected ImageView imageView; // protected TextView textView; // // public CustomViewHolder(View view) { // super(view); // //this.imageView = (ImageView) view.findViewById(R.id.icon); // this.textView = (TextView) view.findViewById(R.id.row); // } // // } // } // // Path: app/src/main/java/com/ccjeng/news/view/adapter/RecyclerItemClickListener.java // public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { // private OnItemClickListener mListener; // // public interface OnItemClickListener { // public void onItemClick(View view, int position); // } // // GestureDetector mGestureDetector; // // public RecyclerItemClickListener(Context context, OnItemClickListener listener) { // mListener = listener; // mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { // @Override // public boolean onSingleTapUp(MotionEvent e) { // return true; // } // }); // } // // @Override // public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { // View childView = view.findChildViewUnder(e.getX(), e.getY()); // if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { // mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); // } // return false; // } // // @Override // public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { // } // // @Override // public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // } // Path: app/src/main/java/com/ccjeng/news/view/TabFragment.java import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import com.ccjeng.news.R; import com.ccjeng.news.view.adapter.NewsCategoryAdapter; import com.ccjeng.news.view.adapter.RecyclerItemClickListener; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); FrameLayout fl = new FrameLayout(getActivity()); fl.setLayoutParams(params); RecyclerView v = new RecyclerView(getActivity()); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); v.setLayoutManager(llm); v.setHasFixedSize(true); switch (position) { case 0: newsSource = getResources().getStringArray(R.array.newsSourceTW); tabName = "TW"; break; case 1: newsSource = getResources().getStringArray(R.array.newsSourceHK); tabName = "HK"; break; case 2: newsSource = getResources().getStringArray(R.array.newsSourceSG); tabName = "SG"; break; }
NewsCategoryAdapter adapter = new NewsCategoryAdapter(getActivity());
ccjeng/News
app/src/main/java/com/ccjeng/news/view/TabFragment.java
// Path: app/src/main/java/com/ccjeng/news/view/adapter/NewsCategoryAdapter.java // public class NewsCategoryAdapter extends RecyclerView.Adapter<NewsCategoryAdapter.CustomViewHolder>{ // // private String[] mArrayString; // private Context mContext; // // public NewsCategoryAdapter(Context context) { // this.mContext = context; // } // // public void setData(String[] arrayString) { // this.mArrayString = arrayString; // notifyDataSetChanged(); // } // // @Override // public CustomViewHolder onCreateViewHolder(ViewGroup parent, int i) { // View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_item, parent, false); // // CustomViewHolder viewHolder = new CustomViewHolder(view); // // return viewHolder; // } // // @Override // public void onBindViewHolder(CustomViewHolder customViewHolder, int i) { // //Setting text view title // customViewHolder.textView.setText(mArrayString[i]); // } // // @Override // public int getItemCount() { // return (null != mArrayString ? mArrayString.length : 0); // } // // public class CustomViewHolder extends RecyclerView.ViewHolder { // //protected ImageView imageView; // protected TextView textView; // // public CustomViewHolder(View view) { // super(view); // //this.imageView = (ImageView) view.findViewById(R.id.icon); // this.textView = (TextView) view.findViewById(R.id.row); // } // // } // } // // Path: app/src/main/java/com/ccjeng/news/view/adapter/RecyclerItemClickListener.java // public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { // private OnItemClickListener mListener; // // public interface OnItemClickListener { // public void onItemClick(View view, int position); // } // // GestureDetector mGestureDetector; // // public RecyclerItemClickListener(Context context, OnItemClickListener listener) { // mListener = listener; // mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { // @Override // public boolean onSingleTapUp(MotionEvent e) { // return true; // } // }); // } // // @Override // public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { // View childView = view.findChildViewUnder(e.getX(), e.getY()); // if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { // mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); // } // return false; // } // // @Override // public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { // } // // @Override // public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // }
import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import com.ccjeng.news.R; import com.ccjeng.news.view.adapter.NewsCategoryAdapter; import com.ccjeng.news.view.adapter.RecyclerItemClickListener;
FrameLayout fl = new FrameLayout(getActivity()); fl.setLayoutParams(params); RecyclerView v = new RecyclerView(getActivity()); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); v.setLayoutManager(llm); v.setHasFixedSize(true); switch (position) { case 0: newsSource = getResources().getStringArray(R.array.newsSourceTW); tabName = "TW"; break; case 1: newsSource = getResources().getStringArray(R.array.newsSourceHK); tabName = "HK"; break; case 2: newsSource = getResources().getStringArray(R.array.newsSourceSG); tabName = "SG"; break; } NewsCategoryAdapter adapter = new NewsCategoryAdapter(getActivity()); v.setAdapter(adapter); adapter.setData(newsSource); v.addOnItemTouchListener(
// Path: app/src/main/java/com/ccjeng/news/view/adapter/NewsCategoryAdapter.java // public class NewsCategoryAdapter extends RecyclerView.Adapter<NewsCategoryAdapter.CustomViewHolder>{ // // private String[] mArrayString; // private Context mContext; // // public NewsCategoryAdapter(Context context) { // this.mContext = context; // } // // public void setData(String[] arrayString) { // this.mArrayString = arrayString; // notifyDataSetChanged(); // } // // @Override // public CustomViewHolder onCreateViewHolder(ViewGroup parent, int i) { // View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_item, parent, false); // // CustomViewHolder viewHolder = new CustomViewHolder(view); // // return viewHolder; // } // // @Override // public void onBindViewHolder(CustomViewHolder customViewHolder, int i) { // //Setting text view title // customViewHolder.textView.setText(mArrayString[i]); // } // // @Override // public int getItemCount() { // return (null != mArrayString ? mArrayString.length : 0); // } // // public class CustomViewHolder extends RecyclerView.ViewHolder { // //protected ImageView imageView; // protected TextView textView; // // public CustomViewHolder(View view) { // super(view); // //this.imageView = (ImageView) view.findViewById(R.id.icon); // this.textView = (TextView) view.findViewById(R.id.row); // } // // } // } // // Path: app/src/main/java/com/ccjeng/news/view/adapter/RecyclerItemClickListener.java // public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { // private OnItemClickListener mListener; // // public interface OnItemClickListener { // public void onItemClick(View view, int position); // } // // GestureDetector mGestureDetector; // // public RecyclerItemClickListener(Context context, OnItemClickListener listener) { // mListener = listener; // mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { // @Override // public boolean onSingleTapUp(MotionEvent e) { // return true; // } // }); // } // // @Override // public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { // View childView = view.findChildViewUnder(e.getX(), e.getY()); // if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { // mListener.onItemClick(childView, view.getChildAdapterPosition(childView)); // } // return false; // } // // @Override // public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { // } // // @Override // public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { // // } // } // Path: app/src/main/java/com/ccjeng/news/view/TabFragment.java import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import com.ccjeng.news.R; import com.ccjeng.news.view.adapter.NewsCategoryAdapter; import com.ccjeng.news.view.adapter.RecyclerItemClickListener; FrameLayout fl = new FrameLayout(getActivity()); fl.setLayoutParams(params); RecyclerView v = new RecyclerView(getActivity()); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); v.setLayoutManager(llm); v.setHasFixedSize(true); switch (position) { case 0: newsSource = getResources().getStringArray(R.array.newsSourceTW); tabName = "TW"; break; case 1: newsSource = getResources().getStringArray(R.array.newsSourceHK); tabName = "HK"; break; case 2: newsSource = getResources().getStringArray(R.array.newsSourceSG); tabName = "SG"; break; } NewsCategoryAdapter adapter = new NewsCategoryAdapter(getActivity()); v.setAdapter(adapter); adapter.setData(newsSource); v.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
ccjeng/News
app/src/main/java/com/ccjeng/news/parser/Standard.java
// Path: app/src/main/java/com/ccjeng/news/utils/WebPage.java // public class Webpage { // private static final String TAG = "Webpage"; // // public static String htmlDrawer(String title, String time, String body) { // // String htmlTagStart = "<body bgcolor=" + BaseApplication.getPrefBGColor() // + "><font color="+ BaseApplication.getPrefFontColor()+">"; // // String htmlTagEnd = "</font></body>"; // // String fontSize = "<font size=+"+ BaseApplication.getPrefFontSize() +">"; // // String html = htmlTagStart + "<h2>" + title + "</h2>" // + "<div>" + time + "</div>"; // // html = html + "<hr>"; // // // if (BaseApplication.getPrefSmartSave()) { // Log.d(TAG, "enable smart save"); // String smartSaveTag = "<small><small>[這是圖片,已啟用智能節費,停止圖片下載]</small></small></br></br>"; // body = body.replace("<img src", smartSaveTag + "<imgsrc"); // } // html = html + fontSize + body + "</font>" + htmlTagEnd; // // return html; // } // // // public static int dip2px(Context context, float dpValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dpValue * scale + 0.5f); // } // // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // // // public static double getWidth(NewsView context) { // int width = 0; // DisplayMetrics dm = new DisplayMetrics(); // context.getWindowManager().getDefaultDisplay().getMetrics(dm); // Configuration config = context.getResources().getConfiguration(); // //int vWidth = 0; // if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) // width = dm.heightPixels; // else // width = dm.widthPixels; // // return Webpage.px2dip(context, width); // // } // }
import android.util.Log; import com.ccjeng.news.utils.Webpage; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Whitelist; import java.io.IOException;
package com.ccjeng.news.parser; /** * Created by andycheng on 2015/11/19. */ public class Standard extends AbstractNews { private static final String TAG = "Standard"; @Override public String parseHtml(final String link, String content) throws IOException { Document doc = Jsoup.parse(content); String title =""; String time = ""; String body = content; Log.d(TAG, "title = " + title); Log.d(TAG, "time = " + time); Log.d(TAG, "body = " + body);
// Path: app/src/main/java/com/ccjeng/news/utils/WebPage.java // public class Webpage { // private static final String TAG = "Webpage"; // // public static String htmlDrawer(String title, String time, String body) { // // String htmlTagStart = "<body bgcolor=" + BaseApplication.getPrefBGColor() // + "><font color="+ BaseApplication.getPrefFontColor()+">"; // // String htmlTagEnd = "</font></body>"; // // String fontSize = "<font size=+"+ BaseApplication.getPrefFontSize() +">"; // // String html = htmlTagStart + "<h2>" + title + "</h2>" // + "<div>" + time + "</div>"; // // html = html + "<hr>"; // // // if (BaseApplication.getPrefSmartSave()) { // Log.d(TAG, "enable smart save"); // String smartSaveTag = "<small><small>[這是圖片,已啟用智能節費,停止圖片下載]</small></small></br></br>"; // body = body.replace("<img src", smartSaveTag + "<imgsrc"); // } // html = html + fontSize + body + "</font>" + htmlTagEnd; // // return html; // } // // // public static int dip2px(Context context, float dpValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dpValue * scale + 0.5f); // } // // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // } // // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // // // public static double getWidth(NewsView context) { // int width = 0; // DisplayMetrics dm = new DisplayMetrics(); // context.getWindowManager().getDefaultDisplay().getMetrics(dm); // Configuration config = context.getResources().getConfiguration(); // //int vWidth = 0; // if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) // width = dm.heightPixels; // else // width = dm.widthPixels; // // return Webpage.px2dip(context, width); // // } // } // Path: app/src/main/java/com/ccjeng/news/parser/Standard.java import android.util.Log; import com.ccjeng.news.utils.Webpage; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Whitelist; import java.io.IOException; package com.ccjeng.news.parser; /** * Created by andycheng on 2015/11/19. */ public class Standard extends AbstractNews { private static final String TAG = "Standard"; @Override public String parseHtml(final String link, String content) throws IOException { Document doc = Jsoup.parse(content); String title =""; String time = ""; String body = content; Log.d(TAG, "title = " + title); Log.d(TAG, "time = " + time); Log.d(TAG, "body = " + body);
return Webpage.htmlDrawer(title, time, cleaner(body));
ccjeng/News
app/src/main/java/com/ccjeng/news/utils/Analytics.java
// Path: app/src/main/java/com/ccjeng/news/view/base/BaseApplication.java // public class BaseApplication extends MultiDexApplication { // // public static final boolean APPDEBUG = BuildConfig.DEBUG; // // @Override // public void onCreate() { // super.onCreate(); // //LeakCanary.install(this); // //this.registerActivityLifecycleCallbacks(ActivityStack.getInstance()); // } // // /* Global Variables // * */ // private static String mPrefFontSize = ""; // public static String getPrefFontSize(){ // return mPrefFontSize; // } // public static void setPrefFontSize(String s){ // mPrefFontSize = s; // } // // private static String mPrefFontColor = ""; // public static String getPrefFontColor(){ // return mPrefFontColor; // } // public static void setPrefFontColor(String s){ // mPrefFontColor = s; // } // // private static String mPrefBGColor = ""; // public static String getPrefBGColor(){ // return mPrefBGColor; // } // public static void setPretBGColor(String s){ // mPrefBGColor = s; // } // // private static Boolean mPrefSmartSave = false; // public static Boolean getPrefSmartSave(){ // return mPrefSmartSave; // } // public static void setPretSmartSave(Boolean s){ // mPrefSmartSave = s; // } // // private static Integer mPrefDefaultTab = 0; // public static Integer getPrefDefaultTab(){ // return mPrefDefaultTab; // } // public static void setPretDefaultTab(Integer s){ // mPrefDefaultTab = s; // } // // // The following line should be changed to include the correct property id. // private static final String PROPERTY_ID = "UA-19743390-22"; // public enum TrackerName { // APP_TRACKER // Tracker used only in this app. // } // HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>(); // // public synchronized Tracker getTracker(TrackerName trackerId) { // if (!mTrackers.containsKey(trackerId)) { // // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); // if (APPDEBUG) { // analytics.getInstance(this).setDryRun(true); // } // Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID) // : analytics.newTracker(R.xml.global_tracker); // t.enableAdvertisingIdCollection(true); // mTrackers.put(trackerId, t); // } // return mTrackers.get(trackerId); // } // // }
import android.app.Activity; import com.ccjeng.news.view.base.BaseApplication; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker;
package com.ccjeng.news.utils; /** * Created by andycheng on 2015/6/28. */ public class Analytics { public static void trackerPage(Activity activity) {
// Path: app/src/main/java/com/ccjeng/news/view/base/BaseApplication.java // public class BaseApplication extends MultiDexApplication { // // public static final boolean APPDEBUG = BuildConfig.DEBUG; // // @Override // public void onCreate() { // super.onCreate(); // //LeakCanary.install(this); // //this.registerActivityLifecycleCallbacks(ActivityStack.getInstance()); // } // // /* Global Variables // * */ // private static String mPrefFontSize = ""; // public static String getPrefFontSize(){ // return mPrefFontSize; // } // public static void setPrefFontSize(String s){ // mPrefFontSize = s; // } // // private static String mPrefFontColor = ""; // public static String getPrefFontColor(){ // return mPrefFontColor; // } // public static void setPrefFontColor(String s){ // mPrefFontColor = s; // } // // private static String mPrefBGColor = ""; // public static String getPrefBGColor(){ // return mPrefBGColor; // } // public static void setPretBGColor(String s){ // mPrefBGColor = s; // } // // private static Boolean mPrefSmartSave = false; // public static Boolean getPrefSmartSave(){ // return mPrefSmartSave; // } // public static void setPretSmartSave(Boolean s){ // mPrefSmartSave = s; // } // // private static Integer mPrefDefaultTab = 0; // public static Integer getPrefDefaultTab(){ // return mPrefDefaultTab; // } // public static void setPretDefaultTab(Integer s){ // mPrefDefaultTab = s; // } // // // The following line should be changed to include the correct property id. // private static final String PROPERTY_ID = "UA-19743390-22"; // public enum TrackerName { // APP_TRACKER // Tracker used only in this app. // } // HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>(); // // public synchronized Tracker getTracker(TrackerName trackerId) { // if (!mTrackers.containsKey(trackerId)) { // // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); // if (APPDEBUG) { // analytics.getInstance(this).setDryRun(true); // } // Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID) // : analytics.newTracker(R.xml.global_tracker); // t.enableAdvertisingIdCollection(true); // mTrackers.put(trackerId, t); // } // return mTrackers.get(trackerId); // } // // } // Path: app/src/main/java/com/ccjeng/news/utils/Analytics.java import android.app.Activity; import com.ccjeng.news.view.base.BaseApplication; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; package com.ccjeng.news.utils; /** * Created by andycheng on 2015/6/28. */ public class Analytics { public static void trackerPage(Activity activity) {
Tracker t = ((BaseApplication) activity.getApplication()).getTracker(
diecode/KillerMoney
src/net/diecode/killermoney/events/KMCCommandExecutionEvent.java
// Path: src/net/diecode/killermoney/objects/CCommand.java // public class CCommand { // // private String command; // private String permission; // private double chance; // private int limit; // private HashMap<UUID, Integer> limitCounter = new HashMap<UUID, Integer>(); // // public CCommand(String command, String permission, double chance, int limit) { // this.command = command; // this.permission = permission; // this.chance = chance; // this.limit = limit; // } // // public String getCommand() { // return command; // } // // public String getPermission() { // return permission; // } // // public double getChance() { // return chance; // } // // public int getLimit() { // return limit; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public HashMap<UUID, Integer> getLimitCounter() { // return limitCounter; // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // if (limitCounter.containsKey(uuid)) { // int current = limitCounter.get(uuid); // // if (current >= limit) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // int current = limitCounter.get(uuid); // // limitCounter.put(uuid, current + 1); // } else { // limitCounter.put(uuid, 1); // } // } // // public int getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return 0; // } // }
import net.diecode.killermoney.objects.CCommand; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList;
package net.diecode.killermoney.events; public class KMCCommandExecutionEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
// Path: src/net/diecode/killermoney/objects/CCommand.java // public class CCommand { // // private String command; // private String permission; // private double chance; // private int limit; // private HashMap<UUID, Integer> limitCounter = new HashMap<UUID, Integer>(); // // public CCommand(String command, String permission, double chance, int limit) { // this.command = command; // this.permission = permission; // this.chance = chance; // this.limit = limit; // } // // public String getCommand() { // return command; // } // // public String getPermission() { // return permission; // } // // public double getChance() { // return chance; // } // // public int getLimit() { // return limit; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public HashMap<UUID, Integer> getLimitCounter() { // return limitCounter; // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // if (limitCounter.containsKey(uuid)) { // int current = limitCounter.get(uuid); // // if (current >= limit) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // int current = limitCounter.get(uuid); // // limitCounter.put(uuid, current + 1); // } else { // limitCounter.put(uuid, 1); // } // } // // public int getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return 0; // } // } // Path: src/net/diecode/killermoney/events/KMCCommandExecutionEvent.java import net.diecode.killermoney.objects.CCommand; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; package net.diecode.killermoney.events; public class KMCCommandExecutionEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
private CCommand cCommand;
diecode/KillerMoney
src/net/diecode/killermoney/events/KMGlobalMultiplierChangeEvent.java
// Path: src/net/diecode/killermoney/functions/MultiplierHandler.java // public class MultiplierHandler implements Listener { // // private static double globalMultiplier = 1; // private static BukkitTask timer; // private static int minuteLeft; // // @EventHandler // public void onGlobalMultiplierChange(KMGlobalMultiplierChangeEvent e) { // if (e.isCancelled()) { // return; // } // // if (e.getNewValue() == 1) { // cancel(); // // LanguageManager.send(e.getSender(), LanguageString.MULTIPLIER_CANCEL_CUSTOM_MULTIPLIER); // } else { // set(e.getNewValue(), e.getMinute()); // // LanguageManager.send(e.getSender(), LanguageString.MULTIPLIER_SET_NEW_MULTIPLIER_VALUE, // MultiplierHandler.getGlobalMultiplier(), Utils.getRemainingTimeHumanFormat(e.getMinute())); // } // } // // private static void set(final double newMultiplier, int minute) { // if (timer != null) { // timer.cancel(); // } // // globalMultiplier = newMultiplier; // minuteLeft = minute; // // timer = Bukkit.getScheduler().runTaskTimer(BukkitMain.getInstance(), new Runnable() { // @Override // public void run() { // minuteLeft--; // // if (minuteLeft < 1) { // cancel(); // } // } // }, 20L * 60, 20L * 60); // } // // private static void cancel() { // if (timer != null) { // timer.cancel(); // timer = null; // } // // globalMultiplier = 1; // minuteLeft = 0; // } // // public static double getPermBasedMoneyMultiplier(Player p) { // double biggest = 1; // // if (p != null) { // for (Map.Entry<String, Double> multiplier : DefaultConfig.getPermBasedMoneyMultipliers().entrySet()) { // if (p.hasPermission(KMPermission.MONEY_MULTIPLIER.get() + "." + multiplier.getKey())) { // if (biggest < multiplier.getValue()) { // biggest = multiplier.getValue(); // } // } // } // } // // return biggest; // } // // public static double getPermBasedMoneyLimitMultiplier(Player p) { // double biggest = 1; // // if (p != null) { // for (Map.Entry<String, Double> multiplier : DefaultConfig.getPermBasedLimitMultipliers().entrySet()) { // if (p.hasPermission(KMPermission.LIMIT_MONEY_MULTIPLIER.get() + "." + multiplier.getKey())) { // if (biggest < multiplier.getValue()) { // biggest = multiplier.getValue(); // } // } // } // } // // return biggest; // } // // public static double getGlobalMultiplier() { // return globalMultiplier; // } // // public static BukkitTask getTimer() { // return timer; // } // // public static int getMinuteLeft() { // return minuteLeft; // } // }
import net.diecode.killermoney.functions.MultiplierHandler; import org.bukkit.command.CommandSender; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList;
package net.diecode.killermoney.events; public class KMGlobalMultiplierChangeEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private double newValue; private int minute; private CommandSender sender; private boolean cancelled; public KMGlobalMultiplierChangeEvent(double newValue, int minute, CommandSender sender) { this.newValue = newValue; this.minute = minute; this.sender = sender; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } public double getCurrentValue() {
// Path: src/net/diecode/killermoney/functions/MultiplierHandler.java // public class MultiplierHandler implements Listener { // // private static double globalMultiplier = 1; // private static BukkitTask timer; // private static int minuteLeft; // // @EventHandler // public void onGlobalMultiplierChange(KMGlobalMultiplierChangeEvent e) { // if (e.isCancelled()) { // return; // } // // if (e.getNewValue() == 1) { // cancel(); // // LanguageManager.send(e.getSender(), LanguageString.MULTIPLIER_CANCEL_CUSTOM_MULTIPLIER); // } else { // set(e.getNewValue(), e.getMinute()); // // LanguageManager.send(e.getSender(), LanguageString.MULTIPLIER_SET_NEW_MULTIPLIER_VALUE, // MultiplierHandler.getGlobalMultiplier(), Utils.getRemainingTimeHumanFormat(e.getMinute())); // } // } // // private static void set(final double newMultiplier, int minute) { // if (timer != null) { // timer.cancel(); // } // // globalMultiplier = newMultiplier; // minuteLeft = minute; // // timer = Bukkit.getScheduler().runTaskTimer(BukkitMain.getInstance(), new Runnable() { // @Override // public void run() { // minuteLeft--; // // if (minuteLeft < 1) { // cancel(); // } // } // }, 20L * 60, 20L * 60); // } // // private static void cancel() { // if (timer != null) { // timer.cancel(); // timer = null; // } // // globalMultiplier = 1; // minuteLeft = 0; // } // // public static double getPermBasedMoneyMultiplier(Player p) { // double biggest = 1; // // if (p != null) { // for (Map.Entry<String, Double> multiplier : DefaultConfig.getPermBasedMoneyMultipliers().entrySet()) { // if (p.hasPermission(KMPermission.MONEY_MULTIPLIER.get() + "." + multiplier.getKey())) { // if (biggest < multiplier.getValue()) { // biggest = multiplier.getValue(); // } // } // } // } // // return biggest; // } // // public static double getPermBasedMoneyLimitMultiplier(Player p) { // double biggest = 1; // // if (p != null) { // for (Map.Entry<String, Double> multiplier : DefaultConfig.getPermBasedLimitMultipliers().entrySet()) { // if (p.hasPermission(KMPermission.LIMIT_MONEY_MULTIPLIER.get() + "." + multiplier.getKey())) { // if (biggest < multiplier.getValue()) { // biggest = multiplier.getValue(); // } // } // } // } // // return biggest; // } // // public static double getGlobalMultiplier() { // return globalMultiplier; // } // // public static BukkitTask getTimer() { // return timer; // } // // public static int getMinuteLeft() { // return minuteLeft; // } // } // Path: src/net/diecode/killermoney/events/KMGlobalMultiplierChangeEvent.java import net.diecode.killermoney.functions.MultiplierHandler; import org.bukkit.command.CommandSender; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; package net.diecode.killermoney.events; public class KMGlobalMultiplierChangeEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private double newValue; private int minute; private CommandSender sender; private boolean cancelled; public KMGlobalMultiplierChangeEvent(double newValue, int minute, CommandSender sender) { this.newValue = newValue; this.minute = minute; this.sender = sender; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } public double getCurrentValue() {
return MultiplierHandler.getGlobalMultiplier();
diecode/KillerMoney
src/net/diecode/killermoney/configs/PlayersConfig.java
// Path: src/net/diecode/killermoney/BukkitMain.java // public class BukkitMain extends JavaPlugin { // // private static BukkitMain instance; // private static Metrics metrics; // // private static Economy economy; // private static MobArenaHandler mobArenaHandler; // private static Updater updater; // // private void initMetrics() { // metrics = new Metrics(this); // metrics.addCustomChart(new Metrics.SimplePie("used_message_method") { // @Override // public String getValue() { // return DefaultConfig.getMessageMethod().name().toUpperCase(); // } // }); // // metrics.addCustomChart(new Metrics.SimplePie("used_money_item_drop") { // @Override // public String getValue() { // return DefaultConfig.isMoneyItemDropEnabled() ? "Enabled" : "Disabled"; // } // }); // } // // private boolean initEconomy() { // RegisteredServiceProvider<Economy> economyProvider = // Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); // // if (economyProvider != null) { // economy = economyProvider.getProvider(); // } // // return (economy != null); // } // // private void hookMobArena() { // if (Bukkit.getPluginManager().getPlugin("MobArena") != null) { // mobArenaHandler = new MobArenaHandler(); // // Logger.info("MobArena hooked"); // } else { // Logger.info("MobArena not found"); // } // } // // @Override // public void onEnable() { // instance = this; // // ConfigManager.init(); // // updater = new Updater(); // // initMetrics(); // // if (!initEconomy()) { // Logger.warning("Vault or economy plugin not found! Money reward disabled."); // } // // if (DefaultConfig.isHookMobArena()) { // hookMobArena(); // } // // getCommand("km").setExecutor(new KMCommand()); // getCommand("kmadmin").setExecutor(new KMAdminCommand()); // // Bukkit.getPluginManager().registerEvents(new EntityManager(), this); // Bukkit.getPluginManager().registerEvents(new MoneyHandler(), this); // Bukkit.getPluginManager().registerEvents(new CItemHandler(), this); // Bukkit.getPluginManager().registerEvents(new CCommandHandler(), this); // Bukkit.getPluginManager().registerEvents(new CExpHandler(), this); // Bukkit.getPluginManager().registerEvents(new MessageHandler(), this); // Bukkit.getPluginManager().registerEvents(new CashTransferHandler(), this); // Bukkit.getPluginManager().registerEvents(new AntiFarmingHandler(), this); // Bukkit.getPluginManager().registerEvents(new LimitHandler(), this); // Bukkit.getPluginManager().registerEvents(new MultiplierHandler(), this); // Bukkit.getPluginManager().registerEvents(new KMPlayerManager(), this); // Bukkit.getPluginManager().registerEvents(updater, this); // // if (DefaultConfig.isCheckUpdate()) { // getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { // @Override // public void run() { // if (!Updater.isUpdateAvailable()) { // updater.query(); // } // } // }, 20L, 20L * 60 * 60 * 24); // } // // for (Player p : Bukkit.getOnlinePlayers()) { // UUID pUUID = p.getUniqueId(); // // if (!KMPlayerManager.getKMPlayers().containsKey(pUUID)) { // KMPlayerManager.getKMPlayers().put(pUUID, new KMPlayer(p)); // } // } // } // // @Override // public void onDisable() { // instance = null; // updater = null; // } // // public static BukkitMain getInstance() { // return instance; // } // // public static Economy getEconomy() { // return economy; // } // // public static MobArenaHandler getMobArenaHandler() { // return mobArenaHandler; // } // }
import net.diecode.killermoney.BukkitMain; import java.io.File;
package net.diecode.killermoney.configs; public class PlayersConfig { public PlayersConfig() {
// Path: src/net/diecode/killermoney/BukkitMain.java // public class BukkitMain extends JavaPlugin { // // private static BukkitMain instance; // private static Metrics metrics; // // private static Economy economy; // private static MobArenaHandler mobArenaHandler; // private static Updater updater; // // private void initMetrics() { // metrics = new Metrics(this); // metrics.addCustomChart(new Metrics.SimplePie("used_message_method") { // @Override // public String getValue() { // return DefaultConfig.getMessageMethod().name().toUpperCase(); // } // }); // // metrics.addCustomChart(new Metrics.SimplePie("used_money_item_drop") { // @Override // public String getValue() { // return DefaultConfig.isMoneyItemDropEnabled() ? "Enabled" : "Disabled"; // } // }); // } // // private boolean initEconomy() { // RegisteredServiceProvider<Economy> economyProvider = // Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); // // if (economyProvider != null) { // economy = economyProvider.getProvider(); // } // // return (economy != null); // } // // private void hookMobArena() { // if (Bukkit.getPluginManager().getPlugin("MobArena") != null) { // mobArenaHandler = new MobArenaHandler(); // // Logger.info("MobArena hooked"); // } else { // Logger.info("MobArena not found"); // } // } // // @Override // public void onEnable() { // instance = this; // // ConfigManager.init(); // // updater = new Updater(); // // initMetrics(); // // if (!initEconomy()) { // Logger.warning("Vault or economy plugin not found! Money reward disabled."); // } // // if (DefaultConfig.isHookMobArena()) { // hookMobArena(); // } // // getCommand("km").setExecutor(new KMCommand()); // getCommand("kmadmin").setExecutor(new KMAdminCommand()); // // Bukkit.getPluginManager().registerEvents(new EntityManager(), this); // Bukkit.getPluginManager().registerEvents(new MoneyHandler(), this); // Bukkit.getPluginManager().registerEvents(new CItemHandler(), this); // Bukkit.getPluginManager().registerEvents(new CCommandHandler(), this); // Bukkit.getPluginManager().registerEvents(new CExpHandler(), this); // Bukkit.getPluginManager().registerEvents(new MessageHandler(), this); // Bukkit.getPluginManager().registerEvents(new CashTransferHandler(), this); // Bukkit.getPluginManager().registerEvents(new AntiFarmingHandler(), this); // Bukkit.getPluginManager().registerEvents(new LimitHandler(), this); // Bukkit.getPluginManager().registerEvents(new MultiplierHandler(), this); // Bukkit.getPluginManager().registerEvents(new KMPlayerManager(), this); // Bukkit.getPluginManager().registerEvents(updater, this); // // if (DefaultConfig.isCheckUpdate()) { // getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { // @Override // public void run() { // if (!Updater.isUpdateAvailable()) { // updater.query(); // } // } // }, 20L, 20L * 60 * 60 * 24); // } // // for (Player p : Bukkit.getOnlinePlayers()) { // UUID pUUID = p.getUniqueId(); // // if (!KMPlayerManager.getKMPlayers().containsKey(pUUID)) { // KMPlayerManager.getKMPlayers().put(pUUID, new KMPlayer(p)); // } // } // } // // @Override // public void onDisable() { // instance = null; // updater = null; // } // // public static BukkitMain getInstance() { // return instance; // } // // public static Economy getEconomy() { // return economy; // } // // public static MobArenaHandler getMobArenaHandler() { // return mobArenaHandler; // } // } // Path: src/net/diecode/killermoney/configs/PlayersConfig.java import net.diecode.killermoney.BukkitMain; import java.io.File; package net.diecode.killermoney.configs; public class PlayersConfig { public PlayersConfig() {
File dir = new File(BukkitMain.getInstance().getDataFolder(), "/players/");
diecode/KillerMoney
src/net/diecode/killermoney/commands/subcommands/km/HelpCommand.java
// Path: src/net/diecode/killermoney/enums/KMCommandType.java // public enum KMCommandType { // // KM, KM_ADMIN // // } // // Path: src/net/diecode/killermoney/enums/SenderType.java // public enum SenderType { // // PLAYER, CONSOLE, ANYONE // // } // // Path: src/net/diecode/killermoney/objects/KMSubCommand.java // public abstract class KMSubCommand { // // protected ArrayList<KMCommandType> usable; // protected String command; // protected KMPermission permission; // protected SenderType senderType; // protected int minArgs; // protected String usage; // protected ArrayList<String> aliases; // protected ArrayList<String> acceptableValues; // // public KMSubCommand(ArrayList<KMCommandType> usable, String command) { // this.usable = usable; // this.command = command; // } // // public ArrayList<KMCommandType> getUsable() { // return usable; // } // // public String getCommand() { // return command; // } // // public KMPermission getPermission() { // return permission; // } // // public SenderType getSenderType() { // return senderType; // } // // public int getMinArgs() { // return minArgs; // } // // public String getUsage() { // return usage; // } // // public ArrayList<String> getAliases() { // return aliases; // } // // public ArrayList<String> getAcceptableValues() { // return acceptableValues; // } // // public abstract void run(CommandSender cs, String[] args); // }
import net.diecode.killermoney.enums.KMCommandType; import net.diecode.killermoney.enums.SenderType; import net.diecode.killermoney.objects.KMSubCommand; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.ArrayList;
package net.diecode.killermoney.commands.subcommands.km; public class HelpCommand extends KMSubCommand { public HelpCommand(String command) { super(
// Path: src/net/diecode/killermoney/enums/KMCommandType.java // public enum KMCommandType { // // KM, KM_ADMIN // // } // // Path: src/net/diecode/killermoney/enums/SenderType.java // public enum SenderType { // // PLAYER, CONSOLE, ANYONE // // } // // Path: src/net/diecode/killermoney/objects/KMSubCommand.java // public abstract class KMSubCommand { // // protected ArrayList<KMCommandType> usable; // protected String command; // protected KMPermission permission; // protected SenderType senderType; // protected int minArgs; // protected String usage; // protected ArrayList<String> aliases; // protected ArrayList<String> acceptableValues; // // public KMSubCommand(ArrayList<KMCommandType> usable, String command) { // this.usable = usable; // this.command = command; // } // // public ArrayList<KMCommandType> getUsable() { // return usable; // } // // public String getCommand() { // return command; // } // // public KMPermission getPermission() { // return permission; // } // // public SenderType getSenderType() { // return senderType; // } // // public int getMinArgs() { // return minArgs; // } // // public String getUsage() { // return usage; // } // // public ArrayList<String> getAliases() { // return aliases; // } // // public ArrayList<String> getAcceptableValues() { // return acceptableValues; // } // // public abstract void run(CommandSender cs, String[] args); // } // Path: src/net/diecode/killermoney/commands/subcommands/km/HelpCommand.java import net.diecode.killermoney.enums.KMCommandType; import net.diecode.killermoney.enums.SenderType; import net.diecode.killermoney.objects.KMSubCommand; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.ArrayList; package net.diecode.killermoney.commands.subcommands.km; public class HelpCommand extends KMSubCommand { public HelpCommand(String command) { super(
new ArrayList<KMCommandType>()
diecode/KillerMoney
src/net/diecode/killermoney/commands/subcommands/km/HelpCommand.java
// Path: src/net/diecode/killermoney/enums/KMCommandType.java // public enum KMCommandType { // // KM, KM_ADMIN // // } // // Path: src/net/diecode/killermoney/enums/SenderType.java // public enum SenderType { // // PLAYER, CONSOLE, ANYONE // // } // // Path: src/net/diecode/killermoney/objects/KMSubCommand.java // public abstract class KMSubCommand { // // protected ArrayList<KMCommandType> usable; // protected String command; // protected KMPermission permission; // protected SenderType senderType; // protected int minArgs; // protected String usage; // protected ArrayList<String> aliases; // protected ArrayList<String> acceptableValues; // // public KMSubCommand(ArrayList<KMCommandType> usable, String command) { // this.usable = usable; // this.command = command; // } // // public ArrayList<KMCommandType> getUsable() { // return usable; // } // // public String getCommand() { // return command; // } // // public KMPermission getPermission() { // return permission; // } // // public SenderType getSenderType() { // return senderType; // } // // public int getMinArgs() { // return minArgs; // } // // public String getUsage() { // return usage; // } // // public ArrayList<String> getAliases() { // return aliases; // } // // public ArrayList<String> getAcceptableValues() { // return acceptableValues; // } // // public abstract void run(CommandSender cs, String[] args); // }
import net.diecode.killermoney.enums.KMCommandType; import net.diecode.killermoney.enums.SenderType; import net.diecode.killermoney.objects.KMSubCommand; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.ArrayList;
package net.diecode.killermoney.commands.subcommands.km; public class HelpCommand extends KMSubCommand { public HelpCommand(String command) { super( new ArrayList<KMCommandType>() { { add(KMCommandType.KM); } }, command ); minArgs = 0;
// Path: src/net/diecode/killermoney/enums/KMCommandType.java // public enum KMCommandType { // // KM, KM_ADMIN // // } // // Path: src/net/diecode/killermoney/enums/SenderType.java // public enum SenderType { // // PLAYER, CONSOLE, ANYONE // // } // // Path: src/net/diecode/killermoney/objects/KMSubCommand.java // public abstract class KMSubCommand { // // protected ArrayList<KMCommandType> usable; // protected String command; // protected KMPermission permission; // protected SenderType senderType; // protected int minArgs; // protected String usage; // protected ArrayList<String> aliases; // protected ArrayList<String> acceptableValues; // // public KMSubCommand(ArrayList<KMCommandType> usable, String command) { // this.usable = usable; // this.command = command; // } // // public ArrayList<KMCommandType> getUsable() { // return usable; // } // // public String getCommand() { // return command; // } // // public KMPermission getPermission() { // return permission; // } // // public SenderType getSenderType() { // return senderType; // } // // public int getMinArgs() { // return minArgs; // } // // public String getUsage() { // return usage; // } // // public ArrayList<String> getAliases() { // return aliases; // } // // public ArrayList<String> getAcceptableValues() { // return acceptableValues; // } // // public abstract void run(CommandSender cs, String[] args); // } // Path: src/net/diecode/killermoney/commands/subcommands/km/HelpCommand.java import net.diecode.killermoney.enums.KMCommandType; import net.diecode.killermoney.enums.SenderType; import net.diecode.killermoney.objects.KMSubCommand; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.ArrayList; package net.diecode.killermoney.commands.subcommands.km; public class HelpCommand extends KMSubCommand { public HelpCommand(String command) { super( new ArrayList<KMCommandType>() { { add(KMCommandType.KM); } }, command ); minArgs = 0;
senderType = SenderType.ANYONE;
diecode/KillerMoney
src/net/diecode/killermoney/commands/subcommands/shared/InfoCommand.java
// Path: src/net/diecode/killermoney/BukkitMain.java // public class BukkitMain extends JavaPlugin { // // private static BukkitMain instance; // private static Metrics metrics; // // private static Economy economy; // private static MobArenaHandler mobArenaHandler; // private static Updater updater; // // private void initMetrics() { // metrics = new Metrics(this); // metrics.addCustomChart(new Metrics.SimplePie("used_message_method") { // @Override // public String getValue() { // return DefaultConfig.getMessageMethod().name().toUpperCase(); // } // }); // // metrics.addCustomChart(new Metrics.SimplePie("used_money_item_drop") { // @Override // public String getValue() { // return DefaultConfig.isMoneyItemDropEnabled() ? "Enabled" : "Disabled"; // } // }); // } // // private boolean initEconomy() { // RegisteredServiceProvider<Economy> economyProvider = // Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); // // if (economyProvider != null) { // economy = economyProvider.getProvider(); // } // // return (economy != null); // } // // private void hookMobArena() { // if (Bukkit.getPluginManager().getPlugin("MobArena") != null) { // mobArenaHandler = new MobArenaHandler(); // // Logger.info("MobArena hooked"); // } else { // Logger.info("MobArena not found"); // } // } // // @Override // public void onEnable() { // instance = this; // // ConfigManager.init(); // // updater = new Updater(); // // initMetrics(); // // if (!initEconomy()) { // Logger.warning("Vault or economy plugin not found! Money reward disabled."); // } // // if (DefaultConfig.isHookMobArena()) { // hookMobArena(); // } // // getCommand("km").setExecutor(new KMCommand()); // getCommand("kmadmin").setExecutor(new KMAdminCommand()); // // Bukkit.getPluginManager().registerEvents(new EntityManager(), this); // Bukkit.getPluginManager().registerEvents(new MoneyHandler(), this); // Bukkit.getPluginManager().registerEvents(new CItemHandler(), this); // Bukkit.getPluginManager().registerEvents(new CCommandHandler(), this); // Bukkit.getPluginManager().registerEvents(new CExpHandler(), this); // Bukkit.getPluginManager().registerEvents(new MessageHandler(), this); // Bukkit.getPluginManager().registerEvents(new CashTransferHandler(), this); // Bukkit.getPluginManager().registerEvents(new AntiFarmingHandler(), this); // Bukkit.getPluginManager().registerEvents(new LimitHandler(), this); // Bukkit.getPluginManager().registerEvents(new MultiplierHandler(), this); // Bukkit.getPluginManager().registerEvents(new KMPlayerManager(), this); // Bukkit.getPluginManager().registerEvents(updater, this); // // if (DefaultConfig.isCheckUpdate()) { // getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { // @Override // public void run() { // if (!Updater.isUpdateAvailable()) { // updater.query(); // } // } // }, 20L, 20L * 60 * 60 * 24); // } // // for (Player p : Bukkit.getOnlinePlayers()) { // UUID pUUID = p.getUniqueId(); // // if (!KMPlayerManager.getKMPlayers().containsKey(pUUID)) { // KMPlayerManager.getKMPlayers().put(pUUID, new KMPlayer(p)); // } // } // } // // @Override // public void onDisable() { // instance = null; // updater = null; // } // // public static BukkitMain getInstance() { // return instance; // } // // public static Economy getEconomy() { // return economy; // } // // public static MobArenaHandler getMobArenaHandler() { // return mobArenaHandler; // } // } // // Path: src/net/diecode/killermoney/enums/KMCommandType.java // public enum KMCommandType { // // KM, KM_ADMIN // // } // // Path: src/net/diecode/killermoney/enums/SenderType.java // public enum SenderType { // // PLAYER, CONSOLE, ANYONE // // } // // Path: src/net/diecode/killermoney/objects/KMSubCommand.java // public abstract class KMSubCommand { // // protected ArrayList<KMCommandType> usable; // protected String command; // protected KMPermission permission; // protected SenderType senderType; // protected int minArgs; // protected String usage; // protected ArrayList<String> aliases; // protected ArrayList<String> acceptableValues; // // public KMSubCommand(ArrayList<KMCommandType> usable, String command) { // this.usable = usable; // this.command = command; // } // // public ArrayList<KMCommandType> getUsable() { // return usable; // } // // public String getCommand() { // return command; // } // // public KMPermission getPermission() { // return permission; // } // // public SenderType getSenderType() { // return senderType; // } // // public int getMinArgs() { // return minArgs; // } // // public String getUsage() { // return usage; // } // // public ArrayList<String> getAliases() { // return aliases; // } // // public ArrayList<String> getAcceptableValues() { // return acceptableValues; // } // // public abstract void run(CommandSender cs, String[] args); // }
import net.diecode.killermoney.BukkitMain; import net.diecode.killermoney.enums.KMCommandType; import net.diecode.killermoney.enums.SenderType; import net.diecode.killermoney.objects.KMSubCommand; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.ArrayList;
package net.diecode.killermoney.commands.subcommands.shared; public class InfoCommand extends KMSubCommand { public InfoCommand(String command) { super(
// Path: src/net/diecode/killermoney/BukkitMain.java // public class BukkitMain extends JavaPlugin { // // private static BukkitMain instance; // private static Metrics metrics; // // private static Economy economy; // private static MobArenaHandler mobArenaHandler; // private static Updater updater; // // private void initMetrics() { // metrics = new Metrics(this); // metrics.addCustomChart(new Metrics.SimplePie("used_message_method") { // @Override // public String getValue() { // return DefaultConfig.getMessageMethod().name().toUpperCase(); // } // }); // // metrics.addCustomChart(new Metrics.SimplePie("used_money_item_drop") { // @Override // public String getValue() { // return DefaultConfig.isMoneyItemDropEnabled() ? "Enabled" : "Disabled"; // } // }); // } // // private boolean initEconomy() { // RegisteredServiceProvider<Economy> economyProvider = // Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); // // if (economyProvider != null) { // economy = economyProvider.getProvider(); // } // // return (economy != null); // } // // private void hookMobArena() { // if (Bukkit.getPluginManager().getPlugin("MobArena") != null) { // mobArenaHandler = new MobArenaHandler(); // // Logger.info("MobArena hooked"); // } else { // Logger.info("MobArena not found"); // } // } // // @Override // public void onEnable() { // instance = this; // // ConfigManager.init(); // // updater = new Updater(); // // initMetrics(); // // if (!initEconomy()) { // Logger.warning("Vault or economy plugin not found! Money reward disabled."); // } // // if (DefaultConfig.isHookMobArena()) { // hookMobArena(); // } // // getCommand("km").setExecutor(new KMCommand()); // getCommand("kmadmin").setExecutor(new KMAdminCommand()); // // Bukkit.getPluginManager().registerEvents(new EntityManager(), this); // Bukkit.getPluginManager().registerEvents(new MoneyHandler(), this); // Bukkit.getPluginManager().registerEvents(new CItemHandler(), this); // Bukkit.getPluginManager().registerEvents(new CCommandHandler(), this); // Bukkit.getPluginManager().registerEvents(new CExpHandler(), this); // Bukkit.getPluginManager().registerEvents(new MessageHandler(), this); // Bukkit.getPluginManager().registerEvents(new CashTransferHandler(), this); // Bukkit.getPluginManager().registerEvents(new AntiFarmingHandler(), this); // Bukkit.getPluginManager().registerEvents(new LimitHandler(), this); // Bukkit.getPluginManager().registerEvents(new MultiplierHandler(), this); // Bukkit.getPluginManager().registerEvents(new KMPlayerManager(), this); // Bukkit.getPluginManager().registerEvents(updater, this); // // if (DefaultConfig.isCheckUpdate()) { // getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { // @Override // public void run() { // if (!Updater.isUpdateAvailable()) { // updater.query(); // } // } // }, 20L, 20L * 60 * 60 * 24); // } // // for (Player p : Bukkit.getOnlinePlayers()) { // UUID pUUID = p.getUniqueId(); // // if (!KMPlayerManager.getKMPlayers().containsKey(pUUID)) { // KMPlayerManager.getKMPlayers().put(pUUID, new KMPlayer(p)); // } // } // } // // @Override // public void onDisable() { // instance = null; // updater = null; // } // // public static BukkitMain getInstance() { // return instance; // } // // public static Economy getEconomy() { // return economy; // } // // public static MobArenaHandler getMobArenaHandler() { // return mobArenaHandler; // } // } // // Path: src/net/diecode/killermoney/enums/KMCommandType.java // public enum KMCommandType { // // KM, KM_ADMIN // // } // // Path: src/net/diecode/killermoney/enums/SenderType.java // public enum SenderType { // // PLAYER, CONSOLE, ANYONE // // } // // Path: src/net/diecode/killermoney/objects/KMSubCommand.java // public abstract class KMSubCommand { // // protected ArrayList<KMCommandType> usable; // protected String command; // protected KMPermission permission; // protected SenderType senderType; // protected int minArgs; // protected String usage; // protected ArrayList<String> aliases; // protected ArrayList<String> acceptableValues; // // public KMSubCommand(ArrayList<KMCommandType> usable, String command) { // this.usable = usable; // this.command = command; // } // // public ArrayList<KMCommandType> getUsable() { // return usable; // } // // public String getCommand() { // return command; // } // // public KMPermission getPermission() { // return permission; // } // // public SenderType getSenderType() { // return senderType; // } // // public int getMinArgs() { // return minArgs; // } // // public String getUsage() { // return usage; // } // // public ArrayList<String> getAliases() { // return aliases; // } // // public ArrayList<String> getAcceptableValues() { // return acceptableValues; // } // // public abstract void run(CommandSender cs, String[] args); // } // Path: src/net/diecode/killermoney/commands/subcommands/shared/InfoCommand.java import net.diecode.killermoney.BukkitMain; import net.diecode.killermoney.enums.KMCommandType; import net.diecode.killermoney.enums.SenderType; import net.diecode.killermoney.objects.KMSubCommand; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import java.util.ArrayList; package net.diecode.killermoney.commands.subcommands.shared; public class InfoCommand extends KMSubCommand { public InfoCommand(String command) { super(
new ArrayList<KMCommandType>()
diecode/KillerMoney
src/net/diecode/killermoney/objects/CItemProperties.java
// Path: src/net/diecode/killermoney/enums/RunMethod.java // public enum RunMethod { // // ALL, RANDOM // // }
import net.diecode.killermoney.enums.RunMethod; import java.util.ArrayList;
package net.diecode.killermoney.objects; public class CItemProperties { private boolean keepDefaultItems = true;
// Path: src/net/diecode/killermoney/enums/RunMethod.java // public enum RunMethod { // // ALL, RANDOM // // } // Path: src/net/diecode/killermoney/objects/CItemProperties.java import net.diecode.killermoney.enums.RunMethod; import java.util.ArrayList; package net.diecode.killermoney.objects; public class CItemProperties { private boolean keepDefaultItems = true;
private RunMethod runMethod;
diecode/KillerMoney
src/net/diecode/killermoney/events/KMEarnMoneyPickedUpEvent.java
// Path: src/net/diecode/killermoney/objects/MoneyProperties.java // public class MoneyProperties { // // private EntityType entityType; // private double chance; // private double minMoney; // private double maxMoney; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public MoneyProperties(EntityType entityType, double chance, double minMoney, double maxMoney, String permission, // int limit, DivisionMethod divisionMethod, boolean enabled) { // this.entityType = entityType; // this.chance = chance; // this.minMoney = minMoney; // this.maxMoney = maxMoney; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public EntityType getEntityType() { // return entityType; // } // // public double getChance() { // return chance; // } // // public double getMinMoney() { // return minMoney; // } // // public double getMaxMoney() { // return maxMoney; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public boolean isEnabled() { // return enabled; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player != null) { // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // } // // BigDecimal limit = getLimit(player); // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.compareTo(limit) >= 0) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // // public BigDecimal getLimit(Player player) { // if (player == null) { // return new BigDecimal(limit); // } // // return new BigDecimal(limit * MultiplierHandler.getPermBasedMoneyLimitMultiplier(player)) // .setScale(DefaultConfig.getDecimalPlaces(), BigDecimal.ROUND_HALF_EVEN); // } // }
import net.diecode.killermoney.objects.MoneyProperties; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal;
package net.diecode.killermoney.events; public class KMEarnMoneyPickedUpEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
// Path: src/net/diecode/killermoney/objects/MoneyProperties.java // public class MoneyProperties { // // private EntityType entityType; // private double chance; // private double minMoney; // private double maxMoney; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public MoneyProperties(EntityType entityType, double chance, double minMoney, double maxMoney, String permission, // int limit, DivisionMethod divisionMethod, boolean enabled) { // this.entityType = entityType; // this.chance = chance; // this.minMoney = minMoney; // this.maxMoney = maxMoney; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public EntityType getEntityType() { // return entityType; // } // // public double getChance() { // return chance; // } // // public double getMinMoney() { // return minMoney; // } // // public double getMaxMoney() { // return maxMoney; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public boolean isEnabled() { // return enabled; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player != null) { // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // } // // BigDecimal limit = getLimit(player); // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.compareTo(limit) >= 0) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // // public BigDecimal getLimit(Player player) { // if (player == null) { // return new BigDecimal(limit); // } // // return new BigDecimal(limit * MultiplierHandler.getPermBasedMoneyLimitMultiplier(player)) // .setScale(DefaultConfig.getDecimalPlaces(), BigDecimal.ROUND_HALF_EVEN); // } // } // Path: src/net/diecode/killermoney/events/KMEarnMoneyPickedUpEvent.java import net.diecode.killermoney.objects.MoneyProperties; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal; package net.diecode.killermoney.events; public class KMEarnMoneyPickedUpEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
private MoneyProperties moneyProperties;
diecode/KillerMoney
src/net/diecode/killermoney/Utils.java
// Path: src/net/diecode/killermoney/enums/DivisionMethod.java // public enum DivisionMethod { // // LAST_HIT, SHARED // // } // // Path: src/net/diecode/killermoney/enums/RunMethod.java // public enum RunMethod { // // ALL, RANDOM // // }
import net.diecode.killermoney.enums.DivisionMethod; import net.diecode.killermoney.enums.RunMethod; import org.bukkit.entity.EntityType; import java.util.ArrayList; import java.util.Random;
if (max > min) { return min + (max - min) * randomNumber; } if (min > max) { return max + (min - max) * randomNumber; } return 0; } public static int randomNumber(int min, int max) { if (min == max) { return min; } return new Random().nextInt(max - min) + min; } public static boolean inEntityEnum(String entity) { for (EntityType et : EntityType.values()) { if (et.name().equalsIgnoreCase(entity)) { return true; } } return false; } public static boolean inDivisionEnum(String division) {
// Path: src/net/diecode/killermoney/enums/DivisionMethod.java // public enum DivisionMethod { // // LAST_HIT, SHARED // // } // // Path: src/net/diecode/killermoney/enums/RunMethod.java // public enum RunMethod { // // ALL, RANDOM // // } // Path: src/net/diecode/killermoney/Utils.java import net.diecode.killermoney.enums.DivisionMethod; import net.diecode.killermoney.enums.RunMethod; import org.bukkit.entity.EntityType; import java.util.ArrayList; import java.util.Random; if (max > min) { return min + (max - min) * randomNumber; } if (min > max) { return max + (min - max) * randomNumber; } return 0; } public static int randomNumber(int min, int max) { if (min == max) { return min; } return new Random().nextInt(max - min) + min; } public static boolean inEntityEnum(String entity) { for (EntityType et : EntityType.values()) { if (et.name().equalsIgnoreCase(entity)) { return true; } } return false; } public static boolean inDivisionEnum(String division) {
for (DivisionMethod div : DivisionMethod.values()) {
diecode/KillerMoney
src/net/diecode/killermoney/Utils.java
// Path: src/net/diecode/killermoney/enums/DivisionMethod.java // public enum DivisionMethod { // // LAST_HIT, SHARED // // } // // Path: src/net/diecode/killermoney/enums/RunMethod.java // public enum RunMethod { // // ALL, RANDOM // // }
import net.diecode.killermoney.enums.DivisionMethod; import net.diecode.killermoney.enums.RunMethod; import org.bukkit.entity.EntityType; import java.util.ArrayList; import java.util.Random;
public static int randomNumber(int min, int max) { if (min == max) { return min; } return new Random().nextInt(max - min) + min; } public static boolean inEntityEnum(String entity) { for (EntityType et : EntityType.values()) { if (et.name().equalsIgnoreCase(entity)) { return true; } } return false; } public static boolean inDivisionEnum(String division) { for (DivisionMethod div : DivisionMethod.values()) { if (div.name().equalsIgnoreCase(division)) { return true; } } return false; } public static boolean inRunMethodEnum(String runMethod) {
// Path: src/net/diecode/killermoney/enums/DivisionMethod.java // public enum DivisionMethod { // // LAST_HIT, SHARED // // } // // Path: src/net/diecode/killermoney/enums/RunMethod.java // public enum RunMethod { // // ALL, RANDOM // // } // Path: src/net/diecode/killermoney/Utils.java import net.diecode.killermoney.enums.DivisionMethod; import net.diecode.killermoney.enums.RunMethod; import org.bukkit.entity.EntityType; import java.util.ArrayList; import java.util.Random; public static int randomNumber(int min, int max) { if (min == max) { return min; } return new Random().nextInt(max - min) + min; } public static boolean inEntityEnum(String entity) { for (EntityType et : EntityType.values()) { if (et.name().equalsIgnoreCase(entity)) { return true; } } return false; } public static boolean inDivisionEnum(String division) { for (DivisionMethod div : DivisionMethod.values()) { if (div.name().equalsIgnoreCase(division)) { return true; } } return false; } public static boolean inRunMethodEnum(String runMethod) {
for (RunMethod rm : RunMethod.values()) {
diecode/KillerMoney
src/net/diecode/killermoney/Updater.java
// Path: src/net/diecode/killermoney/enums/KMPermission.java // public enum KMPermission { // // ADMIN("admin"), // MONEY_MULTIPLIER("money.multiplier"), // // LIMIT_MONEY_MULTIPLIER("moneylimit.multiplier"), // //LIMIT_ITEM_MULTIPLIER("itemlimit.multiplier"), // //LIMIT_COMMAND_MULTIPLIER("commandlimit.multiplier"), // // BYPASS_MONEY_LIMIT("bypass.moneylimit"), // BYPASS_ITEM_LIMIT("bypass.itemlimit"), // BYPASS_COMMAND_LIMIT("bypass.commandlimit"), // BYPASS_MONEY_LIMIT_CASH_TRANSFER("bypass.cashtransferlimit"); // // private String perm; // // KMPermission(String perm) { // this.perm = perm; // } // // public String get() { // return "km." + perm; // } // // }
import net.diecode.killermoney.enums.KMPermission; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;
// Get the version's link String versionLink = (String) latest.get(API_LINK_VALUE); // Get the version's release type String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE); // Get the version's file name String versionFileName = (String) latest.get(API_FILE_NAME_VALUE); // Get the version's game version String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE); newestVersion = versionName.replaceAll("[^\\d.]", ""); Bukkit.getScheduler().scheduleSyncDelayedTask(BukkitMain.getInstance(), new Runnable() { @Override public void run() { try { if (isNewest(newestVersion)) { updateAvailable = true; Logger.info("------------------------------"); Logger.info("| Update found!"); Logger.info("| Your version: " + BukkitMain.getInstance().getDescription().getVersion() + " | " + "New version: " + newestVersion); Logger.info("| " + BukkitMain.getInstance().getDescription().getWebsite()); Logger.info("------------------------------"); for (Player player : Bukkit.getOnlinePlayers()) {
// Path: src/net/diecode/killermoney/enums/KMPermission.java // public enum KMPermission { // // ADMIN("admin"), // MONEY_MULTIPLIER("money.multiplier"), // // LIMIT_MONEY_MULTIPLIER("moneylimit.multiplier"), // //LIMIT_ITEM_MULTIPLIER("itemlimit.multiplier"), // //LIMIT_COMMAND_MULTIPLIER("commandlimit.multiplier"), // // BYPASS_MONEY_LIMIT("bypass.moneylimit"), // BYPASS_ITEM_LIMIT("bypass.itemlimit"), // BYPASS_COMMAND_LIMIT("bypass.commandlimit"), // BYPASS_MONEY_LIMIT_CASH_TRANSFER("bypass.cashtransferlimit"); // // private String perm; // // KMPermission(String perm) { // this.perm = perm; // } // // public String get() { // return "km." + perm; // } // // } // Path: src/net/diecode/killermoney/Updater.java import net.diecode.killermoney.enums.KMPermission; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; // Get the version's link String versionLink = (String) latest.get(API_LINK_VALUE); // Get the version's release type String versionType = (String) latest.get(API_RELEASE_TYPE_VALUE); // Get the version's file name String versionFileName = (String) latest.get(API_FILE_NAME_VALUE); // Get the version's game version String versionGameVersion = (String) latest.get(API_GAME_VERSION_VALUE); newestVersion = versionName.replaceAll("[^\\d.]", ""); Bukkit.getScheduler().scheduleSyncDelayedTask(BukkitMain.getInstance(), new Runnable() { @Override public void run() { try { if (isNewest(newestVersion)) { updateAvailable = true; Logger.info("------------------------------"); Logger.info("| Update found!"); Logger.info("| Your version: " + BukkitMain.getInstance().getDescription().getVersion() + " | " + "New version: " + newestVersion); Logger.info("| " + BukkitMain.getInstance().getDescription().getWebsite()); Logger.info("------------------------------"); for (Player player : Bukkit.getOnlinePlayers()) {
if (player.isOp() || player.hasPermission(KMPermission.ADMIN.get())) {
diecode/KillerMoney
src/net/diecode/killermoney/events/KMLoseMoneyEvent.java
// Path: src/net/diecode/killermoney/objects/MoneyProperties.java // public class MoneyProperties { // // private EntityType entityType; // private double chance; // private double minMoney; // private double maxMoney; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public MoneyProperties(EntityType entityType, double chance, double minMoney, double maxMoney, String permission, // int limit, DivisionMethod divisionMethod, boolean enabled) { // this.entityType = entityType; // this.chance = chance; // this.minMoney = minMoney; // this.maxMoney = maxMoney; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public EntityType getEntityType() { // return entityType; // } // // public double getChance() { // return chance; // } // // public double getMinMoney() { // return minMoney; // } // // public double getMaxMoney() { // return maxMoney; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public boolean isEnabled() { // return enabled; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player != null) { // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // } // // BigDecimal limit = getLimit(player); // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.compareTo(limit) >= 0) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // // public BigDecimal getLimit(Player player) { // if (player == null) { // return new BigDecimal(limit); // } // // return new BigDecimal(limit * MultiplierHandler.getPermBasedMoneyLimitMultiplier(player)) // .setScale(DefaultConfig.getDecimalPlaces(), BigDecimal.ROUND_HALF_EVEN); // } // }
import net.diecode.killermoney.objects.MoneyProperties; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal;
package net.diecode.killermoney.events; public class KMLoseMoneyEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
// Path: src/net/diecode/killermoney/objects/MoneyProperties.java // public class MoneyProperties { // // private EntityType entityType; // private double chance; // private double minMoney; // private double maxMoney; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public MoneyProperties(EntityType entityType, double chance, double minMoney, double maxMoney, String permission, // int limit, DivisionMethod divisionMethod, boolean enabled) { // this.entityType = entityType; // this.chance = chance; // this.minMoney = minMoney; // this.maxMoney = maxMoney; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public EntityType getEntityType() { // return entityType; // } // // public double getChance() { // return chance; // } // // public double getMinMoney() { // return minMoney; // } // // public double getMaxMoney() { // return maxMoney; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public boolean isEnabled() { // return enabled; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player != null) { // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // } // // BigDecimal limit = getLimit(player); // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.compareTo(limit) >= 0) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // // public BigDecimal getLimit(Player player) { // if (player == null) { // return new BigDecimal(limit); // } // // return new BigDecimal(limit * MultiplierHandler.getPermBasedMoneyLimitMultiplier(player)) // .setScale(DefaultConfig.getDecimalPlaces(), BigDecimal.ROUND_HALF_EVEN); // } // } // Path: src/net/diecode/killermoney/events/KMLoseMoneyEvent.java import net.diecode.killermoney.objects.MoneyProperties; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal; package net.diecode.killermoney.events; public class KMLoseMoneyEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
private MoneyProperties moneyProperties;
diecode/KillerMoney
src/net/diecode/killermoney/objects/CExpProperties.java
// Path: src/net/diecode/killermoney/Utils.java // public class Utils { // // public static boolean chanceGenerator(double chance) { // return (Math.random() * 100) < chance; // } // // public static double randomNumber(double min, double max) { // if (min == max) { // return min; // } // // double randomNumber = new Random().nextDouble(); // // if (max > min) { // return min + (max - min) * randomNumber; // } // // if (min > max) { // return max + (min - max) * randomNumber; // } // // return 0; // } // // public static int randomNumber(int min, int max) { // if (min == max) { // return min; // } // // return new Random().nextInt(max - min) + min; // } // // public static boolean inEntityEnum(String entity) { // for (EntityType et : EntityType.values()) { // if (et.name().equalsIgnoreCase(entity)) { // return true; // } // } // // return false; // } // // public static boolean inDivisionEnum(String division) { // for (DivisionMethod div : DivisionMethod.values()) { // if (div.name().equalsIgnoreCase(division)) { // return true; // } // } // // return false; // } // // public static boolean inRunMethodEnum(String runMethod) { // for (RunMethod rm : RunMethod.values()) { // if (rm.name().equalsIgnoreCase(runMethod)) { // return true; // } // } // // return false; // } // // public static double cleanChanceString(String str) { // double chance = Double.valueOf(str.replaceAll("%", "")); // // if (chance > 100) { // chance = 100; // } // // if (chance < 1) { // chance = 1; // } // // return chance; // } // // /* // public static int getMoneyMultiplier(Player p) { // int multiplier = 1; // // for (PermissionAttachmentInfo pai : p.getEffectivePermissions()) { // String perm = pai.getPermission().toLowerCase(); // // if (perm.contains(Permissions.MONEY_MULTIPLIER.getPerm())) { // perm = perm.replace(Permissions.MONEY_MULTIPLIER.getPerm() + ".", ""); // int tmpMultiplier = Integer.valueOf(perm); // // if (tmpMultiplier > multiplier) { // multiplier = tmpMultiplier; // } // } // } // // return multiplier; // } // */ // // public static String getRemainingTimeHumanFormat(int remainingTime) { // final int MINUTES_IN_DAY = 1440; // final int MINUTES_IN_HOUR = 60; // // int minutes = remainingTime; // // int days = minutes / MINUTES_IN_DAY; // minutes = minutes - (days * MINUTES_IN_DAY); // // int hours = minutes / MINUTES_IN_HOUR; // minutes = minutes - (hours * MINUTES_IN_HOUR); // // StringBuilder sb = new StringBuilder(); // // if (days > 0) { // if (days == 1) { // sb.append(days + " day"); // } else { // sb.append(days + " days"); // } // if (hours > 0 || minutes > 0) { // sb.append(", "); // } // } // // if (hours > 0) { // if (hours == 1) { // sb.append(hours + " hour"); // } else { // sb.append(hours + " hours"); // } // if (minutes > 0) { // sb.append(", "); // } // } // // if (minutes > 0) { // if (minutes == 1) { // sb.append(minutes + " minute"); // } else { // sb.append(minutes + " minutes"); // } // } // // if (sb.length() == 0) { // sb.append("< 1 minute"); // } // // return sb.toString(); // } // // public static boolean isValidInput(ArrayList<String> list, String value) { // for (String s : list) { // if (s.equalsIgnoreCase(value)) { // return true; // } // } // // return false; // } // // public static boolean getBoolean(String value) { // if (value.equalsIgnoreCase("on") || value.equalsIgnoreCase("true") // || value.equalsIgnoreCase("enable") || value.equalsIgnoreCase("1")) { // return true; // } // // return false; // } // // }
import net.diecode.killermoney.Utils; import java.util.HashMap; import java.util.UUID;
this.permission = permission; this.limit = limit; this.enabled = enabled; } public int getMinAmount() { return minAmount; } public int getMaxAmount() { return maxAmount; } public double getChance() { return chance; } public String getPermission() { return permission; } public int getLimit() { return limit; } public boolean isEnabled() { return enabled; } public boolean chanceGen() {
// Path: src/net/diecode/killermoney/Utils.java // public class Utils { // // public static boolean chanceGenerator(double chance) { // return (Math.random() * 100) < chance; // } // // public static double randomNumber(double min, double max) { // if (min == max) { // return min; // } // // double randomNumber = new Random().nextDouble(); // // if (max > min) { // return min + (max - min) * randomNumber; // } // // if (min > max) { // return max + (min - max) * randomNumber; // } // // return 0; // } // // public static int randomNumber(int min, int max) { // if (min == max) { // return min; // } // // return new Random().nextInt(max - min) + min; // } // // public static boolean inEntityEnum(String entity) { // for (EntityType et : EntityType.values()) { // if (et.name().equalsIgnoreCase(entity)) { // return true; // } // } // // return false; // } // // public static boolean inDivisionEnum(String division) { // for (DivisionMethod div : DivisionMethod.values()) { // if (div.name().equalsIgnoreCase(division)) { // return true; // } // } // // return false; // } // // public static boolean inRunMethodEnum(String runMethod) { // for (RunMethod rm : RunMethod.values()) { // if (rm.name().equalsIgnoreCase(runMethod)) { // return true; // } // } // // return false; // } // // public static double cleanChanceString(String str) { // double chance = Double.valueOf(str.replaceAll("%", "")); // // if (chance > 100) { // chance = 100; // } // // if (chance < 1) { // chance = 1; // } // // return chance; // } // // /* // public static int getMoneyMultiplier(Player p) { // int multiplier = 1; // // for (PermissionAttachmentInfo pai : p.getEffectivePermissions()) { // String perm = pai.getPermission().toLowerCase(); // // if (perm.contains(Permissions.MONEY_MULTIPLIER.getPerm())) { // perm = perm.replace(Permissions.MONEY_MULTIPLIER.getPerm() + ".", ""); // int tmpMultiplier = Integer.valueOf(perm); // // if (tmpMultiplier > multiplier) { // multiplier = tmpMultiplier; // } // } // } // // return multiplier; // } // */ // // public static String getRemainingTimeHumanFormat(int remainingTime) { // final int MINUTES_IN_DAY = 1440; // final int MINUTES_IN_HOUR = 60; // // int minutes = remainingTime; // // int days = minutes / MINUTES_IN_DAY; // minutes = minutes - (days * MINUTES_IN_DAY); // // int hours = minutes / MINUTES_IN_HOUR; // minutes = minutes - (hours * MINUTES_IN_HOUR); // // StringBuilder sb = new StringBuilder(); // // if (days > 0) { // if (days == 1) { // sb.append(days + " day"); // } else { // sb.append(days + " days"); // } // if (hours > 0 || minutes > 0) { // sb.append(", "); // } // } // // if (hours > 0) { // if (hours == 1) { // sb.append(hours + " hour"); // } else { // sb.append(hours + " hours"); // } // if (minutes > 0) { // sb.append(", "); // } // } // // if (minutes > 0) { // if (minutes == 1) { // sb.append(minutes + " minute"); // } else { // sb.append(minutes + " minutes"); // } // } // // if (sb.length() == 0) { // sb.append("< 1 minute"); // } // // return sb.toString(); // } // // public static boolean isValidInput(ArrayList<String> list, String value) { // for (String s : list) { // if (s.equalsIgnoreCase(value)) { // return true; // } // } // // return false; // } // // public static boolean getBoolean(String value) { // if (value.equalsIgnoreCase("on") || value.equalsIgnoreCase("true") // || value.equalsIgnoreCase("enable") || value.equalsIgnoreCase("1")) { // return true; // } // // return false; // } // // } // Path: src/net/diecode/killermoney/objects/CExpProperties.java import net.diecode.killermoney.Utils; import java.util.HashMap; import java.util.UUID; this.permission = permission; this.limit = limit; this.enabled = enabled; } public int getMinAmount() { return minAmount; } public int getMaxAmount() { return maxAmount; } public double getChance() { return chance; } public String getPermission() { return permission; } public int getLimit() { return limit; } public boolean isEnabled() { return enabled; } public boolean chanceGen() {
return Utils.chanceGenerator(this.chance);
diecode/KillerMoney
src/net/diecode/killermoney/managers/EconomyManager.java
// Path: src/net/diecode/killermoney/BukkitMain.java // public class BukkitMain extends JavaPlugin { // // private static BukkitMain instance; // private static Metrics metrics; // // private static Economy economy; // private static MobArenaHandler mobArenaHandler; // private static Updater updater; // // private void initMetrics() { // metrics = new Metrics(this); // metrics.addCustomChart(new Metrics.SimplePie("used_message_method") { // @Override // public String getValue() { // return DefaultConfig.getMessageMethod().name().toUpperCase(); // } // }); // // metrics.addCustomChart(new Metrics.SimplePie("used_money_item_drop") { // @Override // public String getValue() { // return DefaultConfig.isMoneyItemDropEnabled() ? "Enabled" : "Disabled"; // } // }); // } // // private boolean initEconomy() { // RegisteredServiceProvider<Economy> economyProvider = // Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); // // if (economyProvider != null) { // economy = economyProvider.getProvider(); // } // // return (economy != null); // } // // private void hookMobArena() { // if (Bukkit.getPluginManager().getPlugin("MobArena") != null) { // mobArenaHandler = new MobArenaHandler(); // // Logger.info("MobArena hooked"); // } else { // Logger.info("MobArena not found"); // } // } // // @Override // public void onEnable() { // instance = this; // // ConfigManager.init(); // // updater = new Updater(); // // initMetrics(); // // if (!initEconomy()) { // Logger.warning("Vault or economy plugin not found! Money reward disabled."); // } // // if (DefaultConfig.isHookMobArena()) { // hookMobArena(); // } // // getCommand("km").setExecutor(new KMCommand()); // getCommand("kmadmin").setExecutor(new KMAdminCommand()); // // Bukkit.getPluginManager().registerEvents(new EntityManager(), this); // Bukkit.getPluginManager().registerEvents(new MoneyHandler(), this); // Bukkit.getPluginManager().registerEvents(new CItemHandler(), this); // Bukkit.getPluginManager().registerEvents(new CCommandHandler(), this); // Bukkit.getPluginManager().registerEvents(new CExpHandler(), this); // Bukkit.getPluginManager().registerEvents(new MessageHandler(), this); // Bukkit.getPluginManager().registerEvents(new CashTransferHandler(), this); // Bukkit.getPluginManager().registerEvents(new AntiFarmingHandler(), this); // Bukkit.getPluginManager().registerEvents(new LimitHandler(), this); // Bukkit.getPluginManager().registerEvents(new MultiplierHandler(), this); // Bukkit.getPluginManager().registerEvents(new KMPlayerManager(), this); // Bukkit.getPluginManager().registerEvents(updater, this); // // if (DefaultConfig.isCheckUpdate()) { // getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { // @Override // public void run() { // if (!Updater.isUpdateAvailable()) { // updater.query(); // } // } // }, 20L, 20L * 60 * 60 * 24); // } // // for (Player p : Bukkit.getOnlinePlayers()) { // UUID pUUID = p.getUniqueId(); // // if (!KMPlayerManager.getKMPlayers().containsKey(pUUID)) { // KMPlayerManager.getKMPlayers().put(pUUID, new KMPlayer(p)); // } // } // } // // @Override // public void onDisable() { // instance = null; // updater = null; // } // // public static BukkitMain getInstance() { // return instance; // } // // public static Economy getEconomy() { // return economy; // } // // public static MobArenaHandler getMobArenaHandler() { // return mobArenaHandler; // } // }
import net.diecode.killermoney.BukkitMain; import org.bukkit.entity.Player; import java.math.BigDecimal;
package net.diecode.killermoney.managers; public class EconomyManager { public static void deposit(Player player, double amount) {
// Path: src/net/diecode/killermoney/BukkitMain.java // public class BukkitMain extends JavaPlugin { // // private static BukkitMain instance; // private static Metrics metrics; // // private static Economy economy; // private static MobArenaHandler mobArenaHandler; // private static Updater updater; // // private void initMetrics() { // metrics = new Metrics(this); // metrics.addCustomChart(new Metrics.SimplePie("used_message_method") { // @Override // public String getValue() { // return DefaultConfig.getMessageMethod().name().toUpperCase(); // } // }); // // metrics.addCustomChart(new Metrics.SimplePie("used_money_item_drop") { // @Override // public String getValue() { // return DefaultConfig.isMoneyItemDropEnabled() ? "Enabled" : "Disabled"; // } // }); // } // // private boolean initEconomy() { // RegisteredServiceProvider<Economy> economyProvider = // Bukkit.getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); // // if (economyProvider != null) { // economy = economyProvider.getProvider(); // } // // return (economy != null); // } // // private void hookMobArena() { // if (Bukkit.getPluginManager().getPlugin("MobArena") != null) { // mobArenaHandler = new MobArenaHandler(); // // Logger.info("MobArena hooked"); // } else { // Logger.info("MobArena not found"); // } // } // // @Override // public void onEnable() { // instance = this; // // ConfigManager.init(); // // updater = new Updater(); // // initMetrics(); // // if (!initEconomy()) { // Logger.warning("Vault or economy plugin not found! Money reward disabled."); // } // // if (DefaultConfig.isHookMobArena()) { // hookMobArena(); // } // // getCommand("km").setExecutor(new KMCommand()); // getCommand("kmadmin").setExecutor(new KMAdminCommand()); // // Bukkit.getPluginManager().registerEvents(new EntityManager(), this); // Bukkit.getPluginManager().registerEvents(new MoneyHandler(), this); // Bukkit.getPluginManager().registerEvents(new CItemHandler(), this); // Bukkit.getPluginManager().registerEvents(new CCommandHandler(), this); // Bukkit.getPluginManager().registerEvents(new CExpHandler(), this); // Bukkit.getPluginManager().registerEvents(new MessageHandler(), this); // Bukkit.getPluginManager().registerEvents(new CashTransferHandler(), this); // Bukkit.getPluginManager().registerEvents(new AntiFarmingHandler(), this); // Bukkit.getPluginManager().registerEvents(new LimitHandler(), this); // Bukkit.getPluginManager().registerEvents(new MultiplierHandler(), this); // Bukkit.getPluginManager().registerEvents(new KMPlayerManager(), this); // Bukkit.getPluginManager().registerEvents(updater, this); // // if (DefaultConfig.isCheckUpdate()) { // getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { // @Override // public void run() { // if (!Updater.isUpdateAvailable()) { // updater.query(); // } // } // }, 20L, 20L * 60 * 60 * 24); // } // // for (Player p : Bukkit.getOnlinePlayers()) { // UUID pUUID = p.getUniqueId(); // // if (!KMPlayerManager.getKMPlayers().containsKey(pUUID)) { // KMPlayerManager.getKMPlayers().put(pUUID, new KMPlayer(p)); // } // } // } // // @Override // public void onDisable() { // instance = null; // updater = null; // } // // public static BukkitMain getInstance() { // return instance; // } // // public static Economy getEconomy() { // return economy; // } // // public static MobArenaHandler getMobArenaHandler() { // return mobArenaHandler; // } // } // Path: src/net/diecode/killermoney/managers/EconomyManager.java import net.diecode.killermoney.BukkitMain; import org.bukkit.entity.Player; import java.math.BigDecimal; package net.diecode.killermoney.managers; public class EconomyManager { public static void deposit(Player player, double amount) {
BukkitMain.getEconomy().depositPlayer(player, amount);
diecode/KillerMoney
src/net/diecode/killermoney/events/KMLoseMoneyCashTransferEvent.java
// Path: src/net/diecode/killermoney/objects/CashTransferProperties.java // public class CashTransferProperties { // // private double percent; // private int maxAmount; // private double chance; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public CashTransferProperties(double percent, int maxAmount, double chance, String permission, int limit, // DivisionMethod divisionMethod, boolean enabled) { // this.percent = percent; // this.maxAmount = maxAmount; // this.chance = chance; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public double getPercent() { // return percent; // } // // public int getMaxAmount() { // return maxAmount; // } // // public double getChance() { // return chance; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean isEnabled() { // return enabled; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.doubleValue() >= limit) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // } // // Path: src/net/diecode/killermoney/objects/EntityDamage.java // public class EntityDamage { // // private UUID puuid; // private BigDecimal damage; // private BigDecimal calculatedMoney; // // public EntityDamage(UUID puuid, BigDecimal damage) { // this.puuid = puuid; // this.damage = damage; // } // // public EntityDamage(UUID puuid, BigDecimal damage, BigDecimal money) { // this.puuid = puuid; // this.damage = damage; // this.calculatedMoney = money; // } // // public UUID getPlayerUUID() { // return puuid; // } // // public BigDecimal getDamage() { // return damage; // } // // public void increaseDamage(BigDecimal damage) { // this.damage = this.damage.add(damage); // } // // public BigDecimal getCalculatedMoney() { // return calculatedMoney; // } // // public void setCalculatedMoney(BigDecimal calculatedMoney) { // this.calculatedMoney = calculatedMoney; // } // }
import net.diecode.killermoney.objects.CashTransferProperties; import net.diecode.killermoney.objects.EntityDamage; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal; import java.util.ArrayList;
package net.diecode.killermoney.events; public class KMLoseMoneyCashTransferEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
// Path: src/net/diecode/killermoney/objects/CashTransferProperties.java // public class CashTransferProperties { // // private double percent; // private int maxAmount; // private double chance; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public CashTransferProperties(double percent, int maxAmount, double chance, String permission, int limit, // DivisionMethod divisionMethod, boolean enabled) { // this.percent = percent; // this.maxAmount = maxAmount; // this.chance = chance; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public double getPercent() { // return percent; // } // // public int getMaxAmount() { // return maxAmount; // } // // public double getChance() { // return chance; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean isEnabled() { // return enabled; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.doubleValue() >= limit) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // } // // Path: src/net/diecode/killermoney/objects/EntityDamage.java // public class EntityDamage { // // private UUID puuid; // private BigDecimal damage; // private BigDecimal calculatedMoney; // // public EntityDamage(UUID puuid, BigDecimal damage) { // this.puuid = puuid; // this.damage = damage; // } // // public EntityDamage(UUID puuid, BigDecimal damage, BigDecimal money) { // this.puuid = puuid; // this.damage = damage; // this.calculatedMoney = money; // } // // public UUID getPlayerUUID() { // return puuid; // } // // public BigDecimal getDamage() { // return damage; // } // // public void increaseDamage(BigDecimal damage) { // this.damage = this.damage.add(damage); // } // // public BigDecimal getCalculatedMoney() { // return calculatedMoney; // } // // public void setCalculatedMoney(BigDecimal calculatedMoney) { // this.calculatedMoney = calculatedMoney; // } // } // Path: src/net/diecode/killermoney/events/KMLoseMoneyCashTransferEvent.java import net.diecode.killermoney.objects.CashTransferProperties; import net.diecode.killermoney.objects.EntityDamage; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal; import java.util.ArrayList; package net.diecode.killermoney.events; public class KMLoseMoneyCashTransferEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList();
private CashTransferProperties cashTransferProperties;
diecode/KillerMoney
src/net/diecode/killermoney/events/KMLoseMoneyCashTransferEvent.java
// Path: src/net/diecode/killermoney/objects/CashTransferProperties.java // public class CashTransferProperties { // // private double percent; // private int maxAmount; // private double chance; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public CashTransferProperties(double percent, int maxAmount, double chance, String permission, int limit, // DivisionMethod divisionMethod, boolean enabled) { // this.percent = percent; // this.maxAmount = maxAmount; // this.chance = chance; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public double getPercent() { // return percent; // } // // public int getMaxAmount() { // return maxAmount; // } // // public double getChance() { // return chance; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean isEnabled() { // return enabled; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.doubleValue() >= limit) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // } // // Path: src/net/diecode/killermoney/objects/EntityDamage.java // public class EntityDamage { // // private UUID puuid; // private BigDecimal damage; // private BigDecimal calculatedMoney; // // public EntityDamage(UUID puuid, BigDecimal damage) { // this.puuid = puuid; // this.damage = damage; // } // // public EntityDamage(UUID puuid, BigDecimal damage, BigDecimal money) { // this.puuid = puuid; // this.damage = damage; // this.calculatedMoney = money; // } // // public UUID getPlayerUUID() { // return puuid; // } // // public BigDecimal getDamage() { // return damage; // } // // public void increaseDamage(BigDecimal damage) { // this.damage = this.damage.add(damage); // } // // public BigDecimal getCalculatedMoney() { // return calculatedMoney; // } // // public void setCalculatedMoney(BigDecimal calculatedMoney) { // this.calculatedMoney = calculatedMoney; // } // }
import net.diecode.killermoney.objects.CashTransferProperties; import net.diecode.killermoney.objects.EntityDamage; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal; import java.util.ArrayList;
package net.diecode.killermoney.events; public class KMLoseMoneyCashTransferEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private CashTransferProperties cashTransferProperties;
// Path: src/net/diecode/killermoney/objects/CashTransferProperties.java // public class CashTransferProperties { // // private double percent; // private int maxAmount; // private double chance; // private String permission; // private int limit; // private DivisionMethod divisionMethod; // private boolean enabled; // private HashMap<UUID, BigDecimal> limitCounter = new HashMap<UUID, BigDecimal>(); // // public CashTransferProperties(double percent, int maxAmount, double chance, String permission, int limit, // DivisionMethod divisionMethod, boolean enabled) { // this.percent = percent; // this.maxAmount = maxAmount; // this.chance = chance; // this.permission = permission; // this.limit = limit; // this.divisionMethod = divisionMethod; // this.enabled = enabled; // } // // public double getPercent() { // return percent; // } // // public int getMaxAmount() { // return maxAmount; // } // // public double getChance() { // return chance; // } // // public String getPermission() { // return permission; // } // // public int getLimit() { // return limit; // } // // public DivisionMethod getDivisionMethod() { // return divisionMethod; // } // // public HashMap<UUID, BigDecimal> getLimitCounter() { // return limitCounter; // } // // public boolean isEnabled() { // return enabled; // } // // public boolean chanceGen() { // return Utils.chanceGenerator(this.chance); // } // // public boolean isReachedLimit(UUID uuid) { // if (limit < 1) { // return false; // } // // Player player = Bukkit.getPlayer(uuid); // // if (player.hasPermission(KMPermission.BYPASS_MONEY_LIMIT.get())) { // return false; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal current = limitCounter.get(uuid); // // if (current.doubleValue() >= limit) { // return true; // } // } // // return false; // } // // public void increaseLimitCounter(UUID uuid, BigDecimal money) { // if (limit == 0) { // return; // } // // if (limitCounter.containsKey(uuid)) { // BigDecimal incremented = limitCounter.get(uuid).add(money); // // limitCounter.put(uuid, incremented); // } else { // limitCounter.put(uuid, money); // } // } // // public BigDecimal getCurrentLimitValue(UUID uuid) { // if (limitCounter.containsKey(uuid)) { // return limitCounter.get(uuid); // } // // return BigDecimal.ZERO; // } // } // // Path: src/net/diecode/killermoney/objects/EntityDamage.java // public class EntityDamage { // // private UUID puuid; // private BigDecimal damage; // private BigDecimal calculatedMoney; // // public EntityDamage(UUID puuid, BigDecimal damage) { // this.puuid = puuid; // this.damage = damage; // } // // public EntityDamage(UUID puuid, BigDecimal damage, BigDecimal money) { // this.puuid = puuid; // this.damage = damage; // this.calculatedMoney = money; // } // // public UUID getPlayerUUID() { // return puuid; // } // // public BigDecimal getDamage() { // return damage; // } // // public void increaseDamage(BigDecimal damage) { // this.damage = this.damage.add(damage); // } // // public BigDecimal getCalculatedMoney() { // return calculatedMoney; // } // // public void setCalculatedMoney(BigDecimal calculatedMoney) { // this.calculatedMoney = calculatedMoney; // } // } // Path: src/net/diecode/killermoney/events/KMLoseMoneyCashTransferEvent.java import net.diecode.killermoney.objects.CashTransferProperties; import net.diecode.killermoney.objects.EntityDamage; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import java.math.BigDecimal; import java.util.ArrayList; package net.diecode.killermoney.events; public class KMLoseMoneyCashTransferEvent extends Event implements Cancellable { private static final HandlerList handlers = new HandlerList(); private CashTransferProperties cashTransferProperties;
private ArrayList<EntityDamage> damagers;